hexsha
stringlengths
40
40
size
int64
22
2.4M
ext
stringclasses
5 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
260
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
260
max_issues_repo_name
stringlengths
5
109
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
260
max_forks_repo_name
stringlengths
5
109
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
22
2.4M
avg_line_length
float64
5
169k
max_line_length
int64
5
786k
alphanum_fraction
float64
0.06
0.95
matches
listlengths
1
11
9ecb749f868ec0eddc31ea3380f323e5d364d1ef
16,032
h
C
ImplementingARAP09/GeometricTools/GTEngine/Include/Mathematics/GteIntpQuadraticNonuniform2.h
forestsen/ARAPShapeManipulation
459f3fe0ef723711eb65bec16eab08bcb232ed47
[ "Apache-2.0" ]
18
2019-08-04T05:13:50.000Z
2022-02-08T03:15:58.000Z
ImplementingARAP09/GeometricTools/GTEngine/Include/Mathematics/GteIntpQuadraticNonuniform2.h
forestsen/ARAPShapeManipulation
459f3fe0ef723711eb65bec16eab08bcb232ed47
[ "Apache-2.0" ]
1
2020-08-08T02:07:10.000Z
2020-08-08T02:07:10.000Z
ImplementingARAP09/GeometricTools/GTEngine/Include/Mathematics/GteIntpQuadraticNonuniform2.h
forestsen/ARAPShapeManipulation
459f3fe0ef723711eb65bec16eab08bcb232ed47
[ "Apache-2.0" ]
2
2020-05-13T00:20:58.000Z
2021-11-28T08:07:33.000Z
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2019 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.0 (2016/06/19) #pragma once #include <Mathematics/GteDelaunay2.h> #include <Mathematics/GteContScribeCircle2.h> #include <Mathematics/GteDistPointAlignedBox.h> // Quadratic interpolation of a network of triangles whose vertices are of // the form (x,y,f(x,y)). This code is an implementation of the algorithm // found in // // Zoltan J. Cendes and Steven H. Wong, // C1 quadratic interpolation over arbitrary point sets, // IEEE Computer Graphics & Applications, // pp. 8-16, 1987 // // The TriangleMesh interface must support the following: // int GetNumVertices() const; // int GetNumTriangles() const; // Vector2<Real> const* GetVertices() const; // int const* GetIndices() const; // bool GetVertices(int, std::array<Vector2<Real>, 3>&) const; // bool GetIndices(int, std::array<int, 3>&) const; // bool GetAdjacencies(int, std::array<int, 3>&) const; // bool GetBarycentrics(int, Vector2<Real> const&, // std::array<Real, 3>&) const; // int GetContainingTriangle(Vector2<Real> const&) const; namespace gte { template <typename Real, typename TriangleMesh> class IntpQuadraticNonuniform2 { public: // Construction. // // The first constructor requires only F and a measure of the rate of // change of the function values relative to changes in the spatial // variables. The df/dx and df/dy values are estimated at the sample // points using mesh normals and spatialDelta. // // The second constructor requires you to specify function values F and // first-order partial derivative values df/dx and df/dy. IntpQuadraticNonuniform2(TriangleMesh const& mesh, Real const* F, Real spatialDelta); IntpQuadraticNonuniform2(TriangleMesh const& mesh, Real const* F, Real const* FX, Real const* FY); // Quadratic interpolation. The return value is 'true' if and only if the // input point is in the convex hull of the input vertices, in which case // the interpolation is valid. bool operator()(Vector2<Real> const & P, Real& F, Real& FX, Real& FY) const; private: void EstimateDerivatives(Real spatialDelta); void ProcessTriangles(); void ComputeCrossEdgeIntersections(int t); void ComputeCoefficients(int t); class TriangleData { public: Vector2<Real> center; Vector2<Real> intersect[3]; Real coeff[19]; }; class Jet { public: Real F, FX, FY; }; TriangleMesh const* mMesh; Real const* mF; Real const* mFX; Real const* mFY; std::vector<Real> mFXStorage; std::vector<Real> mFYStorage; std::vector<TriangleData> mTData; }; template <typename Real, typename TriangleMesh> IntpQuadraticNonuniform2<Real, TriangleMesh>::IntpQuadraticNonuniform2( TriangleMesh const& mesh, Real const* F, Real spatialDelta) : mMesh(&mesh), mF(F), mFX(nullptr), mFY(nullptr) { EstimateDerivatives(spatialDelta); ProcessTriangles(); } template <typename Real, typename TriangleMesh> IntpQuadraticNonuniform2<Real, TriangleMesh>::IntpQuadraticNonuniform2( TriangleMesh const& mesh, Real const* F, Real const* FX, Real const* FY) : mMesh(&mesh), mF(F), mFX(FX), mFY(FY) { ProcessTriangles(); } template <typename Real, typename TriangleMesh> bool IntpQuadraticNonuniform2<Real, TriangleMesh>::operator()( Vector2<Real> const& P, Real& F, Real& FX, Real& FY) const { int t = mMesh->GetContainingTriangle(P); if (t == -1) { // The point is outside the triangulation. return false; } // Get the vertices of the triangle. std::array<Vector2<Real>, 3> V; mMesh->GetVertices(t, V); // Get the additional information for the triangle. TriangleData const& tData = mTData[t]; // Determine which of the six subtriangles contains the target point. // Theoretically, P must be in one of these subtriangles. Vector2<Real> sub0 = tData.center; Vector2<Real> sub1; Vector2<Real> sub2 = tData.intersect[2]; Vector3<Real> bary; int index; Real const zero = (Real)0, one = (Real)1; AlignedBox3<Real> barybox({ zero, zero, zero }, { one, one, one }); DCPQuery<Real, Vector3<Real>, AlignedBox3<Real>> pbQuery; int minIndex = 0; Real minDistance = (Real)-1; Vector3<Real> minBary; Vector2<Real> minSub0, minSub1, minSub2; for (index = 1; index <= 6; ++index) { sub1 = sub2; if (index % 2) { sub2 = V[index / 2]; } else { sub2 = tData.intersect[index / 2 - 1]; } bool valid = ComputeBarycentrics(P, sub0, sub1, sub2, &bary[0]); if (valid && zero <= bary[0] && bary[0] <= one && zero <= bary[1] && bary[1] <= one && zero <= bary[2] && bary[2] <= one) { // P is in triangle <Sub0,Sub1,Sub2> break; } // When computing with floating-point arithmetic, rounding errors // can cause us to reach this code when, theoretically, the point // is in the subtriangle. Keep track of the (b0,b1,b2) that is // closest to the barycentric cube [0,1]^3 and choose the triangle // corresponding to it when all 6 tests previously fail. Real distance = pbQuery(bary, barybox).distance; if (minIndex == 0 || distance < minDistance) { minDistance = distance; minIndex = index; minBary = bary; minSub0 = sub0; minSub1 = sub1; minSub2 = sub2; } } // If the subtriangle was not found, rounding errors caused problems. // Choose the barycentric point closest to the box. if (index > 6) { index = minIndex; bary = minBary; sub0 = minSub0; sub1 = minSub1; sub2 = minSub2; } // Fetch Bezier control points. Real bez[6] = { tData.coeff[0], tData.coeff[12 + index], tData.coeff[13 + (index % 6)], tData.coeff[index], tData.coeff[6 + index], tData.coeff[1 + (index % 6)] }; // Evaluate Bezier quadratic. F = bary[0] * (bez[0] * bary[0] + bez[1] * bary[1] + bez[2] * bary[2]) + bary[1] * (bez[1] * bary[0] + bez[3] * bary[1] + bez[4] * bary[2]) + bary[2] * (bez[2] * bary[0] + bez[4] * bary[1] + bez[5] * bary[2]); // Evaluate barycentric derivatives of F. Real FU = ((Real)2)*(bez[0] * bary[0] + bez[1] * bary[1] + bez[2] * bary[2]); Real FV = ((Real)2)*(bez[1] * bary[0] + bez[3] * bary[1] + bez[4] * bary[2]); Real FW = ((Real)2)*(bez[2] * bary[0] + bez[4] * bary[1] + bez[5] * bary[2]); Real duw = FU - FW; Real dvw = FV - FW; // Convert back to (x,y) coordinates. Real m00 = sub0[0] - sub2[0]; Real m10 = sub0[1] - sub2[1]; Real m01 = sub1[0] - sub2[0]; Real m11 = sub1[1] - sub2[1]; Real inv = ((Real)1) / (m00*m11 - m10*m01); FX = inv*(m11*duw - m10*dvw); FY = inv*(m00*dvw - m01*duw); return true; } template <typename Real, typename TriangleMesh> void IntpQuadraticNonuniform2<Real, TriangleMesh>::EstimateDerivatives( Real spatialDelta) { int numVertices = mMesh->GetNumVertices(); Vector2<Real> const* vertices = mMesh->GetVertices(); int numTriangles = mMesh->GetNumTriangles(); int const* indices = mMesh->GetIndices(); mFXStorage.resize(numVertices); mFYStorage.resize(numVertices); std::vector<Real> FZ(numVertices); std::fill(mFXStorage.begin(), mFXStorage.end(), (Real)0); std::fill(mFYStorage.begin(), mFYStorage.end(), (Real)0); std::fill(FZ.begin(), FZ.end(), (Real)0); mFX = &mFXStorage[0]; mFY = &mFYStorage[0]; // Accumulate normals at spatial locations (averaging process). for (int t = 0; t < numTriangles; ++t) { // Get three vertices of triangle. int v0 = *indices++; int v1 = *indices++; int v2 = *indices++; // Compute normal vector of triangle (with positive z-component). Real dx1 = vertices[v1][0] - vertices[v0][0]; Real dy1 = vertices[v1][1] - vertices[v0][1]; Real dz1 = mF[v1] - mF[v0]; Real dx2 = vertices[v2][0] - vertices[v0][0]; Real dy2 = vertices[v2][1] - vertices[v0][1]; Real dz2 = mF[v2] - mF[v0]; Real nx = dy1*dz2 - dy2*dz1; Real ny = dz1*dx2 - dz2*dx1; Real nz = dx1*dy2 - dx2*dy1; if (nz < (Real)0) { nx = -nx; ny = -ny; nz = -nz; } mFXStorage[v0] += nx; mFYStorage[v0] += ny; FZ[v0] += nz; mFXStorage[v1] += nx; mFYStorage[v1] += ny; FZ[v1] += nz; mFXStorage[v2] += nx; mFYStorage[v2] += ny; FZ[v2] += nz; } // Scale the normals to form (x,y,-1). for (int i = 0; i < numVertices; ++i) { if (FZ[i] != (Real)0) { Real inv = -spatialDelta / FZ[i]; mFXStorage[i] *= inv; mFYStorage[i] *= inv; } else { mFXStorage[i] = (Real)0; mFYStorage[i] = (Real)0; } } } template <typename Real, typename TriangleMesh> void IntpQuadraticNonuniform2<Real, TriangleMesh>::ProcessTriangles() { // Add degenerate triangles to boundary triangles so that interpolation // at the boundary can be treated in the same way as interpolation in // the interior. // Compute centers of inscribed circles for triangles. Vector2<Real> const* vertices = mMesh->GetVertices(); int numTriangles = mMesh->GetNumTriangles(); int const* indices = mMesh->GetIndices(); mTData.resize(numTriangles); int t; for (t = 0; t < numTriangles; ++t) { int v0 = *indices++; int v1 = *indices++; int v2 = *indices++; Circle2<Real> circle; Inscribe(vertices[v0], vertices[v1], vertices[v2], circle); mTData[t].center = circle.center; } // Compute cross-edge intersections. for (t = 0; t < numTriangles; ++t) { ComputeCrossEdgeIntersections(t); } // Compute Bezier coefficients. for (t = 0; t < numTriangles; ++t) { ComputeCoefficients(t); } } template <typename Real, typename TriangleMesh> void IntpQuadraticNonuniform2<Real, TriangleMesh>:: ComputeCrossEdgeIntersections(int t) { // Get the vertices of the triangle. std::array<Vector2<Real>, 3> V; mMesh->GetVertices(t, V); // Get the centers of adjacent triangles. TriangleData& tData = mTData[t]; std::array<int, 3> adjacencies; mMesh->GetAdjacencies(t, adjacencies); for (int j0 = 2, j1 = 0; j1 < 3; j0 = j1++) { int a = adjacencies[j0]; if (a >= 0) { // Get center of adjacent triangle's inscribing circle. Vector2<Real> U = mTData[a].center; Real m00 = V[j0][1] - V[j1][1]; Real m01 = V[j1][0] - V[j0][0]; Real m10 = tData.center[1] - U[1]; Real m11 = U[0] - tData.center[0]; Real r0 = m00*V[j0][0] + m01*V[j0][1]; Real r1 = m10*tData.center[0] + m11*tData.center[1]; Real invDet = ((Real)1) / (m00*m11 - m01*m10); tData.intersect[j0][0] = (m11*r0 - m01*r1)*invDet; tData.intersect[j0][1] = (m00*r1 - m10*r0)*invDet; } else { // No adjacent triangle, use center of edge. tData.intersect[j0] = ((Real)0.5)*(V[j0] + V[j1]); } } } template <typename Real, typename TriangleMesh> void IntpQuadraticNonuniform2<Real, TriangleMesh>::ComputeCoefficients(int t) { // Get the vertices of the triangle. std::array<Vector2<Real>, 3> V; mMesh->GetVertices(t, V); // Get the additional information for the triangle. TriangleData& tData = mTData[t]; // Get the sample data at main triangle vertices. std::array<int, 3> indices; mMesh->GetIndices(t, indices); Jet jet[3]; for (int j = 0; j < 3; ++j) { int k = indices[j]; jet[j].F = mF[k]; jet[j].FX = mFX[k]; jet[j].FY = mFY[k]; } // Get centers of adjacent triangles. std::array<int, 3> adjacencies; mMesh->GetAdjacencies(t, adjacencies); Vector2<Real> U[3]; for (int j0 = 2, j1 = 0; j1 < 3; j0 = j1++) { int a = adjacencies[j0]; if (a >= 0) { // Get center of adjacent triangle's circumscribing circle. U[j0] = mTData[a].center; } else { // No adjacent triangle, use center of edge. U[j0] = ((Real)0.5)*(V[j0] + V[j1]); } } // Compute intermediate terms. std::array<Real, 3> cenT, cen0, cen1, cen2; mMesh->GetBarycentrics(t, tData.center, cenT); mMesh->GetBarycentrics(t, U[0], cen0); mMesh->GetBarycentrics(t, U[1], cen1); mMesh->GetBarycentrics(t, U[2], cen2); Real alpha = (cenT[1] * cen1[0] - cenT[0] * cen1[1]) / (cen1[0] - cenT[0]); Real beta = (cenT[2] * cen2[1] - cenT[1] * cen2[2]) / (cen2[1] - cenT[1]); Real gamma = (cenT[0] * cen0[2] - cenT[2] * cen0[0]) / (cen0[2] - cenT[2]); Real oneMinusAlpha = (Real)1 - alpha; Real oneMinusBeta = (Real)1 - beta; Real oneMinusGamma = (Real)1 - gamma; Real tmp, A[9], B[9]; tmp = cenT[0] * V[0][0] + cenT[1] * V[1][0] + cenT[2] * V[2][0]; A[0] = ((Real)0.5)*(tmp - V[0][0]); A[1] = ((Real)0.5)*(tmp - V[1][0]); A[2] = ((Real)0.5)*(tmp - V[2][0]); A[3] = ((Real)0.5)*beta*(V[2][0] - V[0][0]); A[4] = ((Real)0.5)*oneMinusGamma*(V[1][0] - V[0][0]); A[5] = ((Real)0.5)*gamma*(V[0][0] - V[1][0]); A[6] = ((Real)0.5)*oneMinusAlpha*(V[2][0] - V[1][0]); A[7] = ((Real)0.5)*alpha*(V[1][0] - V[2][0]); A[8] = ((Real)0.5)*oneMinusBeta*(V[0][0] - V[2][0]); tmp = cenT[0] * V[0][1] + cenT[1] * V[1][1] + cenT[2] * V[2][1]; B[0] = ((Real)0.5)*(tmp - V[0][1]); B[1] = ((Real)0.5)*(tmp - V[1][1]); B[2] = ((Real)0.5)*(tmp - V[2][1]); B[3] = ((Real)0.5)*beta*(V[2][1] - V[0][1]); B[4] = ((Real)0.5)*oneMinusGamma*(V[1][1] - V[0][1]); B[5] = ((Real)0.5)*gamma*(V[0][1] - V[1][1]); B[6] = ((Real)0.5)*oneMinusAlpha*(V[2][1] - V[1][1]); B[7] = ((Real)0.5)*alpha*(V[1][1] - V[2][1]); B[8] = ((Real)0.5)*oneMinusBeta*(V[0][1] - V[2][1]); // Compute Bezier coefficients. tData.coeff[2] = jet[0].F; tData.coeff[4] = jet[1].F; tData.coeff[6] = jet[2].F; tData.coeff[14] = jet[0].F + A[0] * jet[0].FX + B[0] * jet[0].FY; tData.coeff[7] = jet[0].F + A[3] * jet[0].FX + B[3] * jet[0].FY; tData.coeff[8] = jet[0].F + A[4] * jet[0].FX + B[4] * jet[0].FY; tData.coeff[16] = jet[1].F + A[1] * jet[1].FX + B[1] * jet[1].FY; tData.coeff[9] = jet[1].F + A[5] * jet[1].FX + B[5] * jet[1].FY; tData.coeff[10] = jet[1].F + A[6] * jet[1].FX + B[6] * jet[1].FY; tData.coeff[18] = jet[2].F + A[2] * jet[2].FX + B[2] * jet[2].FY; tData.coeff[11] = jet[2].F + A[7] * jet[2].FX + B[7] * jet[2].FY; tData.coeff[12] = jet[2].F + A[8] * jet[2].FX + B[8] * jet[2].FY; tData.coeff[5] = alpha*tData.coeff[10] + oneMinusAlpha*tData.coeff[11]; tData.coeff[17] = alpha*tData.coeff[16] + oneMinusAlpha*tData.coeff[18]; tData.coeff[1] = beta*tData.coeff[12] + oneMinusBeta*tData.coeff[7]; tData.coeff[13] = beta*tData.coeff[18] + oneMinusBeta*tData.coeff[14]; tData.coeff[3] = gamma*tData.coeff[8] + oneMinusGamma*tData.coeff[9]; tData.coeff[15] = gamma*tData.coeff[14] + oneMinusGamma*tData.coeff[16]; tData.coeff[0] = cenT[0] * tData.coeff[14] + cenT[1] * tData.coeff[16] + cenT[2] * tData.coeff[18]; } }
32.785276
78
0.570983
[ "mesh", "vector" ]
9ed0b2a4d21b149cbb7a4987e3ba6f46c151c672
10,501
h
C
iris-fsw-softconsole/include/drivers/protocol/spi.h
aminya/ManitobaSat-Flight-Software
4b08ed168835904fc0e0a942a9b476b4f477f988
[ "Apache-2.0" ]
9
2020-12-29T20:20:36.000Z
2021-11-23T00:17:20.000Z
iris-fsw-softconsole/include/drivers/protocol/spi.h
aminya/ManitobaSat-Flight-Software
4b08ed168835904fc0e0a942a9b476b4f477f988
[ "Apache-2.0" ]
12
2020-11-20T04:57:43.000Z
2021-05-25T17:58:05.000Z
iris-fsw-softconsole/include/drivers/protocol/spi.h
IrisSat/ManitobaSat-Flight-Software
4b08ed168835904fc0e0a942a9b476b4f477f988
[ "Apache-2.0" ]
1
2020-11-23T06:40:54.000Z
2020-11-23T06:40:54.000Z
#ifndef INCLUDE_SPI_H_ #define INCLUDE_SPI_H_ //------------------------------------------------------------------------------------------------------------------------------------------------------------- // File Description: // SPI tasks and functions for SPI masters. // // History // 2019-02-08 by Tamkin Rahman // - Created. // 2019-02-24 by Tamkin Rahman // - Remove the use of mutex within spi.c functions. Instead, the user will have access to the mutexes via the header file. // 2019-03-28 by Tamkin Rahman // - Correct file description. // 2019-04-17 by Tamkin Rahman // - Allow the user to register a GPIO to use as the slave select to avoid toggling the slave select between byte transfers. Also, // add new functions to allow the user to use a GPIO for the slave select. //------------------------------------------------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------------------------------------------------- // INCLUDES //------------------------------------------------------------------------------------------------------------------------------------------------------------- #include <FreeRTOS-Kernel/include/FreeRTOS.h> #include <FreeRTOS-Kernel/include/semphr.h> #include "drivers/CoreSPI/core_spi.h" // Contains the interface for the CoreSPI drivers. #include "drivers/mss_gpio/mss_gpio.h" //------------------------------------------------------------------------------------------------------------------------------------------------------------- // DEFINES //------------------------------------------------------------------------------------------------------------------------------------------------------------- // NOTE: These macros should only be used in FreeRTOS threads. #define WAIT_FOR_CORE(core, delay) ( xSemaphoreTake(core_lock[(core)], (delay)) == pdTRUE ) // Macro for acquiring a FreeRTOS mutex for an SPI core. #define WAIT_FOR_CORE_MAX_DELAY(core) WAIT_FOR_CORE(core, portMAX_DELAY) // Macro for acquiring a FreeRTOS mutex for an SPI core, with a timeout of portMAX_DELAY. #define RELEASE_CORE(core) xSemaphoreGive(core_lock[(core)]) // Macro for releasing a FreeRTOS mutex for an SPI core. #define SPI_BUFF_SIZE 512 //------------------------------------------------------------------------------------------------------------------------------------------------------------- // ENUMS AND ENUM TYPEDEFS //------------------------------------------------------------------------------------------------------------------------------------------------------------- typedef enum { CORE_SPI_0, CORE_SPI_1, CORE_SPI_2, CORE_SPI_3, CORE_SPI_4, CORE_SPI_5, CORE_SPI_6, MSS_SPI_0, NUM_SPI_INSTANCES, } CoreSPIInstance_t; //------------------------------------------------------------------------------------------------------------------------------------------------------------- // EXTERNS //------------------------------------------------------------------------------------------------------------------------------------------------------------- extern SemaphoreHandle_t core_lock[NUM_SPI_INSTANCES]; // Semaphores for the mutex locks. Should only be used in FreeRTOS threads. //------------------------------------------------------------------------------------------------------------------------------------------------------------- // FUNCTION PROTOTYPES //------------------------------------------------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------------------------------------------------------------- // Description: // Initialize the SPI cores. // Note: The fifo length or each CoreSPI peripheral can only be changed in the // Libero project. The fifo lengths must be updated. // in the spi.c file if changed. // // TODO: Check if clock speed can be updated through software. There is no // function in the driver but CoreSPI user guide says this is possible. // // Returns: // 1 on success, 0 on failure. //------------------------------------------------------------------------------------------------------------------------------------------------------------- int init_spi(); //------------------------------------------------------------------------------------------------------------------------------------------------------------- // Description: // Return the object for the SPI instance. An SPI_instance_t object is necessary for using core_spi.h functions. // // Returns: // The object for the given CoreSPI instance. //------------------------------------------------------------------------------------------------------------------------------------------------------------- spi_instance_t * get_spi_instance( CoreSPIInstance_t core // The SPI core (master) to fetch. ); //------------------------------------------------------------------------------------------------------------------------------------------------------------- // Description: // Configure a slave instance. If a slave is not configured, a default configuration is used. //------------------------------------------------------------------------------------------------------------------------------------------------------------- //void spi_configure_slave( // CoreSPIInstance_t core, // The SPI core (master) to use. // spi_slave_t slave, // The SPI slave to configure. // SPI_protocol_mode_t protocol_mode, // The SPI protocol mode. // SPI_pclk_div_t clk_rate, // The SPI clock rate. // SPI_order_t data_xfer_order // The SPI data transfer order (MSB or LSB). // ); //------------------------------------------------------------------------------------------------------------------------------------------------------------- // Description: // Configure a GPIO for use as a slave select. This will initialize the pin, and the slave select pin to inactive. This is for use with functions with // "_without_toggle" at the end. By default, the CoreSPI driver will toggle the slave select between byte transfers, and so this can be added to register a // GPIO pin to use as the slave select instead. //------------------------------------------------------------------------------------------------------------------------------------------------------------- void spi_configure_gpio_ss(mss_gpio_id_t pin); //------------------------------------------------------------------------------------------------------------------------------------------------------------- // Description: // Perform a slave select, send a command, write data to a slave, and then disable the slave select. The slave // select is toggled between each byte transfer. //------------------------------------------------------------------------------------------------------------------------------------------------------------- void spi_transaction_block_write_with_toggle( CoreSPIInstance_t core, // The SPI core used. spi_slave_t slave, // The SPI slave configuration to use. uint8_t * cmd_buffer, // The buffer containing the command. size_t cmd_size, // The size of the command buffer. uint8_t * wr_buffer, // The buffer containing the data to write. size_t wr_size // The size of the write buffer. ); //------------------------------------------------------------------------------------------------------------------------------------------------------------- // Description: // Perform a slave select, send a command, read data from a slave, and then disable the slave select. The slave // select is toggled between each byte transfer. //------------------------------------------------------------------------------------------------------------------------------------------------------------- void spi_transaction_block_read_with_toggle( CoreSPIInstance_t core, // The SPI core used. spi_slave_t slave, // The SPI slave configuration to use. uint8_t * cmd_buffer, // The buffer containing the command. size_t cmd_size, // The size of the command buffer. uint8_t * rd_buffer, // The buffer containing the data to write. size_t rd_size // The size of the write buffer. ); //------------------------------------------------------------------------------------------------------------------------------------------------------------- // Description: // Perform a slave select, send a command, write data to a slave, and then disable the slave select. The slave // select is held low (i.e. not toggled) between each byte transfer. //------------------------------------------------------------------------------------------------------------------------------------------------------------- void spi_transaction_block_write_without_toggle( CoreSPIInstance_t core, // The SPI core used. spi_slave_t slave, // The SPI slave configuration to use. uint8_t * cmd_buffer, // The buffer containing the command. uint16_t cmd_size, // The size of the command buffer. uint8_t * wr_buffer, // The buffer containing the data to write. uint16_t wr_size // The size of the write buffer. ); //------------------------------------------------------------------------------------------------------------------------------------------------------------- // Description: // Perform a slave select, send a command, read data from a slave, and then disable the slave select. The slave // select is held low (i.e. not toggled) between each byte transfer. //------------------------------------------------------------------------------------------------------------------------------------------------------------- void spi_transaction_block_read_without_toggle( CoreSPIInstance_t core, // The SPI core used. spi_slave_t slave, // The SPI slave configuration to use. uint8_t * cmd_buffer, // The buffer containing the command. uint16_t cmd_size, // The size of the command buffer. uint8_t * rd_buffer, // The buffer containing the data to write. uint16_t rd_size // The size of the write buffer. ); #endif /* INCLUDE_SPI_H_ */
64.423313
185
0.407009
[ "object" ]
9ed326d5098c85db1002ce9d7ab16f3bf8ac033a
3,756
h
C
extsrc/mesa/src/gallium/state_trackers/vega/handle.h
MauroArgentino/RSXGL
bd206e11894f309680f48740346c17efe49755ba
[ "BSD-2-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
extsrc/mesa/src/gallium/state_trackers/vega/handle.h
MauroArgentino/RSXGL
bd206e11894f309680f48740346c17efe49755ba
[ "BSD-2-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
extsrc/mesa/src/gallium/state_trackers/vega/handle.h
MauroArgentino/RSXGL
bd206e11894f309680f48740346c17efe49755ba
[ "BSD-2-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
/************************************************************************** * * Copyright 2010 VMware, 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, 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 VMWARE 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. * **************************************************************************/ /** * Convert opaque VG object handles into pointers and vice versa. * XXX This is not yet 64-bit safe! All VG handles are 32 bits in size. */ #ifndef HANDLE_H #define HANDLE_H #include "pipe/p_compiler.h" #include "util/u_hash_table.h" #include "util/u_pointer.h" #include "VG/openvg.h" #include "vg_context.h" extern struct util_hash_table *handle_hash; struct vg_mask_layer; struct vg_font; struct vg_image; struct vg_paint; struct path; extern void init_handles(void); extern void free_handles(void); extern VGHandle create_handle(void *object); extern void destroy_handle(VGHandle h); static INLINE VGHandle object_to_handle(struct vg_object *obj) { return obj ? obj->handle : VG_INVALID_HANDLE; } static INLINE VGHandle image_to_handle(struct vg_image *img) { /* vg_image is derived from vg_object */ return object_to_handle((struct vg_object *) img); } static INLINE VGHandle masklayer_to_handle(struct vg_mask_layer *mask) { /* vg_object is derived from vg_object */ return object_to_handle((struct vg_object *) mask); } static INLINE VGHandle font_to_handle(struct vg_font *font) { return object_to_handle((struct vg_object *) font); } static INLINE VGHandle paint_to_handle(struct vg_paint *paint) { return object_to_handle((struct vg_object *) paint); } static INLINE VGHandle path_to_handle(struct path *path) { return object_to_handle((struct vg_object *) path); } static INLINE void * handle_to_pointer(VGHandle h) { void *v = util_hash_table_get(handle_hash, intptr_to_pointer(h)); #ifdef DEBUG if (v) { struct vg_object *obj = (struct vg_object *) v; assert(obj->handle == h); } #endif return v; } static INLINE struct vg_font * handle_to_font(VGHandle h) { return (struct vg_font *) handle_to_pointer(h); } static INLINE struct vg_image * handle_to_image(VGHandle h) { return (struct vg_image *) handle_to_pointer(h); } static INLINE struct vg_mask_layer * handle_to_masklayer(VGHandle h) { return (struct vg_mask_layer *) handle_to_pointer(h); } static INLINE struct vg_object * handle_to_object(VGHandle h) { return (struct vg_object *) handle_to_pointer(h); } static INLINE struct vg_paint * handle_to_paint(VGHandle h) { return (struct vg_paint *) handle_to_pointer(h); } static INLINE struct path * handle_to_path(VGHandle h) { return (struct path *) handle_to_pointer(h); } #endif /* HANDLE_H */
21.837209
76
0.714856
[ "object" ]
9ed5d858e839852e2f588d0b8028722ec5e835dc
67,935
c
C
src/drivers/ddragon.c
arcadez2003/classic-cades
03ee05187d667493165c5f86accf011fc684a737
[ "RSA-MD" ]
3
2018-03-28T18:10:09.000Z
2018-04-07T01:35:39.000Z
src/drivers/ddragon.c
arcadez2003/classic-cades
03ee05187d667493165c5f86accf011fc684a737
[ "RSA-MD" ]
32
2018-03-25T14:59:12.000Z
2018-04-09T21:14:36.000Z
src/drivers/ddragon.c
arcadez2003/classic-cades
03ee05187d667493165c5f86accf011fc684a737
[ "RSA-MD" ]
1
2018-03-28T16:49:27.000Z
2018-03-28T16:49:27.000Z
/*************************************************************************** Double Dragon (c) 1987 Technos Japan Double Dragon II (c) 1988 Technos Japan Driver by Carlos A. Lozano, Rob Rosenbrock, Phil Stroffolino, Ernesto Corvi Toffy / Super Toffy added by David Haywood Thanks to Bryan McPhail for spotting the Toffy program rom encryption Toffy / Super Toffy sound hooked up by R. Belmont. BM, 8/1/2006: Double Dragon has a crash which sometimes occurs at the very end of the game (right before the final animation sequence). It occurs because of a jump look up table: BAD3: LDY #$BADD BAD7: JSR [A,Y] At the point of the crash A is 0x3e which causes a jump to 0x3401 (background tile ram) which obviously doesn't contain proper code and causes a crash. The jump table has 32 entries, and only the last contains an invalid jump vector. A is set to 0x3e as a result of code at 0x625f - it reads from the shared spriteram (0x2049 in main cpu memory space), copies the value to 0x523 (main ram) where it is later fetched and shifted to make 0x3e. So.. it's not clear where the error is - the 0x1f value is actually written to shared RAM by the main CPU - perhaps the MCU should modify it before the main CPU reads it back? Perhaps 0x1f should never be written at all? If you want to trace this further please submit a proper fix! In the meantime I have patched the error by making sure the invalid jump is never taken - this fixes the crash (see ddragon_spriteram_r). Modifications by Bryan McPhail, June-November 2003: Correct video & interrupt timing derived from Xain schematics and confirmed on real DD board. Corrected interrupt handling, epecially to MCU (but one semi-hack remains). TStrike now boots but sprites don't appear (I had them working at one point, can't remember what broke them again). Dangerous Dungeons fixed. World version of Double Dragon added (actually same roms as the bootleg, but confirmed from real board) Removed stereo audio flag (still on Toffy - does it have it?) todo: banking in Toffy / Super toffy -- Read Me -- Super Toffy - Unico 1994 Main cpu: MC6809EP Sound cpu: MC6809P Sound: YM2151 Clocks: 12 MHz, 3.579MHz Graphics custom: MDE-2001 -- -- Does this make Super Toffy the sequel to a rip-off / bootleg of a conversion kit which could be applied to a bootleg double dragon :-p? ***************************************************************************/ #include "driver.h" #include "cpu/m6800/m6800.h" #include "cpu/m6809/m6809.h" #include "cpu/z80/z80.h" #include "vidhrdw/generic.h" #include "ost_samples.h" /* from vidhrdw */ extern unsigned char *ddragon_bgvideoram,*ddragon_fgvideoram; extern int ddragon_scrollx_hi, ddragon_scrolly_hi; extern unsigned char *ddragon_scrollx_lo; extern unsigned char *ddragon_scrolly_lo; VIDEO_START( ddragon ); VIDEO_UPDATE( ddragon ); WRITE_HANDLER( ddragon_bgvideoram_w ); WRITE_HANDLER( ddragon_fgvideoram_w ); extern unsigned char *ddragon_spriteram; extern int technos_video_hw; /* end of extern code & data */ /* private globals */ static int dd_sub_cpu_busy; static int sprite_irq, sound_irq, ym_irq, snd_cpu; static int adpcm_pos[2],adpcm_end[2],adpcm_idle[2]; static UINT8* darktowr_mcu_ports, *darktowr_ram; static int VBLK; static UINT8 bank_data; /* end of private globals */ static MACHINE_INIT( ddragon ) { sprite_irq = IRQ_LINE_NMI; sound_irq = M6809_IRQ_LINE; ym_irq = M6809_FIRQ_LINE; technos_video_hw = 0; dd_sub_cpu_busy = 0x10; adpcm_idle[0] = adpcm_idle[1] = 1; snd_cpu = 2; } static MACHINE_INIT( toffy ) { sound_irq = M6809_IRQ_LINE; ym_irq = M6809_FIRQ_LINE; technos_video_hw = 0; dd_sub_cpu_busy = 0x10; adpcm_idle[0] = adpcm_idle[1] = 1; snd_cpu = 1; } static MACHINE_INIT( ddragonb ) { sprite_irq = IRQ_LINE_NMI; sound_irq = M6809_IRQ_LINE; ym_irq = M6809_FIRQ_LINE; technos_video_hw = 0; dd_sub_cpu_busy = 0x10; adpcm_idle[0] = adpcm_idle[1] = 1; snd_cpu = 2; } static MACHINE_INIT( ddragon2 ) { sprite_irq = IRQ_LINE_NMI; sound_irq = IRQ_LINE_NMI; ym_irq = 0; technos_video_hw = 2; dd_sub_cpu_busy = 0x10; snd_cpu = 2; } /*****************************************************************************/ static WRITE_HANDLER( ddragon_bankswitch_w ) { UINT8 *RAM = memory_region(REGION_CPU1); ddragon_scrolly_hi = ( ( data & 0x02 ) << 7 ); ddragon_scrollx_hi = ( ( data & 0x01 ) << 8 ); flip_screen_set(~data & 0x04); /* bit 3 unknown */ if (data & 0x10) dd_sub_cpu_busy = 0x00; else if (dd_sub_cpu_busy == 0x00) cpu_set_irq_line( 1, sprite_irq, (sprite_irq == IRQ_LINE_NMI) ? PULSE_LINE : HOLD_LINE ); cpu_setbank( 1,&RAM[ 0x10000 + ( 0x4000 * ( ( data & 0xe0) >> 5 ) ) ] ); bank_data=data; } static WRITE_HANDLER( toffy_bankswitch_w ) { UINT8 *RAM = memory_region(REGION_CPU1); ddragon_scrolly_hi = ( ( data & 0x02 ) << 7 ); ddragon_scrollx_hi = ( ( data & 0x01 ) << 8 ); /* flip_screen_set(~data & 0x04);*/ /* bit 3 unknown */ /* I don't know ... */ cpu_setbank( 1,&RAM[ 0x10000 + ( 0x4000 * ( ( data & 0x20) >> 5 ) ) ] ); } /*****************************************************************************/ static int darktowr_bank=0; static WRITE_HANDLER( darktowr_bankswitch_w ) { ddragon_scrolly_hi = ( ( data & 0x02 ) << 7 ); ddragon_scrollx_hi = ( ( data & 0x01 ) << 8 ); /* flip_screen_set(~data & 0x04);*/ /* bit 3 unknown */ if (data & 0x10) dd_sub_cpu_busy = 0x00; else if (dd_sub_cpu_busy == 0x00) cpu_set_irq_line( 1, sprite_irq, (sprite_irq == IRQ_LINE_NMI) ? PULSE_LINE : HOLD_LINE ); darktowr_bank=(data & 0xe0) >> 5; /* cpu_setbank( 1,&RAM[ 0x10000 + ( 0x4000 * ( ( data & 0xe0) >> 5 ) ) ] );*/ /* log_cb(RETRO_LOG_DEBUG, LOGPRE "Bank %05x %02x %02x\n",activecpu_get_pc(),darktowr_bank,data);*/ } static READ_HANDLER( darktowr_bank_r ) { UINT8 *RAM = memory_region(REGION_CPU1); /* MCU is mapped into main cpu memory as a bank */ if (darktowr_bank==4) { // log_cb(RETRO_LOG_DEBUG, LOGPRE "BankRead %05x %08x\n",activecpu_get_pc(),offset); /* Horrible hack - the alternate TStrike set is mismatched against the MCU, so just hack around the protection here. (The hacks are 'right' as I have the original source code & notes to this version of TStrike to examine). */ if(!strcmp(Machine->gamedrv->name, "tstrike")) { /* Static protection checks at boot-up */ if (activecpu_get_pc()==0x9ace) return 0; if (activecpu_get_pc()==0x9ae4) return 0x63; /* Just return whatever the code is expecting */ return darktowr_ram[0xbe1]; } if (offset==0x1401 || offset==1) { return darktowr_mcu_ports[0]; } log_cb(RETRO_LOG_DEBUG, LOGPRE "Unmapped mcu bank read %04x\n",offset); return 0xff; } return RAM[offset + 0x10000 + (0x4000*darktowr_bank)]; } static WRITE_HANDLER( darktowr_bank_w ) { if (darktowr_bank==4) { log_cb(RETRO_LOG_DEBUG, LOGPRE "BankWrite %05x %08x %08x\n",activecpu_get_pc(),offset,data); if (offset==0x1400 || offset==0) { int bitSwappedData=BITSWAP8(data,0,1,2,3,4,5,6,7); darktowr_mcu_ports[1]=bitSwappedData; log_cb(RETRO_LOG_DEBUG, LOGPRE "MCU PORT 1 -> %04x (from %04x)\n",bitSwappedData,data); return; } return; } log_cb(RETRO_LOG_DEBUG, LOGPRE "ROM write! %04x %02x\n",offset,data); } static READ_HANDLER( darktowr_mcu_r ) { return darktowr_mcu_ports[offset]; } static WRITE_HANDLER( darktowr_mcu_w ) { log_cb(RETRO_LOG_DEBUG, LOGPRE "McuWrite %05x %08x %08x\n",activecpu_get_pc(),offset,data); darktowr_mcu_ports[offset]=data; } /**************************************************************************/ static WRITE_HANDLER( ddragon_interrupt_w ) { switch (offset) { case 0: /* 380b - NMI ack */ cpu_set_nmi_line(0,CLEAR_LINE); break; case 1: /* 380c - FIRQ ack */ cpu_set_irq_line(0,M6809_FIRQ_LINE,CLEAR_LINE); break; case 2: /* 380d - IRQ ack */ cpu_set_irq_line(0,M6809_IRQ_LINE,CLEAR_LINE); break; case 3: /* 380e - SND irq */ if(ddragon_playing && options.use_alt_sound) { if(generate_ost_sound_ddragon( data )) { soundlatch_w( 0, data ); cpu_set_irq_line( snd_cpu, sound_irq, (sound_irq == IRQ_LINE_NMI) ? PULSE_LINE : HOLD_LINE ); } } else { soundlatch_w( 0, data ); cpu_set_irq_line( snd_cpu, sound_irq, (sound_irq == IRQ_LINE_NMI) ? PULSE_LINE : HOLD_LINE ); } break; case 4: /* 380f - ? */ /* Not sure what this is - almost certainly related to the sprite mcu */ break; }; } static READ_HANDLER( ddragon_hd63701_internal_registers_r ) { log_cb(RETRO_LOG_DEBUG, LOGPRE "%04x: read %d\n",activecpu_get_pc(),offset); return 0; } static WRITE_HANDLER( ddragon_hd63701_internal_registers_w ) { /* I don't know why port 0x17 is used.. Doesn't seem to be a standard MCU port */ if (offset==0x17) { /* This is a guess, but makes sense.. The mcu definitely interrupts the main cpu. I don't know what bit is the assert and what is the clear though (in comparison it's quite obvious from the Double Dragon 2 code, below). */ if (data&3) { cpu_set_irq_line(0,M6809_IRQ_LINE,ASSERT_LINE); cpu_set_irq_line(1,sprite_irq, CLEAR_LINE ); } } } static WRITE_HANDLER( ddragon2_sub_irq_ack_w ) { cpu_set_irq_line(1,sprite_irq, CLEAR_LINE ); } static WRITE_HANDLER( ddragon2_sub_irq_w ) { cpu_set_irq_line(0,M6809_IRQ_LINE,ASSERT_LINE); } static READ_HANDLER( port4_r ) { int port = readinputport( 4 ); return port | dd_sub_cpu_busy | VBLK; } static READ_HANDLER( ddragon_spriteram_r ) { /* Double Dragon crash fix - see notes above */ if(strcmp(Machine->gamedrv->name, "ddragon") == 0) { if (offset==0x49 && activecpu_get_pc()==0x6261 && ddragon_spriteram[offset]==0x1f) return 0x1; } return ddragon_spriteram[offset]; } static WRITE_HANDLER( ddragon_spriteram_w ) { if ( cpu_getactivecpu() == 1 && offset == 0 ) dd_sub_cpu_busy = 0x10; ddragon_spriteram[offset] = data; } /*****************************************************************************/ #if 0 static WRITE_HANDLER( cpu_sound_command_w ) { soundlatch_w( offset, data ); cpu_set_irq_line( snd_cpu, sound_irq, (sound_irq == IRQ_LINE_NMI) ? PULSE_LINE : HOLD_LINE ); } #endif static WRITE_HANDLER( dd_adpcm_w ) { int chip = offset & 1; switch (offset/2) { case 3: adpcm_idle[chip] = 1; MSM5205_reset_w(chip,1); break; case 2: adpcm_pos[chip] = (data & 0x7f) * 0x200; break; case 1: adpcm_end[chip] = (data & 0x7f) * 0x200; break; case 0: adpcm_idle[chip] = 0; MSM5205_reset_w(chip,0); break; } } static void dd_adpcm_int(int chip) { static int adpcm_data[2] = { -1, -1 }; if (adpcm_pos[chip] >= adpcm_end[chip] || adpcm_pos[chip] >= 0x10000) { adpcm_idle[chip] = 1; MSM5205_reset_w(chip,1); } else if (adpcm_data[chip] != -1) { MSM5205_data_w(chip,adpcm_data[chip] & 0x0f); adpcm_data[chip] = -1; } else { UINT8 *ROM = memory_region(REGION_SOUND1) + 0x10000 * chip; adpcm_data[chip] = ROM[adpcm_pos[chip]++]; MSM5205_data_w(chip,adpcm_data[chip] >> 4); } } static READ_HANDLER( dd_adpcm_status_r ) { return adpcm_idle[0] + (adpcm_idle[1] << 1); } /*****************************************************************************/ static MEMORY_READ_START( readmem ) { 0x0000, 0x1fff, MRA_RAM }, { 0x2000, 0x2fff, ddragon_spriteram_r }, { 0x3000, 0x37ff, MRA_RAM }, { 0x3800, 0x3800, input_port_0_r }, { 0x3801, 0x3801, input_port_1_r }, { 0x3802, 0x3802, port4_r }, { 0x3803, 0x3803, input_port_2_r }, { 0x3804, 0x3804, input_port_3_r }, { 0x4000, 0x7fff, MRA_BANK1 }, { 0x8000, 0xffff, MRA_ROM }, MEMORY_END static MEMORY_WRITE_START( writemem ) { 0x0000, 0x0fff, MWA_RAM }, { 0x1000, 0x11ff, paletteram_xxxxBBBBGGGGRRRR_split1_w, &paletteram }, { 0x1200, 0x13ff, paletteram_xxxxBBBBGGGGRRRR_split2_w, &paletteram_2 }, { 0x1400, 0x17ff, MWA_RAM }, { 0x1800, 0x1fff, ddragon_fgvideoram_w, &ddragon_fgvideoram }, { 0x2000, 0x2fff, ddragon_spriteram_w, &ddragon_spriteram }, { 0x3000, 0x37ff, ddragon_bgvideoram_w, &ddragon_bgvideoram }, { 0x3808, 0x3808, ddragon_bankswitch_w }, { 0x3809, 0x3809, MWA_RAM, &ddragon_scrollx_lo }, { 0x380a, 0x380a, MWA_RAM, &ddragon_scrolly_lo }, { 0x380b, 0x380f, ddragon_interrupt_w }, { 0x4000, 0xffff, MWA_ROM }, MEMORY_END static MEMORY_READ_START( darktowr_readmem ) { 0x0000, 0x1fff, MRA_RAM }, { 0x2000, 0x2fff, ddragon_spriteram_r }, { 0x3000, 0x37ff, MRA_RAM }, { 0x3800, 0x3800, input_port_0_r }, { 0x3801, 0x3801, input_port_1_r }, { 0x3802, 0x3802, port4_r }, { 0x3803, 0x3803, input_port_2_r }, { 0x3804, 0x3804, input_port_3_r }, { 0x4000, 0x7fff, darktowr_bank_r }, { 0x8000, 0xffff, MRA_ROM }, MEMORY_END static MEMORY_WRITE_START( darktowr_writemem ) { 0x0000, 0x0fff, MWA_RAM, &darktowr_ram }, { 0x1000, 0x11ff, paletteram_xxxxBBBBGGGGRRRR_split1_w, &paletteram }, { 0x1200, 0x13ff, paletteram_xxxxBBBBGGGGRRRR_split2_w, &paletteram_2 }, { 0x1400, 0x17ff, MWA_RAM }, { 0x1800, 0x1fff, ddragon_fgvideoram_w, &ddragon_fgvideoram }, { 0x2000, 0x2fff, ddragon_spriteram_w, &ddragon_spriteram }, { 0x3000, 0x37ff, ddragon_bgvideoram_w, &ddragon_bgvideoram }, { 0x3808, 0x3808, darktowr_bankswitch_w }, { 0x3809, 0x3809, MWA_RAM, &ddragon_scrollx_lo }, { 0x380a, 0x380a, MWA_RAM, &ddragon_scrolly_lo }, { 0x380b, 0x380f, ddragon_interrupt_w }, { 0x4000, 0x7fff, darktowr_bank_w }, { 0x8000, 0xffff, MWA_ROM }, MEMORY_END static MEMORY_READ_START( dd2_readmem ) { 0x0000, 0x1fff, MRA_RAM }, { 0x2000, 0x2fff, ddragon_spriteram_r }, { 0x3000, 0x37ff, MRA_RAM }, { 0x3800, 0x3800, input_port_0_r }, { 0x3801, 0x3801, input_port_1_r }, { 0x3802, 0x3802, port4_r }, { 0x3803, 0x3803, input_port_2_r }, { 0x3804, 0x3804, input_port_3_r }, { 0x3c00, 0x3fff, MRA_RAM }, { 0x4000, 0x7fff, MRA_BANK1 }, { 0x8000, 0xffff, MRA_ROM }, MEMORY_END static MEMORY_WRITE_START( dd2_writemem ) { 0x0000, 0x17ff, MWA_RAM }, { 0x1800, 0x1fff, ddragon_fgvideoram_w, &ddragon_fgvideoram }, { 0x2000, 0x2fff, ddragon_spriteram_w, &ddragon_spriteram }, { 0x3000, 0x37ff, ddragon_bgvideoram_w, &ddragon_bgvideoram }, { 0x3808, 0x3808, ddragon_bankswitch_w }, { 0x3809, 0x3809, MWA_RAM, &ddragon_scrollx_lo }, { 0x380a, 0x380a, MWA_RAM, &ddragon_scrolly_lo }, { 0x380b, 0x380f, ddragon_interrupt_w }, { 0x3c00, 0x3dff, paletteram_xxxxBBBBGGGGRRRR_split1_w, &paletteram }, { 0x3e00, 0x3fff, paletteram_xxxxBBBBGGGGRRRR_split2_w, &paletteram_2 }, { 0x4000, 0xffff, MWA_ROM }, MEMORY_END static MEMORY_WRITE_START( toffy_writemem ) { 0x0000, 0x0fff, MWA_RAM }, { 0x1000, 0x11ff, paletteram_xxxxBBBBGGGGRRRR_split1_w, &paletteram }, { 0x1200, 0x13ff, paletteram_xxxxBBBBGGGGRRRR_split2_w, &paletteram_2 }, { 0x1400, 0x17ff, MWA_RAM }, { 0x1800, 0x1fff, ddragon_fgvideoram_w, &ddragon_fgvideoram }, { 0x2000, 0x2fff, ddragon_spriteram_w, &ddragon_spriteram }, { 0x3000, 0x37ff, ddragon_bgvideoram_w, &ddragon_bgvideoram }, { 0x3808, 0x3808, toffy_bankswitch_w }, { 0x3809, 0x3809, MWA_RAM, &ddragon_scrollx_lo }, { 0x380a, 0x380a, MWA_RAM, &ddragon_scrolly_lo }, { 0x380b, 0x380f, ddragon_interrupt_w }, { 0x4000, 0xffff, MWA_ROM }, MEMORY_END static MEMORY_READ_START( sub_readmem ) { 0x0000, 0x001f, ddragon_hd63701_internal_registers_r }, { 0x001f, 0x0fff, MRA_RAM }, { 0x8000, 0x8fff, ddragon_spriteram_r }, { 0xc000, 0xffff, MRA_ROM }, MEMORY_END static MEMORY_WRITE_START( sub_writemem ) { 0x0000, 0x001f, ddragon_hd63701_internal_registers_w }, { 0x001f, 0x0fff, MWA_RAM }, { 0x8000, 0x8fff, ddragon_spriteram_w }, { 0xc000, 0xffff, MWA_ROM }, MEMORY_END static MEMORY_READ_START( sound_readmem ) { 0x0000, 0x0fff, MRA_RAM }, { 0x1000, 0x1000, soundlatch_r }, { 0x1800, 0x1800, dd_adpcm_status_r }, { 0x2800, 0x2801, YM2151_status_port_0_r }, { 0x8000, 0xffff, MRA_ROM }, MEMORY_END static MEMORY_WRITE_START( sound_writemem ) { 0x0000, 0x0fff, MWA_RAM }, { 0x2800, 0x2800, YM2151_register_port_0_w }, { 0x2801, 0x2801, YM2151_data_port_0_w }, { 0x3800, 0x3807, dd_adpcm_w }, { 0x8000, 0xffff, MWA_ROM }, MEMORY_END static MEMORY_READ_START( dd2_sub_readmem ) { 0x0000, 0xbfff, MRA_ROM }, { 0xc000, 0xc3ff, ddragon_spriteram_r }, MEMORY_END static MEMORY_WRITE_START( dd2_sub_writemem ) { 0x0000, 0xbfff, MWA_ROM }, { 0xc000, 0xc3ff, ddragon_spriteram_w }, { 0xd000, 0xd000, ddragon2_sub_irq_ack_w }, { 0xe000, 0xe000, ddragon2_sub_irq_w }, MEMORY_END static MEMORY_READ_START( dd2_sound_readmem ) { 0x0000, 0x7fff, MRA_ROM }, { 0x8000, 0x87ff, MRA_RAM }, { 0x8801, 0x8801, YM2151_status_port_0_r }, { 0x9800, 0x9800, OKIM6295_status_0_r }, { 0xA000, 0xA000, soundlatch_r }, MEMORY_END static MEMORY_WRITE_START( dd2_sound_writemem ) { 0x0000, 0x7fff, MWA_ROM }, { 0x8000, 0x87ff, MWA_RAM }, { 0x8800, 0x8800, YM2151_register_port_0_w }, { 0x8801, 0x8801, YM2151_data_port_0_w }, { 0x9800, 0x9800, OKIM6295_data_0_w }, MEMORY_END static MEMORY_READ_START( mcu_readmem ) { 0x0000, 0x0007, darktowr_mcu_r }, { 0x0008, 0x007f, MRA_RAM }, { 0x0080, 0x07ff, MRA_ROM }, MEMORY_END static MEMORY_WRITE_START( mcu_writemem ) { 0x0000, 0x0007, darktowr_mcu_w, &darktowr_mcu_ports }, { 0x0008, 0x007f, MWA_RAM }, { 0x0080, 0x07ff, MWA_ROM }, MEMORY_END /*****************************************************************************/ #define COMMON_PORT4 PORT_START \ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_SERVICE1 ) \ PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON3 ) \ PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 | IPF_PLAYER2 ) \ PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_SPECIAL ) /* Vblank verified to be active high (palette fades in ddragon2) */ \ PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_SPECIAL ) /* sub cpu busy */ \ PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN ) \ PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) \ PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN ) #define COMMON_INPUT_DIP1 PORT_START /* DSW0 */ \ PORT_DIPNAME( 0x07, 0x07, DEF_STR( Coin_A ) ) \ PORT_DIPSETTING( 0x00, DEF_STR( 4C_1C ) ) \ PORT_DIPSETTING( 0x01, DEF_STR( 3C_1C ) ) \ PORT_DIPSETTING( 0x02, DEF_STR( 2C_1C ) ) \ PORT_DIPSETTING( 0x07, DEF_STR( 1C_1C ) ) \ PORT_DIPSETTING( 0x06, DEF_STR( 1C_2C ) ) \ PORT_DIPSETTING( 0x05, DEF_STR( 1C_3C ) ) \ PORT_DIPSETTING( 0x04, DEF_STR( 1C_4C ) ) \ PORT_DIPSETTING( 0x03, DEF_STR( 1C_5C ) ) \ PORT_DIPNAME( 0x38, 0x38, DEF_STR( Coin_B ) ) \ PORT_DIPSETTING( 0x00, DEF_STR( 4C_1C ) ) \ PORT_DIPSETTING( 0x08, DEF_STR( 3C_1C ) ) \ PORT_DIPSETTING( 0x10, DEF_STR( 2C_1C ) ) \ PORT_DIPSETTING( 0x38, DEF_STR( 1C_1C ) ) \ PORT_DIPSETTING( 0x30, DEF_STR( 1C_2C ) ) \ PORT_DIPSETTING( 0x28, DEF_STR( 1C_3C ) ) \ PORT_DIPSETTING( 0x20, DEF_STR( 1C_4C ) ) \ PORT_DIPSETTING( 0x18, DEF_STR( 1C_5C ) ) \ PORT_DIPNAME( 0x40, 0x40, DEF_STR( Cabinet ) ) \ PORT_DIPSETTING( 0x40, DEF_STR( Upright ) ) \ PORT_DIPSETTING( 0x00, DEF_STR( Cocktail ) ) \ PORT_DIPNAME( 0x80, 0x80, DEF_STR( Flip_Screen ) ) \ PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) \ PORT_DIPSETTING( 0x00, DEF_STR( On ) ) #define COMMON_INPUT_DIP2 PORT_START /* DSW0 */ \ PORT_DIPNAME( 0x0f, 0x00, DEF_STR( Coin_A ) ) \ PORT_DIPSETTING( 0x03, DEF_STR( 4C_1C ) ) \ PORT_DIPSETTING( 0x02, DEF_STR( 3C_1C ) ) \ PORT_DIPSETTING( 0x07, DEF_STR( 4C_2C ) ) \ PORT_DIPSETTING( 0x01, DEF_STR( 2C_1C ) ) \ PORT_DIPSETTING( 0x06, DEF_STR( 3C_2C ) ) \ PORT_DIPSETTING( 0x0b, DEF_STR( 4C_3C ) ) \ PORT_DIPSETTING( 0x0f, DEF_STR( 4C_4C ) ) \ PORT_DIPSETTING( 0x0a, DEF_STR( 3C_3C ) ) \ PORT_DIPSETTING( 0x05, DEF_STR( 2C_2C ) ) \ PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) ) \ PORT_DIPSETTING( 0x0e, DEF_STR( 3C_4C ) ) \ PORT_DIPSETTING( 0x09, DEF_STR( 2C_3C ) ) \ PORT_DIPSETTING( 0x0d, DEF_STR( 2C_4C ) ) \ PORT_DIPSETTING( 0x04, DEF_STR( 1C_2C ) ) \ PORT_DIPSETTING( 0x08, DEF_STR( 1C_3C ) ) \ PORT_DIPSETTING( 0x0c, DEF_STR( 1C_4C ) ) \ PORT_DIPNAME( 0xf0, 0x00, DEF_STR( Coin_B ) ) \ PORT_DIPSETTING( 0x30, DEF_STR( 4C_1C ) ) \ PORT_DIPSETTING( 0x20, DEF_STR( 3C_1C ) ) \ PORT_DIPSETTING( 0x70, DEF_STR( 4C_2C ) ) \ PORT_DIPSETTING( 0x10, DEF_STR( 2C_1C ) ) \ PORT_DIPSETTING( 0x60, DEF_STR( 3C_2C ) ) \ PORT_DIPSETTING( 0xb0, DEF_STR( 4C_3C ) ) \ PORT_DIPSETTING( 0xf0, DEF_STR( 4C_4C ) ) \ PORT_DIPSETTING( 0xa0, DEF_STR( 3C_3C ) ) \ PORT_DIPSETTING( 0x50, DEF_STR( 2C_2C ) ) \ PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) ) \ PORT_DIPSETTING( 0xe0, DEF_STR( 3C_4C ) ) \ PORT_DIPSETTING( 0x90, DEF_STR( 2C_3C ) ) \ PORT_DIPSETTING( 0xd0, DEF_STR( 2C_4C ) ) \ PORT_DIPSETTING( 0x40, DEF_STR( 1C_2C ) ) \ PORT_DIPSETTING( 0x80, DEF_STR( 1C_3C ) ) \ PORT_DIPSETTING( 0xc0, DEF_STR( 1C_4C ) ) #define COMMON_INPUT_PORTS PORT_START \ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY ) \ PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY ) \ PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY ) \ PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY ) \ PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) \ PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) \ PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_START1 ) \ PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START2 ) \ PORT_START \ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_PLAYER2 ) \ PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_PLAYER2 ) \ PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_PLAYER2 ) \ PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_PLAYER2 ) \ PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2 ) \ PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER2 ) \ PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN1 ) \ PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_COIN2 ) INPUT_PORTS_START( darktowr ) COMMON_INPUT_PORTS COMMON_INPUT_DIP2 PORT_START /* DSW1 */ PORT_DIPNAME( 0x01, 0x01, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x01, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x02, 0x02, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x02, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x04, 0x04, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x04, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x08, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x10, 0x10, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x10, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x20, 0x20, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x20, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x40, 0x40, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x40, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x80, 0x80, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) COMMON_PORT4 INPUT_PORTS_END INPUT_PORTS_START( tstrike ) COMMON_INPUT_PORTS COMMON_INPUT_DIP1 PORT_START //DSW1 PORT_DIPNAME( 0x01, 0x01, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x01, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x02, 0x02, DEF_STR( Unknown ) ) PORT_DIPSETTING( 0x02, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Difficulty ) ) PORT_DIPSETTING( 0x0c, "Easy" ) PORT_DIPSETTING( 0x08, "Normal" ) PORT_DIPSETTING( 0x04, "Hard" ) PORT_DIPSETTING( 0x00, "Hardest" ) PORT_DIPNAME( 0x30, 0x30, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x30, "1" ) PORT_DIPSETTING( 0x20, "2" ) PORT_DIPSETTING( 0x10, "3" ) PORT_DIPSETTING( 0x00, "4" ) PORT_DIPNAME( 0xc0, 0xc0, DEF_STR( Bonus_Life ) ) PORT_DIPSETTING( 0xc0, "100k and 200k" ) PORT_DIPSETTING( 0x80, "200k and 300k" ) PORT_DIPSETTING( 0x40, "300k and 400k" ) PORT_DIPSETTING( 0x00, "400k and 500k" ) COMMON_PORT4 INPUT_PORTS_END INPUT_PORTS_START( ddragon ) COMMON_INPUT_PORTS COMMON_INPUT_DIP1 PORT_START /* DSW1 */ PORT_DIPNAME( 0x03, 0x03, DEF_STR( Difficulty ) ) PORT_DIPSETTING( 0x01, "Easy" ) PORT_DIPSETTING( 0x03, "Medium" ) PORT_DIPSETTING( 0x02, "Hard" ) PORT_DIPSETTING( 0x00, "Hardest" ) PORT_DIPNAME( 0x04, 0x04, DEF_STR( Demo_Sounds ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x04, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unused ) ) PORT_DIPSETTING( 0x08, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x30, 0x30, DEF_STR( Bonus_Life ) ) PORT_DIPSETTING( 0x10, "20k" ) PORT_DIPSETTING( 0x00, "40k" ) PORT_DIPSETTING( 0x30, "30k and every 60k" ) PORT_DIPSETTING( 0x20, "40k and every 80k" ) PORT_DIPNAME( 0xc0, 0xc0, DEF_STR( Lives ) ) PORT_DIPSETTING( 0xc0, "2" ) PORT_DIPSETTING( 0x80, "3" ) PORT_DIPSETTING( 0x40, "4" ) PORT_BITX( 0, 0x00, IPT_DIPSWITCH_SETTING | IPF_CHEAT, "Infinite", IP_KEY_NONE, IP_JOY_NONE ) COMMON_PORT4 INPUT_PORTS_END INPUT_PORTS_START( ddragon2 ) COMMON_INPUT_PORTS COMMON_INPUT_DIP1 PORT_START /* DSW1 */ PORT_DIPNAME( 0x03, 0x03, DEF_STR( Difficulty ) ) PORT_DIPSETTING( 0x01, "Easy" ) PORT_DIPSETTING( 0x03, "Medium" ) PORT_DIPSETTING( 0x02, "Hard" ) PORT_DIPSETTING( 0x00, "Hardest" ) PORT_DIPNAME( 0x04, 0x04, DEF_STR( Demo_Sounds ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x04, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x08, "Hurricane Kick" ) PORT_DIPSETTING( 0x00, "Easy" ) PORT_DIPSETTING( 0x08, "Normal" ) PORT_DIPNAME( 0x30, 0x30, "Timer" ) PORT_DIPSETTING( 0x00, "60" ) PORT_DIPSETTING( 0x10, "65" ) PORT_DIPSETTING( 0x30, "70" ) PORT_DIPSETTING( 0x20, "80" ) PORT_DIPNAME( 0xc0, 0xc0, DEF_STR( Lives ) ) PORT_DIPSETTING( 0xc0, "1" ) PORT_DIPSETTING( 0x80, "2" ) PORT_DIPSETTING( 0x40, "3" ) PORT_DIPSETTING( 0x00, "4" ) COMMON_PORT4 INPUT_PORTS_END INPUT_PORTS_START( ddungeon ) COMMON_INPUT_PORTS COMMON_INPUT_DIP2 PORT_START /* DSW1 */ PORT_DIPNAME( 0x03, 0x01, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x00, "1" ) PORT_DIPSETTING( 0x01, "2" ) PORT_DIPSETTING( 0x02, "3" ) PORT_DIPSETTING( 0x03, "4" ) PORT_DIPNAME( 0x04, 0x04, DEF_STR( Unused ) ) PORT_DIPSETTING( 0x04, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0x08, 0x08, DEF_STR( Unused ) ) PORT_DIPSETTING( 0x08, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_DIPNAME( 0xf0, 0x90, DEF_STR( Difficulty ) ) PORT_DIPSETTING( 0xf0, "Easy" ) PORT_DIPSETTING( 0x90, "Medium" ) PORT_DIPSETTING( 0x70, "Hard" ) PORT_DIPSETTING( 0x00, "Hardest" ) COMMON_PORT4 INPUT_PORTS_END INPUT_PORTS_START( toffy ) COMMON_INPUT_PORTS PORT_START PORT_DIPNAME( 0x0f, 0x00, DEF_STR( Coin_A ) ) PORT_DIPSETTING( 0x03, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x02, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x07, DEF_STR( 4C_2C ) ) PORT_DIPSETTING( 0x01, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x06, DEF_STR( 3C_2C ) ) PORT_DIPSETTING( 0x05, DEF_STR( 2C_2C ) ) PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x0b, DEF_STR( 4C_5C ) ) PORT_DIPSETTING( 0x0f, "4 Coin/6 Credits" ) PORT_DIPSETTING( 0x0a, "3 Coin/5 Credits" ) PORT_DIPSETTING( 0x04, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x0e, "3 Coin/6 Credits" ) PORT_DIPSETTING( 0x09, DEF_STR( 2C_5C ) ) PORT_DIPSETTING( 0x0d, DEF_STR( 2C_6C ) ) PORT_DIPSETTING( 0x08, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0x0c, DEF_STR( 1C_6C ) ) PORT_DIPNAME( 0xf0, 0x00, DEF_STR( Coin_B ) ) PORT_DIPSETTING( 0x30, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x20, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x70, DEF_STR( 4C_2C ) ) PORT_DIPSETTING( 0x10, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x60, DEF_STR( 3C_2C ) ) PORT_DIPSETTING( 0x50, DEF_STR( 2C_2C ) ) PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0xb0, DEF_STR( 4C_5C ) ) PORT_DIPSETTING( 0xf0, "4 Coin/6 Credits" ) PORT_DIPSETTING( 0xa0, "3 Coin/5 Credits" ) PORT_DIPSETTING( 0x40, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0xe0, "3 Coin/6 Credits" ) PORT_DIPSETTING( 0x90, DEF_STR( 2C_5C ) ) PORT_DIPSETTING( 0xd0, DEF_STR( 2C_6C ) ) PORT_DIPSETTING( 0x80, DEF_STR( 1C_5C ) ) PORT_DIPSETTING( 0xc0, DEF_STR( 1C_6C ) ) PORT_START PORT_DIPNAME( 0x03, 0x01, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x00, "2" ) PORT_DIPSETTING( 0x01, "3" ) PORT_DIPSETTING( 0x02, "4" ) PORT_DIPSETTING( 0x03, "5" ) PORT_DIPNAME( 0x04, 0x00, DEF_STR( Unused ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x04, DEF_STR( On ) ) PORT_DIPNAME( 0x18, 0x08, DEF_STR( Bonus_Life ) ) PORT_DIPSETTING( 0x10, "30k, 50k and 100k" ) PORT_DIPSETTING( 0x08, "50k and 100k" ) PORT_DIPSETTING( 0x18, "100k and 200k" ) PORT_DIPSETTING( 0x00, "None" ) PORT_DIPNAME( 0x20, 0x00, DEF_STR( Unused ) ) PORT_DIPSETTING( 0x00, DEF_STR( Off ) ) PORT_DIPSETTING( 0x20, DEF_STR( On ) ) PORT_DIPNAME( 0xc0, 0x80, DEF_STR( Difficulty ) ) PORT_DIPSETTING( 0xc0, "Easy" ) PORT_DIPSETTING( 0x80, "Normal" ) PORT_DIPSETTING( 0x40, "Hard" ) PORT_DIPSETTING( 0x00, "Hardest" ) COMMON_PORT4 INPUT_PORTS_END #undef COMMON_INPUT_PORTS #undef COMMON_INPUT_DIP2 #undef COMMON_INPUT_DIP1 #undef COMMON_PORT4 /*****************************************************************************/ static struct GfxLayout char_layout = { 8,8, RGN_FRAC(1,1), 4, { 0, 2, 4, 6 }, { 1, 0, 8*8+1, 8*8+0, 16*8+1, 16*8+0, 24*8+1, 24*8+0 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 }, 32*8 }; static struct GfxLayout tile_layout = { 16,16, RGN_FRAC(1,2), 4, { RGN_FRAC(1,2)+0, RGN_FRAC(1,2)+4, 0, 4 }, { 3, 2, 1, 0, 16*8+3, 16*8+2, 16*8+1, 16*8+0, 32*8+3, 32*8+2, 32*8+1, 32*8+0, 48*8+3, 48*8+2, 48*8+1, 48*8+0 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8 }, 64*8 }; static struct GfxDecodeInfo gfxdecodeinfo[] = { { REGION_GFX1, 0, &char_layout, 0, 8 }, /* colors 0-127 */ { REGION_GFX2, 0, &tile_layout, 128, 8 }, /* colors 128-255 */ { REGION_GFX3, 0, &tile_layout, 256, 8 }, /* colors 256-383 */ { -1 } }; /*****************************************************************************/ static void irq_handler(int irq) { cpu_set_irq_line( snd_cpu, ym_irq , irq ? ASSERT_LINE : CLEAR_LINE ); } static struct YM2151interface ym2151_interface = { 1, /* 1 chip */ 3579545, /* ??? */ { YM3012_VOL(60,MIXER_PAN_LEFT,60,MIXER_PAN_RIGHT) }, { irq_handler } }; static struct MSM5205interface msm5205_interface = { 2, /* 2 chips */ 384000, /* 384KHz */ { dd_adpcm_int, dd_adpcm_int },/* interrupt function */ { MSM5205_S48_4B, MSM5205_S48_4B }, /* 8kHz */ { 40, 40 } /* volume */ }; static struct OKIM6295interface okim6295_interface = { 1, /* 1 chip */ { 8000 }, /* frequency (Hz) */ { REGION_SOUND1 }, /* memory region */ { 15 } }; static INTERRUPT_GEN( ddragon_interrupt ) { int scanline=271 - cpu_getiloops(); /* VBLK is lowered on scanline 0 */ if (scanline==0) { VBLK=0; } /* VBLK is raised on scanline 240 and NMI line is pulled high */ if (scanline==240) { force_partial_update(scanline); cpu_set_nmi_line(0,ASSERT_LINE); VBLK=0x8; } /* IMS is triggered every time VPOS line 3 is raised, as VPOS counter starts at 16, effectively every 16 scanlines */ if ((scanline%16)==7) { force_partial_update(scanline); cpu_set_irq_line(0,M6809_FIRQ_LINE,ASSERT_LINE); } } static MACHINE_DRIVER_START( ddragon ) /* basic machine hardware */ MDRV_CPU_ADD(HD6309, 3579545) /* 3.579545 MHz */ MDRV_CPU_MEMORY(readmem,writemem) MDRV_CPU_VBLANK_INT(ddragon_interrupt,272) MDRV_CPU_ADD(HD63701,3579545 / 3) /* This divider seems correct by comparison to real board */ MDRV_CPU_MEMORY(sub_readmem,sub_writemem) MDRV_CPU_ADD(HD6309, 3579545) MDRV_CPU_FLAGS(CPU_AUDIO_CPU) MDRV_CPU_MEMORY(sound_readmem,sound_writemem) MDRV_FRAMES_PER_SECOND(((12000000.0 / 256.0) / 3.0) / 272.0) MDRV_VBLANK_DURATION(0) MDRV_INTERLEAVE(100) /* heavy interleaving to sync up sprite<->main cpu's */ MDRV_MACHINE_INIT(ddragon) /* video hardware */ MDRV_VIDEO_ATTRIBUTES(VIDEO_TYPE_RASTER) MDRV_SCREEN_SIZE(32*8, 32*8) MDRV_VISIBLE_AREA(1*8, 31*8-1, 2*8, 30*8-1) MDRV_GFXDECODE(gfxdecodeinfo) MDRV_PALETTE_LENGTH(384) MDRV_VIDEO_START(ddragon) MDRV_VIDEO_UPDATE(ddragon) /* sound hardware */ MDRV_SOUND_ADD(YM2151, ym2151_interface) MDRV_SOUND_ADD(MSM5205, msm5205_interface) MDRV_SOUND_ADD_TAG("OST Samples", SAMPLES, ost_ddragon) ddragon_playing = true; ddragon_current_music = 0; ddragon_stage = 0; d_title_counter = 0; MACHINE_DRIVER_END static MACHINE_DRIVER_START( darktowr ) /* basic machine hardware */ MDRV_CPU_ADD(HD6309, 3579545) /* 3.579545 MHz */ MDRV_CPU_MEMORY(darktowr_readmem,darktowr_writemem) MDRV_CPU_VBLANK_INT(ddragon_interrupt,272) MDRV_CPU_ADD(HD63701, 3579545 / 3) MDRV_CPU_MEMORY(sub_readmem,sub_writemem) MDRV_CPU_ADD(HD6309, 3579545) MDRV_CPU_FLAGS(CPU_AUDIO_CPU) /* ? */ MDRV_CPU_MEMORY(sound_readmem,sound_writemem) MDRV_CPU_ADD(M68705,8000000/2) /* ? MHz */ MDRV_CPU_MEMORY(mcu_readmem,mcu_writemem) MDRV_FRAMES_PER_SECOND(((12000000.0 / 256.0) / 3.0) / 272.0) MDRV_VBLANK_DURATION(0) MDRV_INTERLEAVE(1000) /* heavy interleaving to sync up sprite<->main cpu's */ MDRV_MACHINE_INIT(ddragon) /* video hardware */ MDRV_VIDEO_ATTRIBUTES(VIDEO_TYPE_RASTER) MDRV_SCREEN_SIZE(32*8, 32*8) MDRV_VISIBLE_AREA(0*8, 32*8-1, 1*8, 31*8-1) MDRV_GFXDECODE(gfxdecodeinfo) MDRV_PALETTE_LENGTH(512) MDRV_VIDEO_START(ddragon) MDRV_VIDEO_UPDATE(ddragon) /* sound hardware */ MDRV_SOUND_ADD(YM2151, ym2151_interface) MDRV_SOUND_ADD(MSM5205, msm5205_interface) MACHINE_DRIVER_END static MACHINE_DRIVER_START( ddragonb ) /* basic machine hardware */ MDRV_CPU_ADD(HD6309, 3579545) /* 3.579545 MHz */ MDRV_CPU_MEMORY(readmem,writemem) MDRV_CPU_VBLANK_INT(ddragon_interrupt,272) MDRV_CPU_ADD(HD6309, 12000000 / 3) /* 4 MHz */ MDRV_CPU_MEMORY(sub_readmem,sub_writemem) MDRV_CPU_ADD(HD6309, 3579545) MDRV_CPU_FLAGS(CPU_AUDIO_CPU) /* ? */ MDRV_CPU_MEMORY(sound_readmem,sound_writemem) MDRV_FRAMES_PER_SECOND(((12000000.0 / 256.0) / 3.0) / 272.0) MDRV_VBLANK_DURATION(0) MDRV_INTERLEAVE(100) /* heavy interleaving to sync up sprite<->main cpu's */ MDRV_MACHINE_INIT(ddragonb) /* video hardware */ MDRV_VIDEO_ATTRIBUTES(VIDEO_TYPE_RASTER) MDRV_SCREEN_SIZE(32*8, 32*8) MDRV_VISIBLE_AREA(1*8, 31*8-1, 2*8, 30*8-1) MDRV_GFXDECODE(gfxdecodeinfo) MDRV_PALETTE_LENGTH(384) MDRV_VIDEO_START(ddragon) MDRV_VIDEO_UPDATE(ddragon) /* sound hardware */ MDRV_SOUND_ADD(YM2151, ym2151_interface) MDRV_SOUND_ADD(MSM5205, msm5205_interface) MACHINE_DRIVER_END static MACHINE_DRIVER_START( ddragon2 ) /* basic machine hardware */ MDRV_CPU_ADD(HD6309, 3579545) /* 3.579545 MHz */ MDRV_CPU_MEMORY(dd2_readmem,dd2_writemem) MDRV_CPU_VBLANK_INT(ddragon_interrupt,272) MDRV_CPU_ADD(Z80, 12000000 / 3) /* 4 MHz */ MDRV_CPU_MEMORY(dd2_sub_readmem,dd2_sub_writemem) MDRV_CPU_ADD(Z80, 3579545) MDRV_CPU_FLAGS(CPU_AUDIO_CPU) /* 3.579545 MHz */ MDRV_CPU_MEMORY(dd2_sound_readmem,dd2_sound_writemem) MDRV_FRAMES_PER_SECOND(((12000000.0 / 256.0) / 3.0) / 272.0) MDRV_VBLANK_DURATION(0) MDRV_INTERLEAVE(100) /* heavy interleaving to sync up sprite<->main cpu's */ MDRV_MACHINE_INIT(ddragon2) /* video hardware */ MDRV_VIDEO_ATTRIBUTES(VIDEO_TYPE_RASTER) MDRV_SCREEN_SIZE(32*8, 32*8) MDRV_VISIBLE_AREA(1*8, 31*8-1, 2*8, 30*8-1) MDRV_GFXDECODE(gfxdecodeinfo) MDRV_PALETTE_LENGTH(384) MDRV_VIDEO_START(ddragon) MDRV_VIDEO_UPDATE(ddragon) /* sound hardware */ MDRV_SOUND_ADD(YM2151, ym2151_interface) MDRV_SOUND_ADD(OKIM6295, okim6295_interface) MACHINE_DRIVER_END static MACHINE_DRIVER_START( toffy ) /* basic machine hardware */ MDRV_CPU_ADD(M6809,3579545) /* 12 MHz / 2 or 3.579545 ?*/ MDRV_CPU_MEMORY(readmem,toffy_writemem) MDRV_CPU_VBLANK_INT(ddragon_interrupt,272) MDRV_CPU_ADD(M6809, 3579545) MDRV_CPU_FLAGS(CPU_AUDIO_CPU) MDRV_CPU_MEMORY(sound_readmem,sound_writemem) MDRV_FRAMES_PER_SECOND(((12000000.0 / 256.0) / 3.0) / 272.0) MDRV_VBLANK_DURATION(0) /* video hardware */ MDRV_VIDEO_ATTRIBUTES(VIDEO_TYPE_RASTER ) MDRV_SCREEN_SIZE(32*8, 32*8) MDRV_VISIBLE_AREA(1*8, 31*8-1, 2*8, 30*8-1) MDRV_GFXDECODE(gfxdecodeinfo) MDRV_PALETTE_LENGTH(384) MDRV_VIDEO_START(ddragon) MDRV_VIDEO_UPDATE(ddragon) MDRV_MACHINE_INIT(toffy) /* sound hardware */ MDRV_SOUND_ATTRIBUTES(SOUND_SUPPORTS_STEREO) MDRV_SOUND_ADD(YM2151, ym2151_interface) MACHINE_DRIVER_END /*************************************************************************** Game driver(s) ***************************************************************************/ ROM_START( ddragon ) ROM_REGION( 0x28000, REGION_CPU1, 0 ) /* 64k for code + bankswitched memory */ ROM_LOAD( "21j-1-5", 0x08000, 0x08000, CRC(42045dfd) SHA1(0983705ea3bb87c4c239692f400e02f15c243479) ) ROM_LOAD( "21j-2-3", 0x10000, 0x08000, CRC(5779705e) SHA1(4b8f22225d10f5414253ce0383bbebd6f720f3af) ) /* banked at 0x4000-0x8000 */ ROM_LOAD( "21j-3", 0x18000, 0x08000, CRC(3bdea613) SHA1(d9038c80646a6ce3ea61da222873237b0383680e) ) /* banked at 0x4000-0x8000 */ ROM_LOAD( "21j-4-1", 0x20000, 0x08000, CRC(728f87b9) SHA1(d7442be24d41bb9fc021587ef44ae5b830e4503d) ) /* banked at 0x4000-0x8000 */ ROM_REGION( 0x10000, REGION_CPU2, 0 ) /* sprite cpu */ ROM_LOAD( "63701.bin", 0xc000, 0x4000, CRC(f5232d03) SHA1(e2a194e38633592fd6587690b3cb2669d93985c7) ) ROM_REGION( 0x10000, REGION_CPU3, 0 ) /* audio cpu */ ROM_LOAD( "21j-0-1", 0x08000, 0x08000, CRC(9efa95bb) SHA1(da997d9cc7b9e7b2c70a4b6d30db693086a6f7d8) ) ROM_REGION( 0x08000, REGION_GFX1, ROMREGION_DISPOSE ) ROM_LOAD( "21j-5", 0x00000, 0x08000, CRC(7a8b8db4) SHA1(8368182234f9d4d763d4714fd7567a9e31b7ebeb) ) /* chars */ ROM_REGION( 0x80000, REGION_GFX2, ROMREGION_DISPOSE ) ROM_LOAD( "21j-a", 0x00000, 0x10000, CRC(574face3) SHA1(481fe574cb79d0159a65ff7486cbc945d50538c5) ) /* sprites */ ROM_LOAD( "21j-b", 0x10000, 0x10000, CRC(40507a76) SHA1(74581a4b6f48100bddf20f319903af2fe36f39fa) ) ROM_LOAD( "21j-c", 0x20000, 0x10000, CRC(bb0bc76f) SHA1(37b2225e0593335f636c1e5fded9b21fdeab2f5a) ) ROM_LOAD( "21j-d", 0x30000, 0x10000, CRC(cb4f231b) SHA1(9f2270f9ceedfe51c5e9a9bbb00d6f43dbc4a3ea) ) ROM_LOAD( "21j-e", 0x40000, 0x10000, CRC(a0a0c261) SHA1(25c534d82bd237386d447d72feee8d9541a5ded4) ) ROM_LOAD( "21j-f", 0x50000, 0x10000, CRC(6ba152f6) SHA1(a301ff809be0e1471f4ff8305b30c2fa4aa57fae) ) ROM_LOAD( "21j-g", 0x60000, 0x10000, CRC(3220a0b6) SHA1(24a16ea509e9aff82b9ddd14935d61bb71acff84) ) ROM_LOAD( "21j-h", 0x70000, 0x10000, CRC(65c7517d) SHA1(f177ba9c1c7cc75ff04d5591b9865ee364788f94) ) ROM_REGION( 0x40000, REGION_GFX3, ROMREGION_DISPOSE ) ROM_LOAD( "21j-8", 0x00000, 0x10000, CRC(7c435887) SHA1(ecb76f2148fa9773426f05aac208eb3ac02747db) ) /* tiles */ ROM_LOAD( "21j-9", 0x10000, 0x10000, CRC(c6640aed) SHA1(f156c337f48dfe4f7e9caee9a72c7ea3d53e3098) ) ROM_LOAD( "21j-i", 0x20000, 0x10000, CRC(5effb0a0) SHA1(1f21acb15dad824e831ed9a42b3fde096bb31141) ) ROM_LOAD( "21j-j", 0x30000, 0x10000, CRC(5fb42e7c) SHA1(7953316712c56c6f8ca6bba127319e24b618b646) ) ROM_REGION( 0x20000, REGION_SOUND1, 0 ) /* adpcm samples */ ROM_LOAD( "21j-6", 0x00000, 0x10000, CRC(34755de3) SHA1(57c06d6ce9497901072fa50a92b6ed0d2d4d6528) ) ROM_LOAD( "21j-7", 0x10000, 0x10000, CRC(904de6f8) SHA1(3623e5ea05fd7c455992b7ed87e605b87c3850aa) ) ROM_REGION( 0x0300, REGION_PROMS, 0 ) ROM_LOAD( "21j-k-0", 0x0000, 0x0100, CRC(fdb130a9) SHA1(4c4f214229b9fab2b5d69c745ec5428787b89e1f) ) /* unknown */ ROM_LOAD( "21j-l-0", 0x0100, 0x0200, CRC(46339529) SHA1(64f4c42a826d67b7cbaa8a23a45ebc4eb6248891) ) /* unknown */ ROM_END ROM_START( ddragonw ) ROM_REGION( 0x28000, REGION_CPU1, 0 ) /* 64k for code + bankswitched memory */ ROM_LOAD( "21j-1", 0x08000, 0x08000, CRC(ae714964) SHA1(072522b97ca4edd099c6b48d7634354dc7088c53) ) ROM_LOAD( "21j-2-3", 0x10000, 0x08000, CRC(5779705e) SHA1(4b8f22225d10f5414253ce0383bbebd6f720f3af) ) /* banked at 0x4000-0x8000 */ ROM_LOAD( "21a-3", 0x18000, 0x08000, CRC(dbf24897) SHA1(1504faaf07c541330cd43b72dc6846911dfd85a3) ) /* banked at 0x4000-0x8000 */ ROM_LOAD( "21j-4", 0x20000, 0x08000, CRC(6c9f46fa) SHA1(df251a4aea69b2328f7a543bf085b9c35933e2c1) ) /* banked at 0x4000-0x8000 */ ROM_REGION( 0x10000, REGION_CPU2, 0 ) /* sprite cpu */ ROM_LOAD( "63701.bin", 0xc000, 0x4000, CRC(f5232d03) SHA1(e2a194e38633592fd6587690b3cb2669d93985c7) ) ROM_REGION( 0x10000, REGION_CPU3, 0 ) /* audio cpu */ ROM_LOAD( "21j-0-1", 0x08000, 0x08000, CRC(9efa95bb) SHA1(da997d9cc7b9e7b2c70a4b6d30db693086a6f7d8) ) ROM_REGION( 0x08000, REGION_GFX1, ROMREGION_DISPOSE ) ROM_LOAD( "21j-5", 0x00000, 0x08000, CRC(7a8b8db4) SHA1(8368182234f9d4d763d4714fd7567a9e31b7ebeb) ) /* chars */ ROM_REGION( 0x80000, REGION_GFX2, ROMREGION_DISPOSE ) ROM_LOAD( "21j-a", 0x00000, 0x10000, CRC(574face3) SHA1(481fe574cb79d0159a65ff7486cbc945d50538c5) ) /* sprites */ ROM_LOAD( "21j-b", 0x10000, 0x10000, CRC(40507a76) SHA1(74581a4b6f48100bddf20f319903af2fe36f39fa) ) ROM_LOAD( "21j-c", 0x20000, 0x10000, CRC(bb0bc76f) SHA1(37b2225e0593335f636c1e5fded9b21fdeab2f5a) ) ROM_LOAD( "21j-d", 0x30000, 0x10000, CRC(cb4f231b) SHA1(9f2270f9ceedfe51c5e9a9bbb00d6f43dbc4a3ea) ) ROM_LOAD( "21j-e", 0x40000, 0x10000, CRC(a0a0c261) SHA1(25c534d82bd237386d447d72feee8d9541a5ded4) ) ROM_LOAD( "21j-f", 0x50000, 0x10000, CRC(6ba152f6) SHA1(a301ff809be0e1471f4ff8305b30c2fa4aa57fae) ) ROM_LOAD( "21j-g", 0x60000, 0x10000, CRC(3220a0b6) SHA1(24a16ea509e9aff82b9ddd14935d61bb71acff84) ) ROM_LOAD( "21j-h", 0x70000, 0x10000, CRC(65c7517d) SHA1(f177ba9c1c7cc75ff04d5591b9865ee364788f94) ) ROM_REGION( 0x40000, REGION_GFX3, ROMREGION_DISPOSE ) ROM_LOAD( "21j-8", 0x00000, 0x10000, CRC(7c435887) SHA1(ecb76f2148fa9773426f05aac208eb3ac02747db) ) /* tiles */ ROM_LOAD( "21j-9", 0x10000, 0x10000, CRC(c6640aed) SHA1(f156c337f48dfe4f7e9caee9a72c7ea3d53e3098) ) ROM_LOAD( "21j-i", 0x20000, 0x10000, CRC(5effb0a0) SHA1(1f21acb15dad824e831ed9a42b3fde096bb31141) ) ROM_LOAD( "21j-j", 0x30000, 0x10000, CRC(5fb42e7c) SHA1(7953316712c56c6f8ca6bba127319e24b618b646) ) ROM_REGION( 0x20000, REGION_SOUND1, 0 ) /* adpcm samples */ ROM_LOAD( "21j-6", 0x00000, 0x10000, CRC(34755de3) SHA1(57c06d6ce9497901072fa50a92b6ed0d2d4d6528) ) ROM_LOAD( "21j-7", 0x10000, 0x10000, CRC(904de6f8) SHA1(3623e5ea05fd7c455992b7ed87e605b87c3850aa) ) ROM_REGION( 0x0300, REGION_PROMS, 0 ) ROM_LOAD( "21j-k-0", 0x0000, 0x0100, CRC(fdb130a9) SHA1(4c4f214229b9fab2b5d69c745ec5428787b89e1f) ) /* unknown */ ROM_LOAD( "21j-l-0", 0x0100, 0x0200, CRC(46339529) SHA1(64f4c42a826d67b7cbaa8a23a45ebc4eb6248891) ) /* unknown */ ROM_END ROM_START( ddragonu ) ROM_REGION( 0x28000, REGION_CPU1, 0 ) /* 64k for code + bankswitched memory */ ROM_LOAD( "21a-1-5", 0x08000, 0x08000, CRC(e24a6e11) SHA1(9dd97dd712d5c896f91fd80df58be9b8a2b198ee) ) ROM_LOAD( "21j-2-3", 0x10000, 0x08000, CRC(5779705e) SHA1(4b8f22225d10f5414253ce0383bbebd6f720f3af) ) /* banked at 0x4000-0x8000 */ ROM_LOAD( "21a-3", 0x18000, 0x08000, CRC(dbf24897) SHA1(1504faaf07c541330cd43b72dc6846911dfd85a3) ) /* banked at 0x4000-0x8000 */ ROM_LOAD( "21a-4", 0x20000, 0x08000, CRC(6ea16072) SHA1(0b3b84a0d54f7a3aba411586009babbfee653f9a) ) /* banked at 0x4000-0x8000 */ ROM_REGION( 0x10000, REGION_CPU2, 0 ) /* sprite cpu */ ROM_LOAD( "63701.bin", 0xc000, 0x4000, CRC(f5232d03) SHA1(e2a194e38633592fd6587690b3cb2669d93985c7) ) ROM_REGION( 0x10000, REGION_CPU3, 0 ) /* audio cpu */ ROM_LOAD( "21j-0-1", 0x08000, 0x08000, CRC(9efa95bb) SHA1(da997d9cc7b9e7b2c70a4b6d30db693086a6f7d8) ) ROM_REGION( 0x08000, REGION_GFX1, ROMREGION_DISPOSE ) ROM_LOAD( "21j-5", 0x00000, 0x08000, CRC(7a8b8db4) SHA1(8368182234f9d4d763d4714fd7567a9e31b7ebeb) ) /* chars */ ROM_REGION( 0x80000, REGION_GFX2, ROMREGION_DISPOSE ) ROM_LOAD( "21j-a", 0x00000, 0x10000, CRC(574face3) SHA1(481fe574cb79d0159a65ff7486cbc945d50538c5) ) /* sprites */ ROM_LOAD( "21j-b", 0x10000, 0x10000, CRC(40507a76) SHA1(74581a4b6f48100bddf20f319903af2fe36f39fa) ) ROM_LOAD( "21j-c", 0x20000, 0x10000, CRC(bb0bc76f) SHA1(37b2225e0593335f636c1e5fded9b21fdeab2f5a) ) ROM_LOAD( "21j-d", 0x30000, 0x10000, CRC(cb4f231b) SHA1(9f2270f9ceedfe51c5e9a9bbb00d6f43dbc4a3ea) ) ROM_LOAD( "21j-e", 0x40000, 0x10000, CRC(a0a0c261) SHA1(25c534d82bd237386d447d72feee8d9541a5ded4) ) ROM_LOAD( "21j-f", 0x50000, 0x10000, CRC(6ba152f6) SHA1(a301ff809be0e1471f4ff8305b30c2fa4aa57fae) ) ROM_LOAD( "21j-g", 0x60000, 0x10000, CRC(3220a0b6) SHA1(24a16ea509e9aff82b9ddd14935d61bb71acff84) ) ROM_LOAD( "21j-h", 0x70000, 0x10000, CRC(65c7517d) SHA1(f177ba9c1c7cc75ff04d5591b9865ee364788f94) ) ROM_REGION( 0x40000, REGION_GFX3, ROMREGION_DISPOSE ) ROM_LOAD( "21j-8", 0x00000, 0x10000, CRC(7c435887) SHA1(ecb76f2148fa9773426f05aac208eb3ac02747db) ) /* tiles */ ROM_LOAD( "21j-9", 0x10000, 0x10000, CRC(c6640aed) SHA1(f156c337f48dfe4f7e9caee9a72c7ea3d53e3098) ) ROM_LOAD( "21j-i", 0x20000, 0x10000, CRC(5effb0a0) SHA1(1f21acb15dad824e831ed9a42b3fde096bb31141) ) ROM_LOAD( "21j-j", 0x30000, 0x10000, CRC(5fb42e7c) SHA1(7953316712c56c6f8ca6bba127319e24b618b646) ) ROM_REGION( 0x20000, REGION_SOUND1, 0 ) /* adpcm samples */ ROM_LOAD( "21j-6", 0x00000, 0x10000, CRC(34755de3) SHA1(57c06d6ce9497901072fa50a92b6ed0d2d4d6528) ) ROM_LOAD( "21j-7", 0x10000, 0x10000, CRC(904de6f8) SHA1(3623e5ea05fd7c455992b7ed87e605b87c3850aa) ) ROM_REGION( 0x0300, REGION_PROMS, 0 ) ROM_LOAD( "21j-k-0", 0x0000, 0x0100, CRC(fdb130a9) SHA1(4c4f214229b9fab2b5d69c745ec5428787b89e1f) ) /* unknown */ ROM_LOAD( "21j-l-0", 0x0100, 0x0200, CRC(46339529) SHA1(64f4c42a826d67b7cbaa8a23a45ebc4eb6248891) ) /* unknown */ ROM_END ROM_START( ddragonb ) ROM_REGION( 0x28000, REGION_CPU1, 0 ) /* 64k for code + bankswitched memory */ ROM_LOAD( "ic26", 0x08000, 0x08000, CRC(ae714964) SHA1(072522b97ca4edd099c6b48d7634354dc7088c53) ) ROM_LOAD( "21j-2-3", 0x10000, 0x08000, CRC(5779705e) SHA1(4b8f22225d10f5414253ce0383bbebd6f720f3af) ) /* banked at 0x4000-0x8000 */ ROM_LOAD( "21a-3", 0x18000, 0x08000, CRC(dbf24897) SHA1(1504faaf07c541330cd43b72dc6846911dfd85a3) ) /* banked at 0x4000-0x8000 */ ROM_LOAD( "ic23", 0x20000, 0x08000, CRC(6c9f46fa) SHA1(df251a4aea69b2328f7a543bf085b9c35933e2c1) ) /* banked at 0x4000-0x8000 */ ROM_REGION( 0x10000, REGION_CPU2, 0 ) /* sprite cpu */ ROM_LOAD( "ic38", 0x0c000, 0x04000, CRC(6a6a0325) SHA1(98a940a9f23ce9154ff94f7f2ce29efe9a92f71b) ) ROM_REGION( 0x10000, REGION_CPU3, 0 ) /* audio cpu */ ROM_LOAD( "21j-0-1", 0x08000, 0x08000, CRC(9efa95bb) SHA1(da997d9cc7b9e7b2c70a4b6d30db693086a6f7d8) ) ROM_REGION( 0x08000, REGION_GFX1, ROMREGION_DISPOSE ) ROM_LOAD( "21j-5", 0x00000, 0x08000, CRC(7a8b8db4) SHA1(8368182234f9d4d763d4714fd7567a9e31b7ebeb) ) /* chars */ ROM_REGION( 0x80000, REGION_GFX2, ROMREGION_DISPOSE ) ROM_LOAD( "21j-a", 0x00000, 0x10000, CRC(574face3) SHA1(481fe574cb79d0159a65ff7486cbc945d50538c5) ) /* sprites */ ROM_LOAD( "21j-b", 0x10000, 0x10000, CRC(40507a76) SHA1(74581a4b6f48100bddf20f319903af2fe36f39fa) ) ROM_LOAD( "21j-c", 0x20000, 0x10000, CRC(bb0bc76f) SHA1(37b2225e0593335f636c1e5fded9b21fdeab2f5a) ) ROM_LOAD( "21j-d", 0x30000, 0x10000, CRC(cb4f231b) SHA1(9f2270f9ceedfe51c5e9a9bbb00d6f43dbc4a3ea) ) ROM_LOAD( "21j-e", 0x40000, 0x10000, CRC(a0a0c261) SHA1(25c534d82bd237386d447d72feee8d9541a5ded4) ) ROM_LOAD( "21j-f", 0x50000, 0x10000, CRC(6ba152f6) SHA1(a301ff809be0e1471f4ff8305b30c2fa4aa57fae) ) ROM_LOAD( "21j-g", 0x60000, 0x10000, CRC(3220a0b6) SHA1(24a16ea509e9aff82b9ddd14935d61bb71acff84) ) ROM_LOAD( "21j-h", 0x70000, 0x10000, CRC(65c7517d) SHA1(f177ba9c1c7cc75ff04d5591b9865ee364788f94) ) ROM_REGION( 0x40000, REGION_GFX3, ROMREGION_DISPOSE ) ROM_LOAD( "21j-8", 0x00000, 0x10000, CRC(7c435887) SHA1(ecb76f2148fa9773426f05aac208eb3ac02747db) ) /* tiles */ ROM_LOAD( "21j-9", 0x10000, 0x10000, CRC(c6640aed) SHA1(f156c337f48dfe4f7e9caee9a72c7ea3d53e3098) ) ROM_LOAD( "21j-i", 0x20000, 0x10000, CRC(5effb0a0) SHA1(1f21acb15dad824e831ed9a42b3fde096bb31141) ) ROM_LOAD( "21j-j", 0x30000, 0x10000, CRC(5fb42e7c) SHA1(7953316712c56c6f8ca6bba127319e24b618b646) ) ROM_REGION( 0x20000, REGION_SOUND1, 0 ) /* adpcm samples */ ROM_LOAD( "21j-6", 0x00000, 0x10000, CRC(34755de3) SHA1(57c06d6ce9497901072fa50a92b6ed0d2d4d6528) ) ROM_LOAD( "21j-7", 0x10000, 0x10000, CRC(904de6f8) SHA1(3623e5ea05fd7c455992b7ed87e605b87c3850aa) ) ROM_REGION( 0x0300, REGION_PROMS, 0 ) ROM_LOAD( "21j-k-0", 0x0000, 0x0100, CRC(fdb130a9) SHA1(4c4f214229b9fab2b5d69c745ec5428787b89e1f) ) /* unknown */ ROM_LOAD( "21j-l-0", 0x0100, 0x0200, CRC(46339529) SHA1(64f4c42a826d67b7cbaa8a23a45ebc4eb6248891) ) /* unknown */ ROM_END ROM_START( ddragon2 ) ROM_REGION( 0x28000, REGION_CPU1, 0 ) /* 64k for code */ ROM_LOAD( "26a9-04.bin", 0x08000, 0x8000, CRC(f2cfc649) SHA1(d3f1e0bae02472914a940222e4f600170a91736d) ) ROM_LOAD( "26aa-03.bin", 0x10000, 0x8000, CRC(44dd5d4b) SHA1(427c4e419668b41545928cfc96435c010ecdc88b) ) ROM_LOAD( "26ab-0.bin", 0x18000, 0x8000, CRC(49ddddcd) SHA1(91dc53718d04718b313f23d86e241027c89d1a03) ) ROM_LOAD( "26ac-0e.63", 0x20000, 0x8000, CRC(57acad2c) SHA1(938e2a78af38ecd7e9e08fb10acc1940f7585f5e) ) ROM_REGION( 0x10000, REGION_CPU2, 0 ) /* sprite CPU 64kb (Upper 16kb = 0) */ ROM_LOAD( "26ae-0.bin", 0x00000, 0x10000, CRC(ea437867) SHA1(cd910203af0565f981b9bdef51ea6e9c33ee82d3) ) ROM_REGION( 0x10000, REGION_CPU3, 0 ) /* music CPU, 64kb */ ROM_LOAD( "26ad-0.bin", 0x00000, 0x8000, CRC(75e36cd6) SHA1(f24805f4f6925b3ac508e66a6fc25c275b05f3b9) ) ROM_REGION( 0x10000, REGION_GFX1, ROMREGION_DISPOSE ) ROM_LOAD( "26a8-0e.19", 0x00000, 0x10000, CRC(4e80cd36) SHA1(dcae0709f27f32effb359f6b943f61b102749f2a) ) /* chars */ ROM_REGION( 0xc0000, REGION_GFX2, ROMREGION_DISPOSE ) ROM_LOAD( "26j0-0.bin", 0x00000, 0x20000, CRC(db309c84) SHA1(ee095e4a3bc86737539784945decb1f63da47b9b) ) /* sprites */ ROM_LOAD( "26j1-0.bin", 0x20000, 0x20000, CRC(c3081e0c) SHA1(c4a9ae151aae21073a2c79c5ac088c72d4f3d9db) ) ROM_LOAD( "26af-0.bin", 0x40000, 0x20000, CRC(3a615aad) SHA1(ec90a35224a177d00327de6fd1a299df38abd790) ) ROM_LOAD( "26j2-0.bin", 0x60000, 0x20000, CRC(589564ae) SHA1(1e6e0ef623545615e8409b6d3ba586a71e2612b6) ) ROM_LOAD( "26j3-0.bin", 0x80000, 0x20000, CRC(daf040d6) SHA1(ab0fd5482625dbe64f0f0b0baff5dcde05309b81) ) ROM_LOAD( "26a10-0.bin", 0xa0000, 0x20000, CRC(6d16d889) SHA1(3bc62b3e7f4ddc3200a9cf8469239662da80c854) ) ROM_REGION( 0x40000, REGION_GFX3, ROMREGION_DISPOSE ) ROM_LOAD( "26j4-0.bin", 0x00000, 0x20000, CRC(a8c93e76) SHA1(54d64f052971e7fa0d21c5ce12f87b0fa2b648d6) ) /* tiles */ ROM_LOAD( "26j5-0.bin", 0x20000, 0x20000, CRC(ee555237) SHA1(f9698f3e57f933a43e508f60667c860dee034d05) ) ROM_REGION( 0x40000, REGION_SOUND1, 0 ) /* adpcm samples */ ROM_LOAD( "26j6-0.bin", 0x00000, 0x20000, CRC(a84b2a29) SHA1(9cb529e4939c16a0a42f45dd5547c76c2f86f07b) ) ROM_LOAD( "26j7-0.bin", 0x20000, 0x20000, CRC(bc6a48d5) SHA1(04c434f8cd42a8f82a263548183569396f9b684d) ) ROM_REGION( 0x0200, REGION_PROMS, 0 ) ROM_LOAD( "prom.16", 0x0000, 0x0200, CRC(46339529) SHA1(64f4c42a826d67b7cbaa8a23a45ebc4eb6248891) ) /* unknown (same as ddragon) */ ROM_END ROM_START( ddragn2u ) ROM_REGION( 0x28000, REGION_CPU1, 0 ) /* 64k for code */ ROM_LOAD( "26a9-04.bin", 0x08000, 0x8000, CRC(f2cfc649) SHA1(d3f1e0bae02472914a940222e4f600170a91736d) ) ROM_LOAD( "26aa-03.bin", 0x10000, 0x8000, CRC(44dd5d4b) SHA1(427c4e419668b41545928cfc96435c010ecdc88b) ) ROM_LOAD( "26ab-0.bin", 0x18000, 0x8000, CRC(49ddddcd) SHA1(91dc53718d04718b313f23d86e241027c89d1a03) ) ROM_LOAD( "26ac-02.bin", 0x20000, 0x8000, CRC(097eaf26) SHA1(60504abd30fec44c45197cdf3832c87d05ef577d) ) ROM_REGION( 0x10000, REGION_CPU2, 0 ) /* sprite CPU 64kb (Upper 16kb = 0) */ ROM_LOAD( "26ae-0.bin", 0x00000, 0x10000, CRC(ea437867) SHA1(cd910203af0565f981b9bdef51ea6e9c33ee82d3) ) ROM_REGION( 0x10000, REGION_CPU3, 0 ) /* music CPU, 64kb */ ROM_LOAD( "26ad-0.bin", 0x00000, 0x8000, CRC(75e36cd6) SHA1(f24805f4f6925b3ac508e66a6fc25c275b05f3b9) ) ROM_REGION( 0x10000, REGION_GFX1, ROMREGION_DISPOSE ) ROM_LOAD( "26a8-0.bin", 0x00000, 0x10000, CRC(3ad1049c) SHA1(11d9544a56f8e6a84beb307a5c8a9ff8afc55c66) ) /* chars */ ROM_REGION( 0xc0000, REGION_GFX2, ROMREGION_DISPOSE ) ROM_LOAD( "26j0-0.bin", 0x00000, 0x20000, CRC(db309c84) SHA1(ee095e4a3bc86737539784945decb1f63da47b9b) ) /* sprites */ ROM_LOAD( "26j1-0.bin", 0x20000, 0x20000, CRC(c3081e0c) SHA1(c4a9ae151aae21073a2c79c5ac088c72d4f3d9db) ) ROM_LOAD( "26af-0.bin", 0x40000, 0x20000, CRC(3a615aad) SHA1(ec90a35224a177d00327de6fd1a299df38abd790) ) ROM_LOAD( "26j2-0.bin", 0x60000, 0x20000, CRC(589564ae) SHA1(1e6e0ef623545615e8409b6d3ba586a71e2612b6) ) ROM_LOAD( "26j3-0.bin", 0x80000, 0x20000, CRC(daf040d6) SHA1(ab0fd5482625dbe64f0f0b0baff5dcde05309b81) ) ROM_LOAD( "26a10-0.bin", 0xa0000, 0x20000, CRC(6d16d889) SHA1(3bc62b3e7f4ddc3200a9cf8469239662da80c854) ) ROM_REGION( 0x40000, REGION_GFX3, ROMREGION_DISPOSE ) ROM_LOAD( "26j4-0.bin", 0x00000, 0x20000, CRC(a8c93e76) SHA1(54d64f052971e7fa0d21c5ce12f87b0fa2b648d6) ) /* tiles */ ROM_LOAD( "26j5-0.bin", 0x20000, 0x20000, CRC(ee555237) SHA1(f9698f3e57f933a43e508f60667c860dee034d05) ) ROM_REGION( 0x40000, REGION_SOUND1, 0 ) /* adpcm samples */ ROM_LOAD( "26j6-0.bin", 0x00000, 0x20000, CRC(a84b2a29) SHA1(9cb529e4939c16a0a42f45dd5547c76c2f86f07b) ) ROM_LOAD( "26j7-0.bin", 0x20000, 0x20000, CRC(bc6a48d5) SHA1(04c434f8cd42a8f82a263548183569396f9b684d) ) ROM_REGION( 0x0200, REGION_PROMS, 0 ) ROM_LOAD( "prom.16", 0x0000, 0x0200, CRC(46339529) SHA1(64f4c42a826d67b7cbaa8a23a45ebc4eb6248891) ) /* unknown (same as ddragon) */ ROM_END ROM_START( toffy ) ROM_REGION( 0x28000, REGION_CPU1, 0 ) /* Main CPU? */ ROM_LOAD( "2-27512.rom", 0x00000, 0x10000, CRC(244709dd) SHA1(b2db51b910f1a031b94fb50e684351f657a465dc) ) ROM_RELOAD( 0x10000, 0x10000 ) ROM_REGION( 0x10000, REGION_CPU2, 0 ) /* Sound CPU? */ ROM_LOAD( "u142.1", 0x00000, 0x10000, CRC(541bd7f0) SHA1(3f0097f5877eae50651f94d46d7dd9127037eb6e) ) ROM_REGION( 0x10000, REGION_GFX1, 0 ) /* GFX? */ ROM_LOAD( "7-27512.rom", 0x000, 0x10000, CRC(f9e8ec64) SHA1(36891cd8f28800e03fe0eac84b2484a70011eabb) ) ROM_REGION( 0x20000, REGION_GFX3, 0 ) /* GFX */ /* the same as 'Dangerous Dungeons' once decrypted */ ROM_LOAD( "4-27512.rom", 0x00000, 0x10000, CRC(94b5ef6f) SHA1(32967f6cfc6a077c31923318891ed508f83e67f6) ) ROM_LOAD( "3-27512.rom", 0x10000, 0x10000, CRC(a7a053a3) SHA1(98625fe73a409c8d51136931a5f707a0bf75b66a) ) ROM_REGION( 0x20000, REGION_GFX2, 0 ) /* GFX */ ROM_LOAD( "6-27512.rom", 0x00000, 0x10000, CRC(2ba7ca47) SHA1(ad709fc871f1f1a7d4b0fdf0f516c53fd4c8b685) ) ROM_LOAD( "5-27512.rom", 0x10000, 0x10000, CRC(4f91eec6) SHA1(18a5f98dfba33837b73d032a6153eeb03263684b) ) ROM_END ROM_START( stoffy ) ROM_REGION( 0x28000, REGION_CPU1, 0 ) /* Main CPU? */ ROM_LOAD( "u70.2", 0x00000, 0x10000, CRC(3c156610) SHA1(d7fdbc595bdc77c452da39da8b20774db0952e33) ) ROM_RELOAD( 0x10000, 0x10000 ) ROM_REGION( 0x10000, REGION_CPU2, 0 ) /* Sound CPU? */ ROM_LOAD( "u142.1", 0x00000, 0x10000, CRC(541bd7f0) SHA1(3f0097f5877eae50651f94d46d7dd9127037eb6e) ) /* same as 'toffy'*/ ROM_REGION( 0x10000, REGION_GFX1, 0 ) /* GFX? */ ROM_LOAD( "u35.7", 0x00000, 0x10000, CRC(83735d25) SHA1(d82c046db0112d7d2877339652b2111f12513a4f) ) ROM_REGION( 0x20000, REGION_GFX3, 0 ) /* GFX */ ROM_LOAD( "u78.4", 0x00000, 0x10000, CRC(9743a74d) SHA1(876696c5e88e58e6e44671c33a4c140be02a941e) ) /* 0*/ ROM_LOAD( "u77.3", 0x10000, 0x10000, CRC(f267109a) SHA1(679d2147c79636796dda850345c04ad8a9daa6af) ) /* 0*/ ROM_REGION( 0x20000, REGION_GFX2, 0 ) /* GFX */ ROM_LOAD( "u80.5", 0x00000, 0x10000, CRC(ff190865) SHA1(245e69651d0161fcb416bba8f743602b4ee83139) ) /* 1 | should be u80.6 ?*/ ROM_LOAD( "u79.5", 0x10000, 0x10000, CRC(333d5b8a) SHA1(d3573db87e2318c144ee9ace6c975a70fc96f4c4) ) /* 1*/ ROM_END ROM_START( ddungeon ) ROM_REGION( 0x28000, REGION_CPU1, 0 ) /* Main CPU? */ ROM_LOAD( "dd3.bin", 0x10000, 0x8000, CRC(922e719c) SHA1(d1c73f56913cd368158abc613d7bbab669509742) ) ROM_LOAD( "dd2.bin", 0x08000, 0x8000, CRC(a6e7f608) SHA1(83b9301c39bfdc1e50a37f2bdc4d4f65a1111bee) ) /* IC23 is replaced with a daughterboard containing a 68705 MCU */ ROM_REGION( 0x10000, REGION_CPU2, 0 ) /* sprite cpu */ ROM_LOAD( "63701.bin", 0xc000, 0x4000, CRC(f5232d03) SHA1(e2a194e38633592fd6587690b3cb2669d93985c7) ) ROM_REGION( 0x10000, REGION_CPU3, 0 ) /* audio cpu */ ROM_LOAD( "21j-0-1", 0x08000, 0x08000, CRC(9efa95bb) SHA1(da997d9cc7b9e7b2c70a4b6d30db693086a6f7d8) ) /* from ddragon */ ROM_REGION( 0x0800, REGION_CPU4, 0 ) /* 8k for the microcontroller */ ROM_LOAD( "dd_mcu.bin", 0x00000, 0x0800, CRC(34cbb2d3) SHA1(8e0c3b13c636012d88753d547c639b1a8af85680) ) ROM_REGION( 0x10000, REGION_GFX1, 0 ) /* GFX? */ ROM_LOAD( "dd6.bin", 0x00000, 0x08000, CRC(057588ca) SHA1(d4a5dd3ea8cf455b54657473d4d52ab5e838ae15) ) ROM_REGION( 0x20000, REGION_GFX2, 0 ) /* GFX */ ROM_LOAD( "dd-7r.bin", 0x00000, 0x08000, CRC(50d6ab5d) SHA1(4c9cbd72d38b631ea2ca231045ef3f3e11cc7c07) ) /* 1*/ ROM_LOAD( "dd-7k.bin", 0x10000, 0x08000, CRC(43264ad8) SHA1(74f031d6179390bc4fa99f4929a6886db8c2b510) ) /* 1*/ ROM_REGION( 0x20000, REGION_GFX3, 0 ) /* GFX */ ROM_LOAD( "dd-6b.bin", 0x00000, 0x08000, CRC(3deacae9) SHA1(6663f054ed3eed50c5cacfa5d22d465dfb179964) ) /* 0*/ ROM_LOAD( "dd-7c.bin", 0x10000, 0x08000, CRC(5a2f31eb) SHA1(1b85533443e148adb2a9c2c09c43cbf2c35c86bc) ) /* 0*/ ROM_REGION( 0x20000, REGION_SOUND1, 0 ) /* adpcm samples */ ROM_LOAD( "21j-6", 0x00000, 0x10000, CRC(34755de3) SHA1(57c06d6ce9497901072fa50a92b6ed0d2d4d6528) ) ROM_LOAD( "21j-7", 0x10000, 0x10000, CRC(904de6f8) SHA1(3623e5ea05fd7c455992b7ed87e605b87c3850aa) ) ROM_REGION( 0x0300, REGION_PROMS, 0 ) ROM_LOAD( "21j-k-0", 0x0000, 0x0100, CRC(fdb130a9) SHA1(4c4f214229b9fab2b5d69c745ec5428787b89e1f) ) /* unknown */ ROM_LOAD( "21j-l-0", 0x0100, 0x0200, CRC(46339529) SHA1(64f4c42a826d67b7cbaa8a23a45ebc4eb6248891) ) /* unknown */ ROM_END ROM_START( darktowr ) ROM_REGION( 0x28000, REGION_CPU1, 0 ) /* 64k for code + bankswitched memory */ ROM_LOAD( "dt.26", 0x08000, 0x08000, CRC(8134a472) SHA1(7d42d2ed8d09855241d98ed94bce140a314c2f66) ) ROM_LOAD( "21j-2-3.25", 0x10000, 0x08000, CRC(5779705e) SHA1(4b8f22225d10f5414253ce0383bbebd6f720f3af) ) /* from ddragon */ ROM_LOAD( "dt.24", 0x18000, 0x08000, CRC(523a5413) SHA1(71c04287e4f2e792c98abdeb97fe70abd0d5e918) ) /* banked at 0x4000-0x8000 */ /* IC23 is replaced with a daughterboard containing a 68705 MCU */ ROM_REGION( 0x10000, REGION_CPU2, 0 ) /* sprite cpu */ ROM_LOAD( "63701.bin", 0xc000, 0x4000, CRC(f5232d03) SHA1(e2a194e38633592fd6587690b3cb2669d93985c7) ) ROM_REGION( 0x10000, REGION_CPU3, 0 ) /* audio cpu */ ROM_LOAD( "21j-0-1", 0x08000, 0x08000, CRC(9efa95bb) SHA1(da997d9cc7b9e7b2c70a4b6d30db693086a6f7d8) ) /* from ddragon */ ROM_REGION( 0x0800, REGION_CPU4, 0 ) /* 8k for the microcontroller */ ROM_LOAD( "68705prt.mcu", 0x00000, 0x0800, CRC(34cbb2d3) SHA1(8e0c3b13c636012d88753d547c639b1a8af85680) ) ROM_REGION( 0x08000, REGION_GFX1, ROMREGION_DISPOSE ) /* chars */ ROM_LOAD( "dt.20", 0x00000, 0x08000, CRC(860b0298) SHA1(087e4e6511c5bed74ffbfd077ece55a756b13253) ) ROM_REGION( 0x80000, REGION_GFX2, ROMREGION_DISPOSE ) /* sprites */ ROM_LOAD( "dt.117", 0x00000, 0x10000, CRC(750dd0fa) SHA1(d95b95a54c7ed87a27edb8660810dd89efa10c9f) ) ROM_LOAD( "dt.116", 0x10000, 0x10000, CRC(22cfa87b) SHA1(0008a41f307be96be91f491bdeaa1fa450dd0fdf) ) ROM_LOAD( "dt.115", 0x20000, 0x10000, CRC(8a9f1c34) SHA1(1f07f424b2ab14a051f2c84b3d89fc5d35c5f20b) ) ROM_LOAD( "21j-d", 0x30000, 0x10000, CRC(cb4f231b) SHA1(9f2270f9ceedfe51c5e9a9bbb00d6f43dbc4a3ea) ) /* from ddragon */ ROM_LOAD( "dt.113", 0x40000, 0x10000, CRC(7b4bbf9c) SHA1(d0caa3c38e059d3ee48e3e801da36f67457ed542) ) ROM_LOAD( "dt.112", 0x50000, 0x10000, CRC(df3709d4) SHA1(9cca44be97260e730786db8244a0d655c86537aa) ) ROM_LOAD( "dt.111", 0x60000, 0x10000, CRC(59032154) SHA1(637372e4619472a958f4971b50a6fe0985bffc8b) ) ROM_LOAD( "21j-h", 0x70000, 0x10000, CRC(65c7517d) SHA1(f177ba9c1c7cc75ff04d5591b9865ee364788f94) ) /* from ddragon */ ROM_REGION( 0x40000, REGION_GFX3, ROMREGION_DISPOSE ) /* tiles */ ROM_LOAD( "dt.78", 0x00000, 0x10000, CRC(72c15604) SHA1(202b46a2445eea5877e986a871bb0a6b76b88a6f) ) ROM_LOAD( "21j-9", 0x10000, 0x10000, CRC(c6640aed) SHA1(f156c337f48dfe4f7e9caee9a72c7ea3d53e3098) ) /* from ddragon */ ROM_LOAD( "dt.109", 0x20000, 0x10000, CRC(15bdcb62) SHA1(75382a3805dc333b196e119d28b5c3f320bd9f2a) ) ROM_LOAD( "21j-j", 0x30000, 0x10000, CRC(5fb42e7c) SHA1(7953316712c56c6f8ca6bba127319e24b618b646) ) /* from ddragon */ ROM_REGION( 0x20000, REGION_SOUND1, 0 ) /* adpcm samples */ ROM_LOAD( "21j-6", 0x00000, 0x10000, CRC(34755de3) SHA1(57c06d6ce9497901072fa50a92b6ed0d2d4d6528) ) /* from ddragon */ ROM_LOAD( "21j-7", 0x10000, 0x10000, CRC(904de6f8) SHA1(3623e5ea05fd7c455992b7ed87e605b87c3850aa) ) /* from ddragon */ ROM_REGION( 0x0300, REGION_PROMS, 0 ) ROM_LOAD( "21j-k-0", 0x0000, 0x0100, CRC(fdb130a9) SHA1(4c4f214229b9fab2b5d69c745ec5428787b89e1f) ) /* unknown */ /* from ddragon */ ROM_LOAD( "21j-l-0", 0x0100, 0x0200, CRC(46339529) SHA1(64f4c42a826d67b7cbaa8a23a45ebc4eb6248891) ) /* unknown */ /* from ddragon */ ROM_END ROM_START( tstrike ) ROM_REGION( 0x28000, REGION_CPU1, 0 ) /* 64k for code + bankswitched memory */ ROM_LOAD( "tstrike.26", 0x08000, 0x08000, CRC(871b10bc) SHA1(c824775cf72c039612fda76c4a518cd89e4c8657) ) ROM_LOAD( "tstrike.25", 0x10000, 0x08000, CRC(b6a0c2f3) SHA1(3434689ca217f5af268058ad34c277db672d389c) ) /* banked at 0x4000-0x8000 */ ROM_LOAD( "tstrike.24", 0x18000, 0x08000, CRC(363816fa) SHA1(65c1ccbb950e09230196b49dc7312a13a34f3f79) ) /* banked at 0x4000-0x8000 */ /* IC23 is replaced with a daughterboard containing a 68705 MCU */ ROM_REGION( 0x10000, REGION_CPU2, 0 ) /* sprite cpu */ ROM_LOAD( "63701.bin", 0xc000, 0x4000, CRC(f5232d03) SHA1(e2a194e38633592fd6587690b3cb2669d93985c7) ) ROM_REGION( 0x10000, REGION_CPU3, 0 ) /* audio cpu */ ROM_LOAD( "tstrike.30", 0x08000, 0x08000, CRC(3f3f04a1) SHA1(45d2b4542ec783c1c4122616606be6c160f76c06) ) ROM_REGION( 0x0800, REGION_CPU4, 0 ) /* 8k for the microcontroller */ ROM_LOAD( "68705prt.mcu", 0x00000, 0x0800, CRC(34cbb2d3) SHA1(8e0c3b13c636012d88753d547c639b1a8af85680) ) ROM_REGION( 0x08000, REGION_GFX1, ROMREGION_DISPOSE ) ROM_LOAD( "tstrike.20", 0x00000, 0x08000, CRC(b6b8bfa0) SHA1(ce50f8eb1a84873ef3df621d971a6b087473d6c2) ) /* chars */ ROM_REGION( 0x80000, REGION_GFX2, ROMREGION_DISPOSE ) /* sprites */ ROM_LOAD( "tstrike.117", 0x00000, 0x10000, CRC(f7122c0d) SHA1(2b6b359585d9df966c1fc0041fb972aac9b1ab93) ) ROM_LOAD( "21j-b", 0x10000, 0x10000, CRC(40507a76) SHA1(74581a4b6f48100bddf20f319903af2fe36f39fa) ) /* from ddragon (116) */ ROM_LOAD( "tstrike.115", 0x20000, 0x10000, CRC(a13c7b62) SHA1(d929d8db7eb2b949cd3bd77238611ecc54b2e885) ) ROM_LOAD( "21j-d", 0x30000, 0x10000, CRC(cb4f231b) SHA1(9f2270f9ceedfe51c5e9a9bbb00d6f43dbc4a3ea) ) /* from ddragon (114) */ ROM_LOAD( "tstrike.113", 0x40000, 0x10000, CRC(5ad60938) SHA1(a0af9b227157d87fa6d4ea88b34227a97baff20e) ) ROM_LOAD( "21j-f", 0x50000, 0x10000, CRC(6ba152f6) SHA1(a301ff809be0e1471f4ff8305b30c2fa4aa57fae) ) /* from ddragon (112) */ ROM_LOAD( "tstrike.111", 0x60000, 0x10000, CRC(7b9c87ad) SHA1(429049f84b2084bb074e380dca63b75150e7e69f) ) ROM_LOAD( "21j-h", 0x70000, 0x10000, CRC(65c7517d) SHA1(f177ba9c1c7cc75ff04d5591b9865ee364788f94) ) /* from ddragon (110) */ ROM_REGION( 0x40000, REGION_GFX3, ROMREGION_DISPOSE ) /* tiles */ ROM_LOAD( "tstrike.78", 0x00000, 0x10000, CRC(88284aec) SHA1(f07bc5f84f2b2f976c911541c8f1ff2558f569ca) ) ROM_LOAD( "21j-9", 0x10000, 0x10000, CRC(c6640aed) SHA1(f156c337f48dfe4f7e9caee9a72c7ea3d53e3098) ) /* from ddragon (77) */ ROM_LOAD( "tstrike.109", 0x20000, 0x10000, CRC(8c2cd0bb) SHA1(364a708484c7750f38162d463104216bbd555b86) ) ROM_LOAD( "21j-j", 0x30000, 0x10000, CRC(5fb42e7c) SHA1(7953316712c56c6f8ca6bba127319e24b618b646) ) /* from ddragon (108) */ ROM_REGION( 0x20000, REGION_SOUND1, 0 ) /* adpcm samples */ ROM_LOAD( "tstrike.94", 0x00000, 0x10000, CRC(8a2c09fc) SHA1(f59a43c3fa814b169a51744f9604d36ae63c190f) ) /* first+second half identical */ ROM_LOAD( "tstrike.95", 0x10000, 0x08000, CRC(1812eecb) SHA1(9b7d526f30a86682cdf088600b25ea5a56b112ef) ) ROM_REGION( 0x0300, REGION_PROMS, 0 ) ROM_LOAD( "21j-k-0", 0x0000, 0x0100, CRC(fdb130a9) SHA1(4c4f214229b9fab2b5d69c745ec5428787b89e1f) ) /* unknown */ ROM_LOAD( "21j-l-0", 0x0100, 0x0200, CRC(46339529) SHA1(64f4c42a826d67b7cbaa8a23a45ebc4eb6248891) ) /* unknown */ ROM_END /** INITS ** toffy / stoffy are 'encrytped */ static void ddragon_restore_state(int dummy) { ddragon_bankswitch_w(0, bank_data); } static DRIVER_INIT( toffy ) { /* the program rom has a simple bitswap encryption */ UINT8 *rom=memory_region(REGION_CPU1); int i; for (i = 0;i < 0x20000;i++) rom[i] = BITSWAP8(rom[i] , 6,7,5,4,3,2,1,0); /* and the fg gfx ... */ rom=memory_region(REGION_GFX1); for (i = 0;i < 0x10000;i++) rom[i] = BITSWAP8(rom[i] , 7,6,5,3,4,2,1,0); /* and the bg gfx */ rom=memory_region(REGION_GFX3); for (i = 0;i < 0x10000;i++) { rom[i] = BITSWAP8(rom[i] , 7,6,1,4,3,2,5,0); rom[i+0x10000] = BITSWAP8(rom[i+0x10000] , 7,6,2,4,3,5,1,0); } /* and the sprites gfx */ rom=memory_region(REGION_GFX2); for (i = 0;i < 0x20000;i++) rom[i] = BITSWAP8(rom[i] , 7,6,5,4,3,2,0,1); /* should the sound rom be bitswapped too? */ } GAMEC( 1987, ddragon, 0, ddragon, ddragon, 0, ROT0, "Technos", "Double Dragon (Japan)", &ddragon_ctrl, NULL ) GAMEC( 1987, ddragonw, ddragon, ddragon, ddragon, 0, ROT0, "[Technos] (Taito license)", "Double Dragon (World)", &ddragon_ctrl, NULL ) GAMEC( 1987, ddragonu, ddragon, ddragon, ddragon, 0, ROT0, "[Technos] (Taito America license)", "Double Dragon (US)", &ddragon_ctrl, NULL ) GAMEC( 1987, ddragonb, ddragon, ddragonb, ddragon, 0, ROT0, "bootleg", "Double Dragon (bootleg)", &ddragon_ctrl, NULL ) GAMEC( 1988, ddragon2, 0, ddragon2, ddragon2, 0, ROT0, "Technos", "Double Dragon II - The Revenge (World)", &ddragon2_ctrl, NULL ) GAMEC( 1988, ddragn2u, ddragon2, ddragon2, ddragon2, 0, ROT0, "Technos", "Double Dragon II - The Revenge (US)", &ddragon2_ctrl, NULL ) /* these were conversions of double dragon */ GAME( 1991, tstrike, 0, darktowr, tstrike, 0, ROT0, "East Coast Coin Company (Melbourne)", "Thunder Strike") GAME( 1992, ddungeon, 0, darktowr, ddungeon, 0, ROT0, "East Coast Coin Company (Melbourne)", "Dangerous Dungeons" ) GAME( 1992, darktowr, 0, darktowr, darktowr, 0, ROT0, "Game Room", "Dark Tower" ) /* these run on their own board, but are basically the same game. Toffy even has 'dangerous dungeons' text in it */ GAME( 1993, toffy, 0, toffy, toffy, toffy, ROT0, "Midas", "Toffy" ) GAME( 1994, stoffy, 0, toffy, toffy, toffy, ROT0, "Midas (Unico license)", "Super Toffy" )
41.297872
146
0.713226
[ "vector" ]
9ed7e960b8a3f29f8bc78982bc63cf856872ec5b
4,121
h
C
Simulator/Rotations/Condition.h
tomcool420/SimulatorSWTOR
4d2866f997fc3f75b69a97dd5fc474227185de81
[ "MIT" ]
null
null
null
Simulator/Rotations/Condition.h
tomcool420/SimulatorSWTOR
4d2866f997fc3f75b69a97dd5fc474227185de81
[ "MIT" ]
null
null
null
Simulator/Rotations/Condition.h
tomcool420/SimulatorSWTOR
4d2866f997fc3f75b69a97dd5fc474227185de81
[ "MIT" ]
null
null
null
#pragma once #include "Simulator/SimulatorBase/Target.h" #include "Simulator/SimulatorBase/types.h" #include <nlohmann/json.hpp> namespace Simulator { class ConditionC { public: virtual bool check(const TargetPtr &, const TargetPtr &, const Second &, const Second &) = 0; virtual nlohmann::json serialize() = 0; virtual ~ConditionC() = default; }; constexpr char cooldown_condition[] = "cooldown_condition"; constexpr char energy_condition[] = "energy_condition"; constexpr char buff_condition[] = "buff_condition"; constexpr char debuff_condition[] = "debuff_condition"; constexpr char sub30_condition[] = "sub30_condition"; constexpr char stack_condition[] = "stack_condition"; class CooldownCondition : public ConditionC { public: CooldownCondition(AbilityId id) : _id(id) {} explicit CooldownCondition(const nlohmann::json &json); bool check(const TargetPtr &source, const TargetPtr &target, const Second &nextFreeInstant, const Second &nextFreeGCD) override; nlohmann::json serialize() override; virtual ~CooldownCondition() = default; private: AbilityId _id; }; class EnergyCondition : public ConditionC { public: explicit EnergyCondition(const nlohmann::json &json); EnergyCondition(double energy, bool above = true) : _energy(energy), _above(above) {} bool check(const TargetPtr &source, const TargetPtr &target, const Second &nextFreeInstant, const Second &nextFreeGCD) override; nlohmann::json serialize() override; virtual ~EnergyCondition() = default; private: double _energy{0}; bool _above{true}; }; class BuffCondition : public ConditionC { public: explicit BuffCondition(const nlohmann::json &json); BuffCondition(AbilityId id, Second timeRemaining, bool invert = false) : _buffId(id), _timeRemaing(timeRemaining), _invert(invert) {} bool check(const TargetPtr &source, const TargetPtr &target, const Second &nextFreeInstant, const Second &nextFreeGCD) override; nlohmann::json serialize() override; virtual ~BuffCondition() = default; private: AbilityId _buffId; Second _timeRemaing{0.0}; bool _invert{false}; }; class StackCondition : public ConditionC { public: explicit StackCondition(const nlohmann::json &json); StackCondition(AbilityId id, int stackCount = -1, bool invert = false) : _buffId(id), _stackCount(stackCount), _invert(invert) {} bool check(const TargetPtr &source, const TargetPtr &target, const Second &nextFreeInstant, const Second &nextFreeGCD) override; nlohmann::json serialize() override; virtual ~StackCondition() = default; private: AbilityId _buffId; int _stackCount; bool _invert{false}; }; class DebuffCondition : public ConditionC { public: explicit DebuffCondition(const nlohmann::json &json); DebuffCondition(AbilityId id, Second timeRemaining, bool invert = false) : _buffId(id), _timeRemaing(timeRemaining), _invert(invert) {} bool check(const TargetPtr &source, const TargetPtr &target, const Second &nextFreeInstant, const Second &nextFreeGCD) override; nlohmann::json serialize() override; virtual ~DebuffCondition() = default; private: AbilityId _buffId; Second _timeRemaing{0.0}; bool _invert{false}; }; class SubThirtyCondition : public ConditionC { public: SubThirtyCondition() = default; explicit SubThirtyCondition(const nlohmann::json &json); bool check(const TargetPtr &source, const TargetPtr &target, const Second &nextFreeInstant, const Second &nextFreeGCD) override; nlohmann::json serialize() override; virtual ~SubThirtyCondition() = default; }; using ConditionPtr = std::unique_ptr<ConditionC>; using Conditions = std::vector<ConditionPtr>; Conditions getCooldownFinishedCondition(AbilityId id); ConditionPtr getDeserializedCondition(const nlohmann::json &condition); nlohmann::json serializeConditions(const Conditions &conditions); Conditions deserializeConditions(const nlohmann::json &j); } // namespace Simulator
35.834783
97
0.726523
[ "vector" ]
9ed94a134926cb50a1859badc8906e977e6fd4c3
2,447
h
C
copasi/UI/CCopasiPlotSelectionDialog.h
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
64
2015-03-14T14:06:18.000Z
2022-02-04T23:19:08.000Z
copasi/UI/CCopasiPlotSelectionDialog.h
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
4
2017-08-16T10:26:46.000Z
2020-01-08T12:05:54.000Z
copasi/UI/CCopasiPlotSelectionDialog.h
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
28
2015-04-16T14:14:59.000Z
2022-03-28T12:04:14.000Z
// Copyright (C) 2019 - 2020 by Pedro Mendes, Rector and Visitors of the // University of Virginia, University of Heidelberg, and University // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2004 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #ifndef CCopasiPlotSelectionDialog_H__ #define CCopasiPlotSelectionDialog_H__ #include <vector> #include <QDialog> #include <QLabel> #include "copasi/UI/CQSimpleSelectionTree.h" class QWidget; class QPushButton; class QSplitter; class QCheckBox; class QHBoxLayout; class QVBoxLayout; class QLabel; class CDataObject; class CModel; class CCopasiSelectionWidget; class CCopasiPlotSelectionDialog: public QDialog { Q_OBJECT public: CCopasiPlotSelectionDialog(QWidget * parent = 0, const char * name = 0, bool modal = false, Qt::WindowFlags f = Qt::WindowFlags()); ~CCopasiPlotSelectionDialog(); void setOutputVectors(std::vector< const CDataObject * > *outputVector1, std::vector< const CDataObject * > *outputVector2); void setModel(CModel *model, const CQSimpleSelectionTree::ObjectClasses &classes); protected slots: void slotOKButtonClicked(); void slotCancelButtonClicked(); void slotExpertCheckBoxToggled(bool checked); protected: void setTabOrder(); protected: QCheckBox *mpExpertCheckBox; CCopasiSelectionWidget *mpXAxisSelectionWidget; CCopasiSelectionWidget *mpYAxisSelectionWidget; QSplitter *mpSplitter; QHBoxLayout *mpButtonBox; QVBoxLayout *mpMainLayout; QLabel *mpXAxisLabel; QLabel *mpYAxisLabel; QWidget *mpXAxisSelectionBox; QWidget *mpYAxisSelectionBox; std::vector< const CDataObject * > *mpXAxisOutputVector; std::vector< const CDataObject * > *mpYAxisOutputVector; }; #endif // CPlotSelectionDialog_H__
29.841463
133
0.760114
[ "vector", "model" ]
9eda91983b1f2cc45aefb95c3e6f444c03eb4363
56,788
c
C
src/sys/net/bridgestp.c
dnybz/MeshBSD
5c6c0539ce13d7cda9e2645e2e9e916e371f87b2
[ "BSD-3-Clause" ]
null
null
null
src/sys/net/bridgestp.c
dnybz/MeshBSD
5c6c0539ce13d7cda9e2645e2e9e916e371f87b2
[ "BSD-3-Clause" ]
null
null
null
src/sys/net/bridgestp.c
dnybz/MeshBSD
5c6c0539ce13d7cda9e2645e2e9e916e371f87b2
[ "BSD-3-Clause" ]
null
null
null
/* $NetBSD: bridgestp.c,v 1.5 2003/11/28 08:56:48 keihan Exp $ */ /* * Copyright (c) 2000 Jason L. Wright (jason@thought.net) * Copyright (c) 2006 Andrew Thompson (thompsa@FreeBSD.org) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 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. * * OpenBSD: bridgestp.c,v 1.5 2001/03/22 03:48:29 jason Exp */ /* * Implementation of the spanning tree protocol as defined in * ISO/IEC 802.1D-2004, June 9, 2004. */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: releng/11.0/sys/net/bridgestp.c 298995 2016-05-03 18:05:43Z pfg $"); #include <sys/param.h> #include <sys/systm.h> #include <sys/mbuf.h> #include <sys/socket.h> #include <sys/sockio.h> #include <sys/kernel.h> #include <sys/malloc.h> #include <sys/callout.h> #include <sys/module.h> #include <sys/proc.h> #include <sys/lock.h> #include <sys/mutex.h> #include <sys/taskqueue.h> #include <net/if.h> #include <net/if_var.h> #include <net/if_dl.h> #include <net/if_types.h> #include <net/if_llc.h> #include <net/if_media.h> #include <net/vnet.h> #include <netinet/in.h> #include <netinet/in_systm.h> #include <netinet/in_var.h> #include <netinet/if_ether.h> #include <net/bridgestp.h> #ifdef BRIDGESTP_DEBUG #define DPRINTF(fmt, arg...) printf("bstp: " fmt, ##arg) #else #define DPRINTF(fmt, arg...) (void)0 #endif #define PV2ADDR(pv, eaddr) do { \ eaddr[0] = pv >> 40; \ eaddr[1] = pv >> 32; \ eaddr[2] = pv >> 24; \ eaddr[3] = pv >> 16; \ eaddr[4] = pv >> 8; \ eaddr[5] = pv >> 0; \ } while (0) #define INFO_BETTER 1 #define INFO_SAME 0 #define INFO_WORSE -1 const uint8_t bstp_etheraddr[] = { 0x01, 0x80, 0xc2, 0x00, 0x00, 0x00 }; LIST_HEAD(, bstp_state) bstp_list; static struct mtx bstp_list_mtx; static void bstp_transmit(struct bstp_state *, struct bstp_port *); static void bstp_transmit_bpdu(struct bstp_state *, struct bstp_port *); static void bstp_transmit_tcn(struct bstp_state *, struct bstp_port *); static void bstp_decode_bpdu(struct bstp_port *, struct bstp_cbpdu *, struct bstp_config_unit *); static void bstp_send_bpdu(struct bstp_state *, struct bstp_port *, struct bstp_cbpdu *); static int bstp_pdu_flags(struct bstp_port *); static void bstp_received_stp(struct bstp_state *, struct bstp_port *, struct mbuf **, struct bstp_tbpdu *); static void bstp_received_rstp(struct bstp_state *, struct bstp_port *, struct mbuf **, struct bstp_tbpdu *); static void bstp_received_tcn(struct bstp_state *, struct bstp_port *, struct bstp_tcn_unit *); static void bstp_received_bpdu(struct bstp_state *, struct bstp_port *, struct bstp_config_unit *); static int bstp_pdu_rcvtype(struct bstp_port *, struct bstp_config_unit *); static int bstp_pdu_bettersame(struct bstp_port *, int); static int bstp_info_cmp(struct bstp_pri_vector *, struct bstp_pri_vector *); static int bstp_info_superior(struct bstp_pri_vector *, struct bstp_pri_vector *); static void bstp_assign_roles(struct bstp_state *); static void bstp_update_roles(struct bstp_state *, struct bstp_port *); static void bstp_update_state(struct bstp_state *, struct bstp_port *); static void bstp_update_tc(struct bstp_port *); static void bstp_update_info(struct bstp_port *); static void bstp_set_other_tcprop(struct bstp_port *); static void bstp_set_all_reroot(struct bstp_state *); static void bstp_set_all_sync(struct bstp_state *); static void bstp_set_port_state(struct bstp_port *, int); static void bstp_set_port_role(struct bstp_port *, int); static void bstp_set_port_proto(struct bstp_port *, int); static void bstp_set_port_tc(struct bstp_port *, int); static void bstp_set_timer_tc(struct bstp_port *); static void bstp_set_timer_msgage(struct bstp_port *); static int bstp_rerooted(struct bstp_state *, struct bstp_port *); static uint32_t bstp_calc_path_cost(struct bstp_port *); static void bstp_notify_state(void *, int); static void bstp_notify_rtage(void *, int); static void bstp_ifupdstatus(void *, int); static void bstp_enable_port(struct bstp_state *, struct bstp_port *); static void bstp_disable_port(struct bstp_state *, struct bstp_port *); static void bstp_tick(void *); static void bstp_timer_start(struct bstp_timer *, uint16_t); static void bstp_timer_stop(struct bstp_timer *); static void bstp_timer_latch(struct bstp_timer *); static int bstp_timer_dectest(struct bstp_timer *); static void bstp_hello_timer_expiry(struct bstp_state *, struct bstp_port *); static void bstp_message_age_expiry(struct bstp_state *, struct bstp_port *); static void bstp_migrate_delay_expiry(struct bstp_state *, struct bstp_port *); static void bstp_edge_delay_expiry(struct bstp_state *, struct bstp_port *); static int bstp_addr_cmp(const uint8_t *, const uint8_t *); static int bstp_same_bridgeid(uint64_t, uint64_t); static void bstp_reinit(struct bstp_state *); static void bstp_transmit(struct bstp_state *bs, struct bstp_port *bp) { if (bs->bs_running == 0) return; /* * a PDU can only be sent if we have tx quota left and the * hello timer is running. */ if (bp->bp_hello_timer.active == 0) { /* Test if it needs to be reset */ bstp_hello_timer_expiry(bs, bp); return; } if (bp->bp_txcount > bs->bs_txholdcount) /* Ran out of karma */ return; if (bp->bp_protover == BSTP_PROTO_RSTP) { bstp_transmit_bpdu(bs, bp); bp->bp_tc_ack = 0; } else { /* STP */ switch (bp->bp_role) { case BSTP_ROLE_DESIGNATED: bstp_transmit_bpdu(bs, bp); bp->bp_tc_ack = 0; break; case BSTP_ROLE_ROOT: bstp_transmit_tcn(bs, bp); break; } } bstp_timer_start(&bp->bp_hello_timer, bp->bp_desg_htime); bp->bp_flags &= ~BSTP_PORT_NEWINFO; } static void bstp_transmit_bpdu(struct bstp_state *bs, struct bstp_port *bp) { struct bstp_cbpdu bpdu; BSTP_LOCK_ASSERT(bs); bpdu.cbu_rootpri = htons(bp->bp_desg_pv.pv_root_id >> 48); PV2ADDR(bp->bp_desg_pv.pv_root_id, bpdu.cbu_rootaddr); bpdu.cbu_rootpathcost = htonl(bp->bp_desg_pv.pv_cost); bpdu.cbu_bridgepri = htons(bp->bp_desg_pv.pv_dbridge_id >> 48); PV2ADDR(bp->bp_desg_pv.pv_dbridge_id, bpdu.cbu_bridgeaddr); bpdu.cbu_portid = htons(bp->bp_port_id); bpdu.cbu_messageage = htons(bp->bp_desg_msg_age); bpdu.cbu_maxage = htons(bp->bp_desg_max_age); bpdu.cbu_hellotime = htons(bp->bp_desg_htime); bpdu.cbu_forwarddelay = htons(bp->bp_desg_fdelay); bpdu.cbu_flags = bstp_pdu_flags(bp); switch (bp->bp_protover) { case BSTP_PROTO_STP: bpdu.cbu_bpdutype = BSTP_MSGTYPE_CFG; break; case BSTP_PROTO_RSTP: bpdu.cbu_bpdutype = BSTP_MSGTYPE_RSTP; break; } bstp_send_bpdu(bs, bp, &bpdu); } static void bstp_transmit_tcn(struct bstp_state *bs, struct bstp_port *bp) { struct bstp_tbpdu bpdu; struct ifnet *ifp = bp->bp_ifp; struct ether_header *eh; struct mbuf *m; KASSERT(bp == bs->bs_root_port, ("%s: bad root port\n", __func__)); if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) return; m = m_gethdr(M_NOWAIT, MT_DATA); if (m == NULL) return; m->m_pkthdr.rcvif = ifp; m->m_pkthdr.len = sizeof(*eh) + sizeof(bpdu); m->m_len = m->m_pkthdr.len; eh = mtod(m, struct ether_header *); memcpy(eh->ether_shost, IF_LLADDR(ifp), ETHER_ADDR_LEN); memcpy(eh->ether_dhost, bstp_etheraddr, ETHER_ADDR_LEN); eh->ether_type = htons(sizeof(bpdu)); bpdu.tbu_ssap = bpdu.tbu_dsap = LLC_8021D_LSAP; bpdu.tbu_ctl = LLC_UI; bpdu.tbu_protoid = 0; bpdu.tbu_protover = 0; bpdu.tbu_bpdutype = BSTP_MSGTYPE_TCN; memcpy(mtod(m, caddr_t) + sizeof(*eh), &bpdu, sizeof(bpdu)); bp->bp_txcount++; ifp->if_transmit(ifp, m); } static void bstp_decode_bpdu(struct bstp_port *bp, struct bstp_cbpdu *cpdu, struct bstp_config_unit *cu) { int flags; cu->cu_pv.pv_root_id = (((uint64_t)ntohs(cpdu->cbu_rootpri)) << 48) | (((uint64_t)cpdu->cbu_rootaddr[0]) << 40) | (((uint64_t)cpdu->cbu_rootaddr[1]) << 32) | (((uint64_t)cpdu->cbu_rootaddr[2]) << 24) | (((uint64_t)cpdu->cbu_rootaddr[3]) << 16) | (((uint64_t)cpdu->cbu_rootaddr[4]) << 8) | (((uint64_t)cpdu->cbu_rootaddr[5]) << 0); cu->cu_pv.pv_dbridge_id = (((uint64_t)ntohs(cpdu->cbu_bridgepri)) << 48) | (((uint64_t)cpdu->cbu_bridgeaddr[0]) << 40) | (((uint64_t)cpdu->cbu_bridgeaddr[1]) << 32) | (((uint64_t)cpdu->cbu_bridgeaddr[2]) << 24) | (((uint64_t)cpdu->cbu_bridgeaddr[3]) << 16) | (((uint64_t)cpdu->cbu_bridgeaddr[4]) << 8) | (((uint64_t)cpdu->cbu_bridgeaddr[5]) << 0); cu->cu_pv.pv_cost = ntohl(cpdu->cbu_rootpathcost); cu->cu_message_age = ntohs(cpdu->cbu_messageage); cu->cu_max_age = ntohs(cpdu->cbu_maxage); cu->cu_hello_time = ntohs(cpdu->cbu_hellotime); cu->cu_forward_delay = ntohs(cpdu->cbu_forwarddelay); cu->cu_pv.pv_dport_id = ntohs(cpdu->cbu_portid); cu->cu_pv.pv_port_id = bp->bp_port_id; cu->cu_message_type = cpdu->cbu_bpdutype; /* Strip off unused flags in STP mode */ flags = cpdu->cbu_flags; switch (cpdu->cbu_protover) { case BSTP_PROTO_STP: flags &= BSTP_PDU_STPMASK; /* A STP BPDU explicitly conveys a Designated Port */ cu->cu_role = BSTP_ROLE_DESIGNATED; break; case BSTP_PROTO_RSTP: flags &= BSTP_PDU_RSTPMASK; break; } cu->cu_topology_change_ack = (flags & BSTP_PDU_F_TCA) ? 1 : 0; cu->cu_proposal = (flags & BSTP_PDU_F_P) ? 1 : 0; cu->cu_agree = (flags & BSTP_PDU_F_A) ? 1 : 0; cu->cu_learning = (flags & BSTP_PDU_F_L) ? 1 : 0; cu->cu_forwarding = (flags & BSTP_PDU_F_F) ? 1 : 0; cu->cu_topology_change = (flags & BSTP_PDU_F_TC) ? 1 : 0; switch ((flags & BSTP_PDU_PRMASK) >> BSTP_PDU_PRSHIFT) { case BSTP_PDU_F_ROOT: cu->cu_role = BSTP_ROLE_ROOT; break; case BSTP_PDU_F_ALT: cu->cu_role = BSTP_ROLE_ALTERNATE; break; case BSTP_PDU_F_DESG: cu->cu_role = BSTP_ROLE_DESIGNATED; break; } } static void bstp_send_bpdu(struct bstp_state *bs, struct bstp_port *bp, struct bstp_cbpdu *bpdu) { struct ifnet *ifp; struct mbuf *m; struct ether_header *eh; BSTP_LOCK_ASSERT(bs); ifp = bp->bp_ifp; if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) return; m = m_gethdr(M_NOWAIT, MT_DATA); if (m == NULL) return; eh = mtod(m, struct ether_header *); bpdu->cbu_ssap = bpdu->cbu_dsap = LLC_8021D_LSAP; bpdu->cbu_ctl = LLC_UI; bpdu->cbu_protoid = htons(BSTP_PROTO_ID); memcpy(eh->ether_shost, IF_LLADDR(ifp), ETHER_ADDR_LEN); memcpy(eh->ether_dhost, bstp_etheraddr, ETHER_ADDR_LEN); switch (bpdu->cbu_bpdutype) { case BSTP_MSGTYPE_CFG: bpdu->cbu_protover = BSTP_PROTO_STP; m->m_pkthdr.len = sizeof(*eh) + BSTP_BPDU_STP_LEN; eh->ether_type = htons(BSTP_BPDU_STP_LEN); memcpy(mtod(m, caddr_t) + sizeof(*eh), bpdu, BSTP_BPDU_STP_LEN); break; case BSTP_MSGTYPE_RSTP: bpdu->cbu_protover = BSTP_PROTO_RSTP; bpdu->cbu_versionlen = htons(0); m->m_pkthdr.len = sizeof(*eh) + BSTP_BPDU_RSTP_LEN; eh->ether_type = htons(BSTP_BPDU_RSTP_LEN); memcpy(mtod(m, caddr_t) + sizeof(*eh), bpdu, BSTP_BPDU_RSTP_LEN); break; default: panic("not implemented"); } m->m_pkthdr.rcvif = ifp; m->m_len = m->m_pkthdr.len; bp->bp_txcount++; ifp->if_transmit(ifp, m); } static int bstp_pdu_flags(struct bstp_port *bp) { int flags = 0; if (bp->bp_proposing && bp->bp_state != BSTP_IFSTATE_FORWARDING) flags |= BSTP_PDU_F_P; if (bp->bp_agree) flags |= BSTP_PDU_F_A; if (bp->bp_tc_timer.active) flags |= BSTP_PDU_F_TC; if (bp->bp_tc_ack) flags |= BSTP_PDU_F_TCA; switch (bp->bp_state) { case BSTP_IFSTATE_LEARNING: flags |= BSTP_PDU_F_L; break; case BSTP_IFSTATE_FORWARDING: flags |= (BSTP_PDU_F_L | BSTP_PDU_F_F); break; } switch (bp->bp_role) { case BSTP_ROLE_ROOT: flags |= (BSTP_PDU_F_ROOT << BSTP_PDU_PRSHIFT); break; case BSTP_ROLE_ALTERNATE: case BSTP_ROLE_BACKUP: /* fall through */ flags |= (BSTP_PDU_F_ALT << BSTP_PDU_PRSHIFT); break; case BSTP_ROLE_DESIGNATED: flags |= (BSTP_PDU_F_DESG << BSTP_PDU_PRSHIFT); break; } /* Strip off unused flags in either mode */ switch (bp->bp_protover) { case BSTP_PROTO_STP: flags &= BSTP_PDU_STPMASK; break; case BSTP_PROTO_RSTP: flags &= BSTP_PDU_RSTPMASK; break; } return (flags); } void bstp_input(struct bstp_port *bp, struct ifnet *ifp, struct mbuf *m) { struct bstp_state *bs = bp->bp_bs; struct ether_header *eh; struct bstp_tbpdu tpdu; uint16_t len; if (bp->bp_active == 0) { m_freem(m); return; } BSTP_LOCK(bs); eh = mtod(m, struct ether_header *); len = ntohs(eh->ether_type); if (len < sizeof(tpdu)) goto out; m_adj(m, ETHER_HDR_LEN); if (m->m_pkthdr.len > len) m_adj(m, len - m->m_pkthdr.len); if (m->m_len < sizeof(tpdu) && (m = m_pullup(m, sizeof(tpdu))) == NULL) goto out; memcpy(&tpdu, mtod(m, caddr_t), sizeof(tpdu)); /* basic packet checks */ if (tpdu.tbu_dsap != LLC_8021D_LSAP || tpdu.tbu_ssap != LLC_8021D_LSAP || tpdu.tbu_ctl != LLC_UI) goto out; if (tpdu.tbu_protoid != BSTP_PROTO_ID) goto out; /* * We can treat later versions of the PDU as the same as the maximum * version we implement. All additional parameters/flags are ignored. */ if (tpdu.tbu_protover > BSTP_PROTO_MAX) tpdu.tbu_protover = BSTP_PROTO_MAX; if (tpdu.tbu_protover != bp->bp_protover) { /* * Wait for the migration delay timer to expire before changing * protocol version to avoid flip-flops. */ if (bp->bp_flags & BSTP_PORT_CANMIGRATE) bstp_set_port_proto(bp, tpdu.tbu_protover); else goto out; } /* Clear operedge upon receiving a PDU on the port */ bp->bp_operedge = 0; bstp_timer_start(&bp->bp_edge_delay_timer, BSTP_DEFAULT_MIGRATE_DELAY); switch (tpdu.tbu_protover) { case BSTP_PROTO_STP: bstp_received_stp(bs, bp, &m, &tpdu); break; case BSTP_PROTO_RSTP: bstp_received_rstp(bs, bp, &m, &tpdu); break; } out: BSTP_UNLOCK(bs); if (m) m_freem(m); } static void bstp_received_stp(struct bstp_state *bs, struct bstp_port *bp, struct mbuf **mp, struct bstp_tbpdu *tpdu) { struct bstp_cbpdu cpdu; struct bstp_config_unit *cu = &bp->bp_msg_cu; struct bstp_tcn_unit tu; switch (tpdu->tbu_bpdutype) { case BSTP_MSGTYPE_TCN: tu.tu_message_type = tpdu->tbu_bpdutype; bstp_received_tcn(bs, bp, &tu); break; case BSTP_MSGTYPE_CFG: if ((*mp)->m_len < BSTP_BPDU_STP_LEN && (*mp = m_pullup(*mp, BSTP_BPDU_STP_LEN)) == NULL) return; memcpy(&cpdu, mtod(*mp, caddr_t), BSTP_BPDU_STP_LEN); bstp_decode_bpdu(bp, &cpdu, cu); bstp_received_bpdu(bs, bp, cu); break; } } static void bstp_received_rstp(struct bstp_state *bs, struct bstp_port *bp, struct mbuf **mp, struct bstp_tbpdu *tpdu) { struct bstp_cbpdu cpdu; struct bstp_config_unit *cu = &bp->bp_msg_cu; if (tpdu->tbu_bpdutype != BSTP_MSGTYPE_RSTP) return; if ((*mp)->m_len < BSTP_BPDU_RSTP_LEN && (*mp = m_pullup(*mp, BSTP_BPDU_RSTP_LEN)) == NULL) return; memcpy(&cpdu, mtod(*mp, caddr_t), BSTP_BPDU_RSTP_LEN); bstp_decode_bpdu(bp, &cpdu, cu); bstp_received_bpdu(bs, bp, cu); } static void bstp_received_tcn(struct bstp_state *bs, struct bstp_port *bp, struct bstp_tcn_unit *tcn) { bp->bp_rcvdtcn = 1; bstp_update_tc(bp); } static void bstp_received_bpdu(struct bstp_state *bs, struct bstp_port *bp, struct bstp_config_unit *cu) { int type; BSTP_LOCK_ASSERT(bs); /* We need to have transitioned to INFO_MINE before proceeding */ switch (bp->bp_infois) { case BSTP_INFO_DISABLED: case BSTP_INFO_AGED: return; } type = bstp_pdu_rcvtype(bp, cu); switch (type) { case BSTP_PDU_SUPERIOR: bs->bs_allsynced = 0; bp->bp_agreed = 0; bp->bp_proposing = 0; if (cu->cu_proposal && cu->cu_forwarding == 0) bp->bp_proposed = 1; if (cu->cu_topology_change) bp->bp_rcvdtc = 1; if (cu->cu_topology_change_ack) bp->bp_rcvdtca = 1; if (bp->bp_agree && !bstp_pdu_bettersame(bp, BSTP_INFO_RECEIVED)) bp->bp_agree = 0; /* copy the received priority and timers to the port */ bp->bp_port_pv = cu->cu_pv; bp->bp_port_msg_age = cu->cu_message_age; bp->bp_port_max_age = cu->cu_max_age; bp->bp_port_fdelay = cu->cu_forward_delay; bp->bp_port_htime = (cu->cu_hello_time > BSTP_MIN_HELLO_TIME ? cu->cu_hello_time : BSTP_MIN_HELLO_TIME); /* set expiry for the new info */ bstp_set_timer_msgage(bp); bp->bp_infois = BSTP_INFO_RECEIVED; bstp_assign_roles(bs); break; case BSTP_PDU_REPEATED: if (cu->cu_proposal && cu->cu_forwarding == 0) bp->bp_proposed = 1; if (cu->cu_topology_change) bp->bp_rcvdtc = 1; if (cu->cu_topology_change_ack) bp->bp_rcvdtca = 1; /* rearm the age timer */ bstp_set_timer_msgage(bp); break; case BSTP_PDU_INFERIOR: if (cu->cu_learning) { bp->bp_agreed = 1; bp->bp_proposing = 0; } break; case BSTP_PDU_INFERIORALT: /* * only point to point links are allowed fast * transitions to forwarding. */ if (cu->cu_agree && bp->bp_ptp_link) { bp->bp_agreed = 1; bp->bp_proposing = 0; } else bp->bp_agreed = 0; if (cu->cu_topology_change) bp->bp_rcvdtc = 1; if (cu->cu_topology_change_ack) bp->bp_rcvdtca = 1; break; case BSTP_PDU_OTHER: return; /* do nothing */ } /* update the state machines with the new data */ bstp_update_state(bs, bp); } static int bstp_pdu_rcvtype(struct bstp_port *bp, struct bstp_config_unit *cu) { int type; /* default return type */ type = BSTP_PDU_OTHER; switch (cu->cu_role) { case BSTP_ROLE_DESIGNATED: if (bstp_info_superior(&bp->bp_port_pv, &cu->cu_pv)) /* bpdu priority is superior */ type = BSTP_PDU_SUPERIOR; else if (bstp_info_cmp(&bp->bp_port_pv, &cu->cu_pv) == INFO_SAME) { if (bp->bp_port_msg_age != cu->cu_message_age || bp->bp_port_max_age != cu->cu_max_age || bp->bp_port_fdelay != cu->cu_forward_delay || bp->bp_port_htime != cu->cu_hello_time) /* bpdu priority is equal and timers differ */ type = BSTP_PDU_SUPERIOR; else /* bpdu is equal */ type = BSTP_PDU_REPEATED; } else /* bpdu priority is worse */ type = BSTP_PDU_INFERIOR; break; case BSTP_ROLE_ROOT: case BSTP_ROLE_ALTERNATE: case BSTP_ROLE_BACKUP: if (bstp_info_cmp(&bp->bp_port_pv, &cu->cu_pv) <= INFO_SAME) /* * not a designated port and priority is the same or * worse */ type = BSTP_PDU_INFERIORALT; break; } return (type); } static int bstp_pdu_bettersame(struct bstp_port *bp, int newinfo) { if (newinfo == BSTP_INFO_RECEIVED && bp->bp_infois == BSTP_INFO_RECEIVED && bstp_info_cmp(&bp->bp_port_pv, &bp->bp_msg_cu.cu_pv) >= INFO_SAME) return (1); if (newinfo == BSTP_INFO_MINE && bp->bp_infois == BSTP_INFO_MINE && bstp_info_cmp(&bp->bp_port_pv, &bp->bp_desg_pv) >= INFO_SAME) return (1); return (0); } static int bstp_info_cmp(struct bstp_pri_vector *pv, struct bstp_pri_vector *cpv) { if (cpv->pv_root_id < pv->pv_root_id) return (INFO_BETTER); if (cpv->pv_root_id > pv->pv_root_id) return (INFO_WORSE); if (cpv->pv_cost < pv->pv_cost) return (INFO_BETTER); if (cpv->pv_cost > pv->pv_cost) return (INFO_WORSE); if (cpv->pv_dbridge_id < pv->pv_dbridge_id) return (INFO_BETTER); if (cpv->pv_dbridge_id > pv->pv_dbridge_id) return (INFO_WORSE); if (cpv->pv_dport_id < pv->pv_dport_id) return (INFO_BETTER); if (cpv->pv_dport_id > pv->pv_dport_id) return (INFO_WORSE); return (INFO_SAME); } /* * This message priority vector is superior to the port priority vector and * will replace it if, and only if, the message priority vector is better than * the port priority vector, or the message has been transmitted from the same * designated bridge and designated port as the port priority vector. */ static int bstp_info_superior(struct bstp_pri_vector *pv, struct bstp_pri_vector *cpv) { if (bstp_info_cmp(pv, cpv) == INFO_BETTER || (bstp_same_bridgeid(pv->pv_dbridge_id, cpv->pv_dbridge_id) && (cpv->pv_dport_id & 0xfff) == (pv->pv_dport_id & 0xfff))) return (1); return (0); } static void bstp_assign_roles(struct bstp_state *bs) { struct bstp_port *bp, *rbp = NULL; struct bstp_pri_vector pv; /* default to our priority vector */ bs->bs_root_pv = bs->bs_bridge_pv; bs->bs_root_msg_age = 0; bs->bs_root_max_age = bs->bs_bridge_max_age; bs->bs_root_fdelay = bs->bs_bridge_fdelay; bs->bs_root_htime = bs->bs_bridge_htime; bs->bs_root_port = NULL; /* check if any received info supersedes us */ LIST_FOREACH(bp, &bs->bs_bplist, bp_next) { if (bp->bp_infois != BSTP_INFO_RECEIVED) continue; pv = bp->bp_port_pv; pv.pv_cost += bp->bp_path_cost; /* * The root priority vector is the best of the set comprising * the bridge priority vector plus all root path priority * vectors whose bridge address is not equal to us. */ if (bstp_same_bridgeid(pv.pv_dbridge_id, bs->bs_bridge_pv.pv_dbridge_id) == 0 && bstp_info_cmp(&bs->bs_root_pv, &pv) == INFO_BETTER) { /* the port vector replaces the root */ bs->bs_root_pv = pv; bs->bs_root_msg_age = bp->bp_port_msg_age + BSTP_MESSAGE_AGE_INCR; bs->bs_root_max_age = bp->bp_port_max_age; bs->bs_root_fdelay = bp->bp_port_fdelay; bs->bs_root_htime = bp->bp_port_htime; rbp = bp; } } LIST_FOREACH(bp, &bs->bs_bplist, bp_next) { /* calculate the port designated vector */ bp->bp_desg_pv.pv_root_id = bs->bs_root_pv.pv_root_id; bp->bp_desg_pv.pv_cost = bs->bs_root_pv.pv_cost; bp->bp_desg_pv.pv_dbridge_id = bs->bs_bridge_pv.pv_dbridge_id; bp->bp_desg_pv.pv_dport_id = bp->bp_port_id; bp->bp_desg_pv.pv_port_id = bp->bp_port_id; /* calculate designated times */ bp->bp_desg_msg_age = bs->bs_root_msg_age; bp->bp_desg_max_age = bs->bs_root_max_age; bp->bp_desg_fdelay = bs->bs_root_fdelay; bp->bp_desg_htime = bs->bs_bridge_htime; switch (bp->bp_infois) { case BSTP_INFO_DISABLED: bstp_set_port_role(bp, BSTP_ROLE_DISABLED); break; case BSTP_INFO_AGED: bstp_set_port_role(bp, BSTP_ROLE_DESIGNATED); bstp_update_info(bp); break; case BSTP_INFO_MINE: bstp_set_port_role(bp, BSTP_ROLE_DESIGNATED); /* update the port info if stale */ if (bstp_info_cmp(&bp->bp_port_pv, &bp->bp_desg_pv) != INFO_SAME || (rbp != NULL && (bp->bp_port_msg_age != rbp->bp_port_msg_age || bp->bp_port_max_age != rbp->bp_port_max_age || bp->bp_port_fdelay != rbp->bp_port_fdelay || bp->bp_port_htime != rbp->bp_port_htime))) bstp_update_info(bp); break; case BSTP_INFO_RECEIVED: if (bp == rbp) { /* * root priority is derived from this * port, make it the root port. */ bstp_set_port_role(bp, BSTP_ROLE_ROOT); bs->bs_root_port = bp; } else if (bstp_info_cmp(&bp->bp_port_pv, &bp->bp_desg_pv) == INFO_BETTER) { /* * the port priority is lower than the root * port. */ bstp_set_port_role(bp, BSTP_ROLE_DESIGNATED); bstp_update_info(bp); } else { if (bstp_same_bridgeid( bp->bp_port_pv.pv_dbridge_id, bs->bs_bridge_pv.pv_dbridge_id)) { /* * the designated bridge refers to * another port on this bridge. */ bstp_set_port_role(bp, BSTP_ROLE_BACKUP); } else { /* * the port is an inferior path to the * root bridge. */ bstp_set_port_role(bp, BSTP_ROLE_ALTERNATE); } } break; } } } static void bstp_update_state(struct bstp_state *bs, struct bstp_port *bp) { struct bstp_port *bp2; int synced; BSTP_LOCK_ASSERT(bs); /* check if all the ports have syncronised again */ if (!bs->bs_allsynced) { synced = 1; LIST_FOREACH(bp2, &bs->bs_bplist, bp_next) { if (!(bp2->bp_synced || bp2->bp_role == BSTP_ROLE_ROOT)) { synced = 0; break; } } bs->bs_allsynced = synced; } bstp_update_roles(bs, bp); bstp_update_tc(bp); } static void bstp_update_roles(struct bstp_state *bs, struct bstp_port *bp) { switch (bp->bp_role) { case BSTP_ROLE_DISABLED: /* Clear any flags if set */ if (bp->bp_sync || !bp->bp_synced || bp->bp_reroot) { bp->bp_sync = 0; bp->bp_synced = 1; bp->bp_reroot = 0; } break; case BSTP_ROLE_ALTERNATE: case BSTP_ROLE_BACKUP: if ((bs->bs_allsynced && !bp->bp_agree) || (bp->bp_proposed && bp->bp_agree)) { bp->bp_proposed = 0; bp->bp_agree = 1; bp->bp_flags |= BSTP_PORT_NEWINFO; DPRINTF("%s -> ALTERNATE_AGREED\n", bp->bp_ifp->if_xname); } if (bp->bp_proposed && !bp->bp_agree) { bstp_set_all_sync(bs); bp->bp_proposed = 0; DPRINTF("%s -> ALTERNATE_PROPOSED\n", bp->bp_ifp->if_xname); } /* Clear any flags if set */ if (bp->bp_sync || !bp->bp_synced || bp->bp_reroot) { bp->bp_sync = 0; bp->bp_synced = 1; bp->bp_reroot = 0; DPRINTF("%s -> ALTERNATE_PORT\n", bp->bp_ifp->if_xname); } break; case BSTP_ROLE_ROOT: if (bp->bp_state != BSTP_IFSTATE_FORWARDING && !bp->bp_reroot) { bstp_set_all_reroot(bs); DPRINTF("%s -> ROOT_REROOT\n", bp->bp_ifp->if_xname); } if ((bs->bs_allsynced && !bp->bp_agree) || (bp->bp_proposed && bp->bp_agree)) { bp->bp_proposed = 0; bp->bp_sync = 0; bp->bp_agree = 1; bp->bp_flags |= BSTP_PORT_NEWINFO; DPRINTF("%s -> ROOT_AGREED\n", bp->bp_ifp->if_xname); } if (bp->bp_proposed && !bp->bp_agree) { bstp_set_all_sync(bs); bp->bp_proposed = 0; DPRINTF("%s -> ROOT_PROPOSED\n", bp->bp_ifp->if_xname); } if (bp->bp_state != BSTP_IFSTATE_FORWARDING && (bp->bp_forward_delay_timer.active == 0 || (bstp_rerooted(bs, bp) && bp->bp_recent_backup_timer.active == 0 && bp->bp_protover == BSTP_PROTO_RSTP))) { switch (bp->bp_state) { case BSTP_IFSTATE_DISCARDING: bstp_set_port_state(bp, BSTP_IFSTATE_LEARNING); break; case BSTP_IFSTATE_LEARNING: bstp_set_port_state(bp, BSTP_IFSTATE_FORWARDING); break; } } if (bp->bp_state == BSTP_IFSTATE_FORWARDING && bp->bp_reroot) { bp->bp_reroot = 0; DPRINTF("%s -> ROOT_REROOTED\n", bp->bp_ifp->if_xname); } break; case BSTP_ROLE_DESIGNATED: if (bp->bp_recent_root_timer.active == 0 && bp->bp_reroot) { bp->bp_reroot = 0; DPRINTF("%s -> DESIGNATED_RETIRED\n", bp->bp_ifp->if_xname); } if ((bp->bp_state == BSTP_IFSTATE_DISCARDING && !bp->bp_synced) || (bp->bp_agreed && !bp->bp_synced) || (bp->bp_operedge && !bp->bp_synced) || (bp->bp_sync && bp->bp_synced)) { bstp_timer_stop(&bp->bp_recent_root_timer); bp->bp_synced = 1; bp->bp_sync = 0; DPRINTF("%s -> DESIGNATED_SYNCED\n", bp->bp_ifp->if_xname); } if (bp->bp_state != BSTP_IFSTATE_FORWARDING && !bp->bp_agreed && !bp->bp_proposing && !bp->bp_operedge) { bp->bp_proposing = 1; bp->bp_flags |= BSTP_PORT_NEWINFO; bstp_timer_start(&bp->bp_edge_delay_timer, (bp->bp_ptp_link ? BSTP_DEFAULT_MIGRATE_DELAY : bp->bp_desg_max_age)); DPRINTF("%s -> DESIGNATED_PROPOSE\n", bp->bp_ifp->if_xname); } if (bp->bp_state != BSTP_IFSTATE_FORWARDING && (bp->bp_forward_delay_timer.active == 0 || bp->bp_agreed || bp->bp_operedge) && (bp->bp_recent_root_timer.active == 0 || !bp->bp_reroot) && !bp->bp_sync) { if (bp->bp_agreed) DPRINTF("%s -> AGREED\n", bp->bp_ifp->if_xname); /* * If agreed|operedge then go straight to forwarding, * otherwise follow discard -> learn -> forward. */ if (bp->bp_agreed || bp->bp_operedge || bp->bp_state == BSTP_IFSTATE_LEARNING) { bstp_set_port_state(bp, BSTP_IFSTATE_FORWARDING); bp->bp_agreed = bp->bp_protover; } else if (bp->bp_state == BSTP_IFSTATE_DISCARDING) bstp_set_port_state(bp, BSTP_IFSTATE_LEARNING); } if (((bp->bp_sync && !bp->bp_synced) || (bp->bp_reroot && bp->bp_recent_root_timer.active) || (bp->bp_flags & BSTP_PORT_DISPUTED)) && !bp->bp_operedge && bp->bp_state != BSTP_IFSTATE_DISCARDING) { bstp_set_port_state(bp, BSTP_IFSTATE_DISCARDING); bp->bp_flags &= ~BSTP_PORT_DISPUTED; bstp_timer_start(&bp->bp_forward_delay_timer, bp->bp_protover == BSTP_PROTO_RSTP ? bp->bp_desg_htime : bp->bp_desg_fdelay); DPRINTF("%s -> DESIGNATED_DISCARD\n", bp->bp_ifp->if_xname); } break; } if (bp->bp_flags & BSTP_PORT_NEWINFO) bstp_transmit(bs, bp); } static void bstp_update_tc(struct bstp_port *bp) { switch (bp->bp_tcstate) { case BSTP_TCSTATE_ACTIVE: if ((bp->bp_role != BSTP_ROLE_DESIGNATED && bp->bp_role != BSTP_ROLE_ROOT) || bp->bp_operedge) bstp_set_port_tc(bp, BSTP_TCSTATE_LEARNING); if (bp->bp_rcvdtcn) bstp_set_port_tc(bp, BSTP_TCSTATE_TCN); if (bp->bp_rcvdtc) bstp_set_port_tc(bp, BSTP_TCSTATE_TC); if (bp->bp_tc_prop && !bp->bp_operedge) bstp_set_port_tc(bp, BSTP_TCSTATE_PROPAG); if (bp->bp_rcvdtca) bstp_set_port_tc(bp, BSTP_TCSTATE_ACK); break; case BSTP_TCSTATE_INACTIVE: if ((bp->bp_state == BSTP_IFSTATE_LEARNING || bp->bp_state == BSTP_IFSTATE_FORWARDING) && bp->bp_fdbflush == 0) bstp_set_port_tc(bp, BSTP_TCSTATE_LEARNING); break; case BSTP_TCSTATE_LEARNING: if (bp->bp_rcvdtc || bp->bp_rcvdtcn || bp->bp_rcvdtca || bp->bp_tc_prop) bstp_set_port_tc(bp, BSTP_TCSTATE_LEARNING); else if (bp->bp_role != BSTP_ROLE_DESIGNATED && bp->bp_role != BSTP_ROLE_ROOT && bp->bp_state == BSTP_IFSTATE_DISCARDING) bstp_set_port_tc(bp, BSTP_TCSTATE_INACTIVE); if ((bp->bp_role == BSTP_ROLE_DESIGNATED || bp->bp_role == BSTP_ROLE_ROOT) && bp->bp_state == BSTP_IFSTATE_FORWARDING && !bp->bp_operedge) bstp_set_port_tc(bp, BSTP_TCSTATE_DETECTED); break; /* these are transient states and go straight back to ACTIVE */ case BSTP_TCSTATE_DETECTED: case BSTP_TCSTATE_TCN: case BSTP_TCSTATE_TC: case BSTP_TCSTATE_PROPAG: case BSTP_TCSTATE_ACK: DPRINTF("Invalid TC state for %s\n", bp->bp_ifp->if_xname); break; } } static void bstp_update_info(struct bstp_port *bp) { struct bstp_state *bs = bp->bp_bs; bp->bp_proposing = 0; bp->bp_proposed = 0; if (bp->bp_agreed && !bstp_pdu_bettersame(bp, BSTP_INFO_MINE)) bp->bp_agreed = 0; if (bp->bp_synced && !bp->bp_agreed) { bp->bp_synced = 0; bs->bs_allsynced = 0; } /* copy the designated pv to the port */ bp->bp_port_pv = bp->bp_desg_pv; bp->bp_port_msg_age = bp->bp_desg_msg_age; bp->bp_port_max_age = bp->bp_desg_max_age; bp->bp_port_fdelay = bp->bp_desg_fdelay; bp->bp_port_htime = bp->bp_desg_htime; bp->bp_infois = BSTP_INFO_MINE; /* Set transmit flag but do not immediately send */ bp->bp_flags |= BSTP_PORT_NEWINFO; } /* set tcprop on every port other than the caller */ static void bstp_set_other_tcprop(struct bstp_port *bp) { struct bstp_state *bs = bp->bp_bs; struct bstp_port *bp2; BSTP_LOCK_ASSERT(bs); LIST_FOREACH(bp2, &bs->bs_bplist, bp_next) { if (bp2 == bp) continue; bp2->bp_tc_prop = 1; } } static void bstp_set_all_reroot(struct bstp_state *bs) { struct bstp_port *bp; BSTP_LOCK_ASSERT(bs); LIST_FOREACH(bp, &bs->bs_bplist, bp_next) bp->bp_reroot = 1; } static void bstp_set_all_sync(struct bstp_state *bs) { struct bstp_port *bp; BSTP_LOCK_ASSERT(bs); LIST_FOREACH(bp, &bs->bs_bplist, bp_next) { bp->bp_sync = 1; bp->bp_synced = 0; /* Not explicit in spec */ } bs->bs_allsynced = 0; } static void bstp_set_port_state(struct bstp_port *bp, int state) { if (bp->bp_state == state) return; bp->bp_state = state; switch (bp->bp_state) { case BSTP_IFSTATE_DISCARDING: DPRINTF("state changed to DISCARDING on %s\n", bp->bp_ifp->if_xname); break; case BSTP_IFSTATE_LEARNING: DPRINTF("state changed to LEARNING on %s\n", bp->bp_ifp->if_xname); bstp_timer_start(&bp->bp_forward_delay_timer, bp->bp_protover == BSTP_PROTO_RSTP ? bp->bp_desg_htime : bp->bp_desg_fdelay); break; case BSTP_IFSTATE_FORWARDING: DPRINTF("state changed to FORWARDING on %s\n", bp->bp_ifp->if_xname); bstp_timer_stop(&bp->bp_forward_delay_timer); /* Record that we enabled forwarding */ bp->bp_forward_transitions++; break; } /* notify the parent bridge */ taskqueue_enqueue(taskqueue_swi, &bp->bp_statetask); } static void bstp_set_port_role(struct bstp_port *bp, int role) { struct bstp_state *bs = bp->bp_bs; if (bp->bp_role == role) return; /* perform pre-change tasks */ switch (bp->bp_role) { case BSTP_ROLE_DISABLED: bstp_timer_start(&bp->bp_forward_delay_timer, bp->bp_desg_max_age); break; case BSTP_ROLE_BACKUP: bstp_timer_start(&bp->bp_recent_backup_timer, bp->bp_desg_htime * 2); /* fall through */ case BSTP_ROLE_ALTERNATE: bstp_timer_start(&bp->bp_forward_delay_timer, bp->bp_desg_fdelay); bp->bp_sync = 0; bp->bp_synced = 1; bp->bp_reroot = 0; break; case BSTP_ROLE_ROOT: bstp_timer_start(&bp->bp_recent_root_timer, BSTP_DEFAULT_FORWARD_DELAY); break; } bp->bp_role = role; /* clear values not carried between roles */ bp->bp_proposing = 0; bs->bs_allsynced = 0; /* initialise the new role */ switch (bp->bp_role) { case BSTP_ROLE_DISABLED: case BSTP_ROLE_ALTERNATE: case BSTP_ROLE_BACKUP: DPRINTF("%s role -> ALT/BACK/DISABLED\n", bp->bp_ifp->if_xname); bstp_set_port_state(bp, BSTP_IFSTATE_DISCARDING); bstp_timer_stop(&bp->bp_recent_root_timer); bstp_timer_latch(&bp->bp_forward_delay_timer); bp->bp_sync = 0; bp->bp_synced = 1; bp->bp_reroot = 0; break; case BSTP_ROLE_ROOT: DPRINTF("%s role -> ROOT\n", bp->bp_ifp->if_xname); bstp_set_port_state(bp, BSTP_IFSTATE_DISCARDING); bstp_timer_latch(&bp->bp_recent_root_timer); bp->bp_proposing = 0; break; case BSTP_ROLE_DESIGNATED: DPRINTF("%s role -> DESIGNATED\n", bp->bp_ifp->if_xname); bstp_timer_start(&bp->bp_hello_timer, bp->bp_desg_htime); bp->bp_agree = 0; break; } /* let the TC state know that the role changed */ bstp_update_tc(bp); } static void bstp_set_port_proto(struct bstp_port *bp, int proto) { struct bstp_state *bs = bp->bp_bs; /* supported protocol versions */ switch (proto) { case BSTP_PROTO_STP: /* we can downgrade protocols only */ bstp_timer_stop(&bp->bp_migrate_delay_timer); /* clear unsupported features */ bp->bp_operedge = 0; /* STP compat mode only uses 16 bits of the 32 */ if (bp->bp_path_cost > 65535) bp->bp_path_cost = 65535; break; case BSTP_PROTO_RSTP: bstp_timer_start(&bp->bp_migrate_delay_timer, bs->bs_migration_delay); break; default: DPRINTF("Unsupported STP version %d\n", proto); return; } bp->bp_protover = proto; bp->bp_flags &= ~BSTP_PORT_CANMIGRATE; } static void bstp_set_port_tc(struct bstp_port *bp, int state) { struct bstp_state *bs = bp->bp_bs; bp->bp_tcstate = state; /* initialise the new state */ switch (bp->bp_tcstate) { case BSTP_TCSTATE_ACTIVE: DPRINTF("%s -> TC_ACTIVE\n", bp->bp_ifp->if_xname); /* nothing to do */ break; case BSTP_TCSTATE_INACTIVE: bstp_timer_stop(&bp->bp_tc_timer); /* flush routes on the parent bridge */ bp->bp_fdbflush = 1; taskqueue_enqueue(taskqueue_swi, &bp->bp_rtagetask); bp->bp_tc_ack = 0; DPRINTF("%s -> TC_INACTIVE\n", bp->bp_ifp->if_xname); break; case BSTP_TCSTATE_LEARNING: bp->bp_rcvdtc = 0; bp->bp_rcvdtcn = 0; bp->bp_rcvdtca = 0; bp->bp_tc_prop = 0; DPRINTF("%s -> TC_LEARNING\n", bp->bp_ifp->if_xname); break; case BSTP_TCSTATE_DETECTED: bstp_set_timer_tc(bp); bstp_set_other_tcprop(bp); /* send out notification */ bp->bp_flags |= BSTP_PORT_NEWINFO; bstp_transmit(bs, bp); getmicrotime(&bs->bs_last_tc_time); DPRINTF("%s -> TC_DETECTED\n", bp->bp_ifp->if_xname); bp->bp_tcstate = BSTP_TCSTATE_ACTIVE; /* UCT */ break; case BSTP_TCSTATE_TCN: bstp_set_timer_tc(bp); DPRINTF("%s -> TC_TCN\n", bp->bp_ifp->if_xname); /* fall through */ case BSTP_TCSTATE_TC: bp->bp_rcvdtc = 0; bp->bp_rcvdtcn = 0; if (bp->bp_role == BSTP_ROLE_DESIGNATED) bp->bp_tc_ack = 1; bstp_set_other_tcprop(bp); DPRINTF("%s -> TC_TC\n", bp->bp_ifp->if_xname); bp->bp_tcstate = BSTP_TCSTATE_ACTIVE; /* UCT */ break; case BSTP_TCSTATE_PROPAG: /* flush routes on the parent bridge */ bp->bp_fdbflush = 1; taskqueue_enqueue(taskqueue_swi, &bp->bp_rtagetask); bp->bp_tc_prop = 0; bstp_set_timer_tc(bp); DPRINTF("%s -> TC_PROPAG\n", bp->bp_ifp->if_xname); bp->bp_tcstate = BSTP_TCSTATE_ACTIVE; /* UCT */ break; case BSTP_TCSTATE_ACK: bstp_timer_stop(&bp->bp_tc_timer); bp->bp_rcvdtca = 0; DPRINTF("%s -> TC_ACK\n", bp->bp_ifp->if_xname); bp->bp_tcstate = BSTP_TCSTATE_ACTIVE; /* UCT */ break; } } static void bstp_set_timer_tc(struct bstp_port *bp) { struct bstp_state *bs = bp->bp_bs; if (bp->bp_tc_timer.active) return; switch (bp->bp_protover) { case BSTP_PROTO_RSTP: bstp_timer_start(&bp->bp_tc_timer, bp->bp_desg_htime + BSTP_TICK_VAL); bp->bp_flags |= BSTP_PORT_NEWINFO; break; case BSTP_PROTO_STP: bstp_timer_start(&bp->bp_tc_timer, bs->bs_root_max_age + bs->bs_root_fdelay); break; } } static void bstp_set_timer_msgage(struct bstp_port *bp) { if (bp->bp_port_msg_age + BSTP_MESSAGE_AGE_INCR <= bp->bp_port_max_age) { bstp_timer_start(&bp->bp_message_age_timer, bp->bp_port_htime * 3); } else /* expires immediately */ bstp_timer_start(&bp->bp_message_age_timer, 0); } static int bstp_rerooted(struct bstp_state *bs, struct bstp_port *bp) { struct bstp_port *bp2; int rr_set = 0; LIST_FOREACH(bp2, &bs->bs_bplist, bp_next) { if (bp2 == bp) continue; if (bp2->bp_recent_root_timer.active) { rr_set = 1; break; } } return (!rr_set); } int bstp_set_htime(struct bstp_state *bs, int t) { /* convert seconds to ticks */ t *= BSTP_TICK_VAL; /* value can only be changed in leagacy stp mode */ if (bs->bs_protover != BSTP_PROTO_STP) return (EPERM); if (t < BSTP_MIN_HELLO_TIME || t > BSTP_MAX_HELLO_TIME) return (EINVAL); BSTP_LOCK(bs); bs->bs_bridge_htime = t; bstp_reinit(bs); BSTP_UNLOCK(bs); return (0); } int bstp_set_fdelay(struct bstp_state *bs, int t) { /* convert seconds to ticks */ t *= BSTP_TICK_VAL; if (t < BSTP_MIN_FORWARD_DELAY || t > BSTP_MAX_FORWARD_DELAY) return (EINVAL); BSTP_LOCK(bs); bs->bs_bridge_fdelay = t; bstp_reinit(bs); BSTP_UNLOCK(bs); return (0); } int bstp_set_maxage(struct bstp_state *bs, int t) { /* convert seconds to ticks */ t *= BSTP_TICK_VAL; if (t < BSTP_MIN_MAX_AGE || t > BSTP_MAX_MAX_AGE) return (EINVAL); BSTP_LOCK(bs); bs->bs_bridge_max_age = t; bstp_reinit(bs); BSTP_UNLOCK(bs); return (0); } int bstp_set_holdcount(struct bstp_state *bs, int count) { struct bstp_port *bp; if (count < BSTP_MIN_HOLD_COUNT || count > BSTP_MAX_HOLD_COUNT) return (EINVAL); BSTP_LOCK(bs); bs->bs_txholdcount = count; LIST_FOREACH(bp, &bs->bs_bplist, bp_next) bp->bp_txcount = 0; BSTP_UNLOCK(bs); return (0); } int bstp_set_protocol(struct bstp_state *bs, int proto) { struct bstp_port *bp; switch (proto) { /* Supported protocol versions */ case BSTP_PROTO_STP: case BSTP_PROTO_RSTP: break; default: return (EINVAL); } BSTP_LOCK(bs); bs->bs_protover = proto; bs->bs_bridge_htime = BSTP_DEFAULT_HELLO_TIME; LIST_FOREACH(bp, &bs->bs_bplist, bp_next) { /* reinit state */ bp->bp_infois = BSTP_INFO_DISABLED; bp->bp_txcount = 0; bstp_set_port_proto(bp, bs->bs_protover); bstp_set_port_role(bp, BSTP_ROLE_DISABLED); bstp_set_port_tc(bp, BSTP_TCSTATE_INACTIVE); bstp_timer_stop(&bp->bp_recent_backup_timer); } bstp_reinit(bs); BSTP_UNLOCK(bs); return (0); } int bstp_set_priority(struct bstp_state *bs, int pri) { if (pri < 0 || pri > BSTP_MAX_PRIORITY) return (EINVAL); /* Limit to steps of 4096 */ pri -= pri % 4096; BSTP_LOCK(bs); bs->bs_bridge_priority = pri; bstp_reinit(bs); BSTP_UNLOCK(bs); return (0); } int bstp_set_port_priority(struct bstp_port *bp, int pri) { struct bstp_state *bs = bp->bp_bs; if (pri < 0 || pri > BSTP_MAX_PORT_PRIORITY) return (EINVAL); /* Limit to steps of 16 */ pri -= pri % 16; BSTP_LOCK(bs); bp->bp_priority = pri; bstp_reinit(bs); BSTP_UNLOCK(bs); return (0); } int bstp_set_path_cost(struct bstp_port *bp, uint32_t path_cost) { struct bstp_state *bs = bp->bp_bs; if (path_cost > BSTP_MAX_PATH_COST) return (EINVAL); /* STP compat mode only uses 16 bits of the 32 */ if (bp->bp_protover == BSTP_PROTO_STP && path_cost > 65535) path_cost = 65535; BSTP_LOCK(bs); if (path_cost == 0) { /* use auto */ bp->bp_flags &= ~BSTP_PORT_ADMCOST; bp->bp_path_cost = bstp_calc_path_cost(bp); } else { bp->bp_path_cost = path_cost; bp->bp_flags |= BSTP_PORT_ADMCOST; } bstp_reinit(bs); BSTP_UNLOCK(bs); return (0); } int bstp_set_edge(struct bstp_port *bp, int set) { struct bstp_state *bs = bp->bp_bs; BSTP_LOCK(bs); if ((bp->bp_operedge = set) == 0) bp->bp_flags &= ~BSTP_PORT_ADMEDGE; else bp->bp_flags |= BSTP_PORT_ADMEDGE; BSTP_UNLOCK(bs); return (0); } int bstp_set_autoedge(struct bstp_port *bp, int set) { struct bstp_state *bs = bp->bp_bs; BSTP_LOCK(bs); if (set) { bp->bp_flags |= BSTP_PORT_AUTOEDGE; /* we may be able to transition straight to edge */ if (bp->bp_edge_delay_timer.active == 0) bstp_edge_delay_expiry(bs, bp); } else bp->bp_flags &= ~BSTP_PORT_AUTOEDGE; BSTP_UNLOCK(bs); return (0); } int bstp_set_ptp(struct bstp_port *bp, int set) { struct bstp_state *bs = bp->bp_bs; BSTP_LOCK(bs); bp->bp_ptp_link = set; BSTP_UNLOCK(bs); return (0); } int bstp_set_autoptp(struct bstp_port *bp, int set) { struct bstp_state *bs = bp->bp_bs; BSTP_LOCK(bs); if (set) { bp->bp_flags |= BSTP_PORT_AUTOPTP; if (bp->bp_role != BSTP_ROLE_DISABLED) taskqueue_enqueue(taskqueue_swi, &bp->bp_mediatask); } else bp->bp_flags &= ~BSTP_PORT_AUTOPTP; BSTP_UNLOCK(bs); return (0); } /* * Calculate the path cost according to the link speed. */ static uint32_t bstp_calc_path_cost(struct bstp_port *bp) { struct ifnet *ifp = bp->bp_ifp; uint32_t path_cost; /* If the priority has been manually set then retain the value */ if (bp->bp_flags & BSTP_PORT_ADMCOST) return bp->bp_path_cost; if (ifp->if_link_state == LINK_STATE_DOWN) { /* Recalc when the link comes up again */ bp->bp_flags |= BSTP_PORT_PNDCOST; return (BSTP_DEFAULT_PATH_COST); } if (ifp->if_baudrate < 1000) return (BSTP_DEFAULT_PATH_COST); /* formula from section 17.14, IEEE Std 802.1D-2004 */ path_cost = 20000000000ULL / (ifp->if_baudrate / 1000); if (path_cost > BSTP_MAX_PATH_COST) path_cost = BSTP_MAX_PATH_COST; /* STP compat mode only uses 16 bits of the 32 */ if (bp->bp_protover == BSTP_PROTO_STP && path_cost > 65535) path_cost = 65535; return (path_cost); } /* * Notify the bridge that a port state has changed, we need to do this from a * taskqueue to avoid a LOR. */ static void bstp_notify_state(void *arg, int pending) { struct bstp_port *bp = (struct bstp_port *)arg; struct bstp_state *bs = bp->bp_bs; if (bp->bp_active == 1 && bs->bs_state_cb != NULL) (*bs->bs_state_cb)(bp->bp_ifp, bp->bp_state); } /* * Flush the routes on the bridge port, we need to do this from a * taskqueue to avoid a LOR. */ static void bstp_notify_rtage(void *arg, int pending) { struct bstp_port *bp = (struct bstp_port *)arg; struct bstp_state *bs = bp->bp_bs; int age = 0; BSTP_LOCK(bs); switch (bp->bp_protover) { case BSTP_PROTO_STP: /* convert to seconds */ age = bp->bp_desg_fdelay / BSTP_TICK_VAL; break; case BSTP_PROTO_RSTP: age = 0; break; } BSTP_UNLOCK(bs); if (bp->bp_active == 1 && bs->bs_rtage_cb != NULL) (*bs->bs_rtage_cb)(bp->bp_ifp, age); /* flush is complete */ BSTP_LOCK(bs); bp->bp_fdbflush = 0; BSTP_UNLOCK(bs); } void bstp_linkstate(struct bstp_port *bp) { struct bstp_state *bs = bp->bp_bs; if (!bp->bp_active) return; bstp_ifupdstatus(bp, 0); BSTP_LOCK(bs); bstp_update_state(bs, bp); BSTP_UNLOCK(bs); } static void bstp_ifupdstatus(void *arg, int pending) { struct bstp_port *bp = (struct bstp_port *)arg; struct bstp_state *bs = bp->bp_bs; struct ifnet *ifp = bp->bp_ifp; struct ifmediareq ifmr; int error, changed; if (!bp->bp_active) return; bzero((char *)&ifmr, sizeof(ifmr)); error = (*ifp->if_ioctl)(ifp, SIOCGIFMEDIA, (caddr_t)&ifmr); BSTP_LOCK(bs); changed = 0; if ((error == 0) && (ifp->if_flags & IFF_UP)) { if (ifmr.ifm_status & IFM_ACTIVE) { /* A full-duplex link is assumed to be point to point */ if (bp->bp_flags & BSTP_PORT_AUTOPTP) { int fdx; fdx = ifmr.ifm_active & IFM_FDX ? 1 : 0; if (bp->bp_ptp_link ^ fdx) { bp->bp_ptp_link = fdx; changed = 1; } } /* Calc the cost if the link was down previously */ if (bp->bp_flags & BSTP_PORT_PNDCOST) { uint32_t cost; cost = bstp_calc_path_cost(bp); if (bp->bp_path_cost != cost) { bp->bp_path_cost = cost; changed = 1; } bp->bp_flags &= ~BSTP_PORT_PNDCOST; } if (bp->bp_role == BSTP_ROLE_DISABLED) { bstp_enable_port(bs, bp); changed = 1; } } else { if (bp->bp_role != BSTP_ROLE_DISABLED) { bstp_disable_port(bs, bp); changed = 1; if ((bp->bp_flags & BSTP_PORT_ADMEDGE) && bp->bp_protover == BSTP_PROTO_RSTP) bp->bp_operedge = 1; } } } else if (bp->bp_infois != BSTP_INFO_DISABLED) { bstp_disable_port(bs, bp); changed = 1; } if (changed) bstp_assign_roles(bs); BSTP_UNLOCK(bs); } static void bstp_enable_port(struct bstp_state *bs, struct bstp_port *bp) { bp->bp_infois = BSTP_INFO_AGED; } static void bstp_disable_port(struct bstp_state *bs, struct bstp_port *bp) { bp->bp_infois = BSTP_INFO_DISABLED; } static void bstp_tick(void *arg) { struct bstp_state *bs = arg; struct bstp_port *bp; BSTP_LOCK_ASSERT(bs); if (bs->bs_running == 0) return; CURVNET_SET(bs->bs_vnet); /* poll link events on interfaces that do not support linkstate */ if (bstp_timer_dectest(&bs->bs_link_timer)) { LIST_FOREACH(bp, &bs->bs_bplist, bp_next) { if (!(bp->bp_ifp->if_capabilities & IFCAP_LINKSTATE)) taskqueue_enqueue(taskqueue_swi, &bp->bp_mediatask); } bstp_timer_start(&bs->bs_link_timer, BSTP_LINK_TIMER); } LIST_FOREACH(bp, &bs->bs_bplist, bp_next) { /* no events need to happen for these */ bstp_timer_dectest(&bp->bp_tc_timer); bstp_timer_dectest(&bp->bp_recent_root_timer); bstp_timer_dectest(&bp->bp_forward_delay_timer); bstp_timer_dectest(&bp->bp_recent_backup_timer); if (bstp_timer_dectest(&bp->bp_hello_timer)) bstp_hello_timer_expiry(bs, bp); if (bstp_timer_dectest(&bp->bp_message_age_timer)) bstp_message_age_expiry(bs, bp); if (bstp_timer_dectest(&bp->bp_migrate_delay_timer)) bstp_migrate_delay_expiry(bs, bp); if (bstp_timer_dectest(&bp->bp_edge_delay_timer)) bstp_edge_delay_expiry(bs, bp); /* update the various state machines for the port */ bstp_update_state(bs, bp); if (bp->bp_txcount > 0) bp->bp_txcount--; } CURVNET_RESTORE(); callout_reset(&bs->bs_bstpcallout, hz, bstp_tick, bs); } static void bstp_timer_start(struct bstp_timer *t, uint16_t v) { t->value = v; t->active = 1; t->latched = 0; } static void bstp_timer_stop(struct bstp_timer *t) { t->value = 0; t->active = 0; t->latched = 0; } static void bstp_timer_latch(struct bstp_timer *t) { t->latched = 1; t->active = 1; } static int bstp_timer_dectest(struct bstp_timer *t) { if (t->active == 0 || t->latched) return (0); t->value -= BSTP_TICK_VAL; if (t->value <= 0) { bstp_timer_stop(t); return (1); } return (0); } static void bstp_hello_timer_expiry(struct bstp_state *bs, struct bstp_port *bp) { if ((bp->bp_flags & BSTP_PORT_NEWINFO) || bp->bp_role == BSTP_ROLE_DESIGNATED || (bp->bp_role == BSTP_ROLE_ROOT && bp->bp_tc_timer.active == 1)) { bstp_timer_start(&bp->bp_hello_timer, bp->bp_desg_htime); bp->bp_flags |= BSTP_PORT_NEWINFO; bstp_transmit(bs, bp); } } static void bstp_message_age_expiry(struct bstp_state *bs, struct bstp_port *bp) { if (bp->bp_infois == BSTP_INFO_RECEIVED) { bp->bp_infois = BSTP_INFO_AGED; bstp_assign_roles(bs); DPRINTF("aged info on %s\n", bp->bp_ifp->if_xname); } } static void bstp_migrate_delay_expiry(struct bstp_state *bs, struct bstp_port *bp) { bp->bp_flags |= BSTP_PORT_CANMIGRATE; } static void bstp_edge_delay_expiry(struct bstp_state *bs, struct bstp_port *bp) { if ((bp->bp_flags & BSTP_PORT_AUTOEDGE) && bp->bp_protover == BSTP_PROTO_RSTP && bp->bp_proposing && bp->bp_role == BSTP_ROLE_DESIGNATED) { bp->bp_operedge = 1; DPRINTF("%s -> edge port\n", bp->bp_ifp->if_xname); } } static int bstp_addr_cmp(const uint8_t *a, const uint8_t *b) { int i, d; for (i = 0, d = 0; i < ETHER_ADDR_LEN && d == 0; i++) { d = ((int)a[i]) - ((int)b[i]); } return (d); } /* * compare the bridge address component of the bridgeid */ static int bstp_same_bridgeid(uint64_t id1, uint64_t id2) { u_char addr1[ETHER_ADDR_LEN]; u_char addr2[ETHER_ADDR_LEN]; PV2ADDR(id1, addr1); PV2ADDR(id2, addr2); if (bstp_addr_cmp(addr1, addr2) == 0) return (1); return (0); } void bstp_reinit(struct bstp_state *bs) { struct bstp_port *bp; struct ifnet *ifp, *mif; u_char *e_addr; void *bridgeptr; static const u_char llzero[ETHER_ADDR_LEN]; /* 00:00:00:00:00:00 */ BSTP_LOCK_ASSERT(bs); if (LIST_EMPTY(&bs->bs_bplist)) goto disablestp; mif = NULL; bridgeptr = LIST_FIRST(&bs->bs_bplist)->bp_ifp->if_bridge; KASSERT(bridgeptr != NULL, ("Invalid bridge pointer")); /* * Search through the Ethernet adapters and find the one with the * lowest value. Make sure the adapter which we take the MAC address * from is part of this bridge, so we can have more than one independent * bridges in the same STP domain. */ IFNET_RLOCK_NOSLEEP(); TAILQ_FOREACH(ifp, &V_ifnet, if_link) { if (ifp->if_type != IFT_ETHER) continue; /* Not Ethernet */ if (ifp->if_bridge != bridgeptr) continue; /* Not part of our bridge */ if (bstp_addr_cmp(IF_LLADDR(ifp), llzero) == 0) continue; /* No mac address set */ if (mif == NULL) { mif = ifp; continue; } if (bstp_addr_cmp(IF_LLADDR(ifp), IF_LLADDR(mif)) < 0) { mif = ifp; continue; } } IFNET_RUNLOCK_NOSLEEP(); if (mif == NULL) goto disablestp; e_addr = IF_LLADDR(mif); bs->bs_bridge_pv.pv_dbridge_id = (((uint64_t)bs->bs_bridge_priority) << 48) | (((uint64_t)e_addr[0]) << 40) | (((uint64_t)e_addr[1]) << 32) | (((uint64_t)e_addr[2]) << 24) | (((uint64_t)e_addr[3]) << 16) | (((uint64_t)e_addr[4]) << 8) | (((uint64_t)e_addr[5])); bs->bs_bridge_pv.pv_root_id = bs->bs_bridge_pv.pv_dbridge_id; bs->bs_bridge_pv.pv_cost = 0; bs->bs_bridge_pv.pv_dport_id = 0; bs->bs_bridge_pv.pv_port_id = 0; if (bs->bs_running && callout_pending(&bs->bs_bstpcallout) == 0) callout_reset(&bs->bs_bstpcallout, hz, bstp_tick, bs); LIST_FOREACH(bp, &bs->bs_bplist, bp_next) { bp->bp_port_id = (bp->bp_priority << 8) | (bp->bp_ifp->if_index & 0xfff); taskqueue_enqueue(taskqueue_swi, &bp->bp_mediatask); } bstp_assign_roles(bs); bstp_timer_start(&bs->bs_link_timer, BSTP_LINK_TIMER); return; disablestp: /* Set the bridge and root id (lower bits) to zero */ bs->bs_bridge_pv.pv_dbridge_id = ((uint64_t)bs->bs_bridge_priority) << 48; bs->bs_bridge_pv.pv_root_id = bs->bs_bridge_pv.pv_dbridge_id; bs->bs_root_pv = bs->bs_bridge_pv; /* Disable any remaining ports, they will have no MAC address */ LIST_FOREACH(bp, &bs->bs_bplist, bp_next) { bp->bp_infois = BSTP_INFO_DISABLED; bstp_set_port_role(bp, BSTP_ROLE_DISABLED); } callout_stop(&bs->bs_bstpcallout); } static int bstp_modevent(module_t mod, int type, void *data) { switch (type) { case MOD_LOAD: mtx_init(&bstp_list_mtx, "bridgestp list", NULL, MTX_DEF); LIST_INIT(&bstp_list); break; case MOD_UNLOAD: mtx_destroy(&bstp_list_mtx); break; default: return (EOPNOTSUPP); } return (0); } static moduledata_t bstp_mod = { "bridgestp", bstp_modevent, 0 }; DECLARE_MODULE(bridgestp, bstp_mod, SI_SUB_PSEUDO, SI_ORDER_ANY); MODULE_VERSION(bridgestp, 1); void bstp_attach(struct bstp_state *bs, struct bstp_cb_ops *cb) { BSTP_LOCK_INIT(bs); callout_init_mtx(&bs->bs_bstpcallout, &bs->bs_mtx, 0); LIST_INIT(&bs->bs_bplist); bs->bs_bridge_max_age = BSTP_DEFAULT_MAX_AGE; bs->bs_bridge_htime = BSTP_DEFAULT_HELLO_TIME; bs->bs_bridge_fdelay = BSTP_DEFAULT_FORWARD_DELAY; bs->bs_bridge_priority = BSTP_DEFAULT_BRIDGE_PRIORITY; bs->bs_hold_time = BSTP_DEFAULT_HOLD_TIME; bs->bs_migration_delay = BSTP_DEFAULT_MIGRATE_DELAY; bs->bs_txholdcount = BSTP_DEFAULT_HOLD_COUNT; bs->bs_protover = BSTP_PROTO_RSTP; bs->bs_state_cb = cb->bcb_state; bs->bs_rtage_cb = cb->bcb_rtage; bs->bs_vnet = curvnet; getmicrotime(&bs->bs_last_tc_time); mtx_lock(&bstp_list_mtx); LIST_INSERT_HEAD(&bstp_list, bs, bs_list); mtx_unlock(&bstp_list_mtx); } void bstp_detach(struct bstp_state *bs) { KASSERT(LIST_EMPTY(&bs->bs_bplist), ("bstp still active")); mtx_lock(&bstp_list_mtx); LIST_REMOVE(bs, bs_list); mtx_unlock(&bstp_list_mtx); callout_drain(&bs->bs_bstpcallout); BSTP_LOCK_DESTROY(bs); } void bstp_init(struct bstp_state *bs) { BSTP_LOCK(bs); callout_reset(&bs->bs_bstpcallout, hz, bstp_tick, bs); bs->bs_running = 1; bstp_reinit(bs); BSTP_UNLOCK(bs); } void bstp_stop(struct bstp_state *bs) { struct bstp_port *bp; BSTP_LOCK(bs); LIST_FOREACH(bp, &bs->bs_bplist, bp_next) bstp_set_port_state(bp, BSTP_IFSTATE_DISCARDING); bs->bs_running = 0; callout_stop(&bs->bs_bstpcallout); BSTP_UNLOCK(bs); } int bstp_create(struct bstp_state *bs, struct bstp_port *bp, struct ifnet *ifp) { bzero(bp, sizeof(struct bstp_port)); BSTP_LOCK(bs); bp->bp_ifp = ifp; bp->bp_bs = bs; bp->bp_priority = BSTP_DEFAULT_PORT_PRIORITY; TASK_INIT(&bp->bp_statetask, 0, bstp_notify_state, bp); TASK_INIT(&bp->bp_rtagetask, 0, bstp_notify_rtage, bp); TASK_INIT(&bp->bp_mediatask, 0, bstp_ifupdstatus, bp); /* Init state */ bp->bp_infois = BSTP_INFO_DISABLED; bp->bp_flags = BSTP_PORT_AUTOEDGE|BSTP_PORT_AUTOPTP; bstp_set_port_state(bp, BSTP_IFSTATE_DISCARDING); bstp_set_port_proto(bp, bs->bs_protover); bstp_set_port_role(bp, BSTP_ROLE_DISABLED); bstp_set_port_tc(bp, BSTP_TCSTATE_INACTIVE); bp->bp_path_cost = bstp_calc_path_cost(bp); BSTP_UNLOCK(bs); return (0); } int bstp_enable(struct bstp_port *bp) { struct bstp_state *bs = bp->bp_bs; struct ifnet *ifp = bp->bp_ifp; KASSERT(bp->bp_active == 0, ("already a bstp member")); switch (ifp->if_type) { case IFT_ETHER: /* These can do spanning tree. */ break; default: /* Nothing else can. */ return (EINVAL); } BSTP_LOCK(bs); LIST_INSERT_HEAD(&bs->bs_bplist, bp, bp_next); bp->bp_active = 1; bp->bp_flags |= BSTP_PORT_NEWINFO; bstp_reinit(bs); bstp_update_roles(bs, bp); BSTP_UNLOCK(bs); return (0); } void bstp_disable(struct bstp_port *bp) { struct bstp_state *bs = bp->bp_bs; KASSERT(bp->bp_active == 1, ("not a bstp member")); BSTP_LOCK(bs); bstp_disable_port(bs, bp); LIST_REMOVE(bp, bp_next); bp->bp_active = 0; bstp_reinit(bs); BSTP_UNLOCK(bs); } /* * The bstp_port structure is about to be freed by the parent bridge. */ void bstp_destroy(struct bstp_port *bp) { KASSERT(bp->bp_active == 0, ("port is still attached")); taskqueue_drain(taskqueue_swi, &bp->bp_statetask); taskqueue_drain(taskqueue_swi, &bp->bp_rtagetask); taskqueue_drain(taskqueue_swi, &bp->bp_mediatask); }
24.961758
88
0.689952
[ "vector" ]
9ede49d7ac96ee92e6fb0715cb7641640887f7e1
12,476
h
C
blazetest/blazetest/mathtest/tdvecdmatmult/AliasingTest.h
nimerix/blaze
55424cc652a7d9af8daa93252e80e70d0581a319
[ "Unlicense" ]
null
null
null
blazetest/blazetest/mathtest/tdvecdmatmult/AliasingTest.h
nimerix/blaze
55424cc652a7d9af8daa93252e80e70d0581a319
[ "Unlicense" ]
null
null
null
blazetest/blazetest/mathtest/tdvecdmatmult/AliasingTest.h
nimerix/blaze
55424cc652a7d9af8daa93252e80e70d0581a319
[ "Unlicense" ]
null
null
null
//================================================================================================= /*! // \file blazetest/mathtest/tdvecdmatmult/AliasingTest.h // \brief Header file for the dense vector/dense matrix multiplication aliasing test // // Copyright (C) 2012-2017 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. 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 names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= #ifndef _BLAZETEST_MATHTEST_TDVECDMATMULT_ALIASINGTEST_H_ #define _BLAZETEST_MATHTEST_TDVECDMATMULT_ALIASINGTEST_H_ //************************************************************************************************* // Includes //************************************************************************************************* #include <sstream> #include <stdexcept> #include <string> #include <blaze/math/CompressedVector.h> #include <blaze/math/DynamicMatrix.h> #include <blaze/math/DynamicVector.h> #include <blaze/math/StaticVector.h> namespace blazetest { namespace mathtest { namespace tdvecdmatmult { //================================================================================================= // // CLASS DEFINITION // //================================================================================================= //************************************************************************************************* /*!\brief Auxiliary class template for the dense vector/dense matrix multiplication aliasing test. // // This class represents a test suite for all dense vector/dense matrix multiplication aliasing // tests. It performs a series of runtime tests to assure that all mathematical operations work // correctly even in the presence of aliasing. */ class AliasingTest { private: //**Type definitions**************************************************************************** typedef blaze::DynamicVector<int,blaze::rowVector> TDVec; //!< Dense row vector type. typedef blaze::DynamicMatrix<int,blaze::rowMajor> DMat; //!< Row-major dense matrix type. typedef blaze::DynamicMatrix<int,blaze::columnMajor> TDMat; //!< Column-major dense matrix type. typedef blaze::CompressedVector<int,blaze::rowVector> TSVec; //!< Sparse row vector type. typedef blaze::StaticVector<int,3UL,blaze::rowVector> TRVec; //!< Result row vector type. //********************************************************************************************** public: //**Constructors******************************************************************************** /*!\name Constructors */ //@{ explicit AliasingTest(); // No explicitly declared copy constructor. //@} //********************************************************************************************** //**Destructor********************************************************************************** // No explicitly declared destructor. //********************************************************************************************** private: //**Test functions****************************************************************************** /*!\name Test functions */ //@{ void testTDVecDMatMult (); void testTDVecTDMatMult(); template< typename T1, typename T2 > void checkResult( const T1& computedResult, const T2& expectedResult ); //@} //********************************************************************************************** //**Utility functions*************************************************************************** /*!\name Utility functions */ //@{ void initialize(); //@} //********************************************************************************************** //**Member variables**************************************************************************** /*!\name Member variables */ //@{ DMat dA4x3_; //!< The first row-major dense matrix. /*!< The \f$ 3 \times 4 \f$ matrix is initialized as \f[\left(\begin{array}{*{3}{c}} -1 & 0 & -2 \\ 0 & 2 & -3 \\ 0 & 1 & 2 \\ 1 & 0 & -2 \\ \end{array}\right)\f]. */ DMat dB3x3_; //!< The second row-major dense matrix. /*!< The \f$ 3 \times 3 \f$ matrix is initialized as \f[\left(\begin{array}{*{3}{c}} 0 & -1 & 0 \\ 1 & -2 & 2 \\ 0 & 0 & -3 \\ \end{array}\right)\f]. */ TDMat tdA4x3_; //!< The first column-major dense matrix. /*!< The \f$ 4 \times 3 \f$ matrix is initialized as \f[\left(\begin{array}{*{3}{c}} -1 & 0 & -2 \\ 0 & 2 & -3 \\ 0 & 1 & 2 \\ 1 & 0 & -2 \\ \end{array}\right)\f]. */ TDMat tdB3x3_; //!< The second column-major dense matrix. /*!< The \f$ 3 \times 3 \f$ matrix is initialized as \f[\left(\begin{array}{*{3}{c}} 0 & -1 & 0 \\ 1 & -2 & 2 \\ 0 & 0 & -3 \\ \end{array}\right)\f]. */ TDVec tda4_; //!< The first dense row vector. /*!< The 4-dimensional vector is initialized as \f[\left(\begin{array}{*{1}{c}} -1 \\ 0 \\ -3 \\ 2 \\ \end{array}\right)\f]. */ TDVec tdb4_; //!< The second dense row vector. /*!< The 4-dimensional vector is initialized as \f[\left(\begin{array}{*{1}{c}} 0 \\ 1 \\ 2 \\ -1 \\ \end{array}\right)\f]. */ TDVec tdc3_; //!< The third dense row vector. /*!< The 3-dimensional vector is initialized as \f[\left(\begin{array}{*{1}{c}} 1 \\ 2 \\ 3 \\ \end{array}\right)\f]. */ TDVec tdd3_; //!< The fourth dense row vector. /*!< The 3-dimensional vector is initialized as \f[\left(\begin{array}{*{1}{c}} 0 \\ 2 \\ 1 \\ \end{array}\right)\f]. */ TDVec tde3_; //!< The fifth dense row vector. /*!< The 3-dimensional vector is initialized as \f[\left(\begin{array}{*{1}{c}} 0 \\ 1 \\ 3 \\ \end{array}\right)\f]. */ TSVec tsa4_; //!< The first sparse row vector. /*!< The 4-dimensional vector is initialized as \f[\left(\begin{array}{*{1}{c}} -1 \\ 0 \\ -3 \\ 2 \\ \end{array}\right)\f]. */ TSVec tsb3_; //!< The second sparse row vector. /*!< The 3-dimensional vector is initialized as \f[\left(\begin{array}{*{1}{c}} 0 \\ 2 \\ 1 \\ \end{array}\right)\f]. */ TRVec result_; //!< The dense vector for the reference result. std::string test_; //!< Label of the currently performed test. //@} //********************************************************************************************** }; //************************************************************************************************* //================================================================================================= // // TEST FUNCTIONS // //================================================================================================= //************************************************************************************************* /*!\brief Checking and comparing the computed result. // // \param computedResult The computed result. // \param expectedResult The expected result. // \return void // \exception std::runtime_error Incorrect result detected. // // This function is called after each test case to check and compare the computed result. // In case the computed and the expected result differ in any way, a \a std::runtime_error // exception is thrown. */ template< typename T1 // Vector type of the computed result , typename T2 > // Vector type of the expected result void AliasingTest::checkResult( const T1& computedResult, const T2& expectedResult ) { if( computedResult != expectedResult ) { std::ostringstream oss; oss.precision( 20 ); oss << " Test : " << test_ << "\n" << " Error: Incorrect result detected\n" << " Details:\n" << " Computed result:\n" << computedResult << "\n" << " Expected result:\n" << expectedResult << "\n"; throw std::runtime_error( oss.str() ); } } //************************************************************************************************* //================================================================================================= // // GLOBAL TEST FUNCTIONS // //================================================================================================= //************************************************************************************************* /*!\brief Testing the dense vector/dense matrix multiplication in the presence of aliasing. // // \return void */ void runTest() { AliasingTest(); } //************************************************************************************************* //================================================================================================= // // MACRO DEFINITIONS // //================================================================================================= //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Macro for the execution of the dense vector/dense matrix multiplication aliasing test. */ #define RUN_TDVECDMATMULT_ALIASING_TEST \ blazetest::mathtest::tdvecdmatmult::runTest() /*! \endcond */ //************************************************************************************************* } // namespace tdvecdmatmult } // namespace mathtest } // namespace blazetest #endif
43.02069
102
0.415598
[ "vector" ]
9edf3a8970d4e9dba9c38a531fcc925f8d0e3583
10,406
c
C
src/issuer.c
elastos/Elastos.DID.Native.SDK
8ca000f86f382aac2db4c28c3504b463f77cc5f0
[ "MIT" ]
3
2020-04-30T05:43:24.000Z
2021-01-11T14:07:26.000Z
src/issuer.c
elastos/Elastos.DID.Native.SDK
8ca000f86f382aac2db4c28c3504b463f77cc5f0
[ "MIT" ]
2
2020-07-10T02:27:34.000Z
2020-07-16T03:01:15.000Z
src/issuer.c
elastos/Elastos.DID.Native.SDK
8ca000f86f382aac2db4c28c3504b463f77cc5f0
[ "MIT" ]
7
2020-04-28T12:33:56.000Z
2021-04-23T06:01:34.000Z
/* * Copyright (c) 2019 - 2021 Elastos Foundation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <stdlib.h> #include <string.h> #include <time.h> #include <assert.h> #include "ela_did.h" #include "diderror.h" #include "did.h" #include "credential.h" #include "crypto.h" #include "issuer.h" #include "didstore.h" #include "diddocument.h" extern const char *ProofType; static const char *DEFAULT_CREDENTIAL_TYPE = "VerifiableCredential"; extern const char *W3C_CREDENTIAL_CONTEXT; extern const char *ELASTOS_CREDENTIAL_CONTEXT; Issuer *Issuer_Create(DID *did, DIDURL *signkey, DIDStore *store) { Issuer *issuer; DIDDocument *doc; DIDERROR_INITIALIZE(); CHECK_ARG(!did, "No did to create issuer.", NULL); CHECK_ARG(!store, "No store argument.", NULL); doc = DIDStore_LoadDID(store, did); if (!doc) { DIDError_Set(DIDERR_NOT_EXISTS, "No issuer document in the store."); return NULL; } if (!signkey) { signkey = DIDDocument_GetDefaultPublicKey(doc); if (!signkey) { DIDError_Set(DIDERR_NOT_EXISTS, "No default key of issuer."); DIDDocument_Destroy(doc); return NULL; } } else { if (!DIDDocument_IsAuthenticationKey(doc, signkey)) { DIDError_Set(DIDERR_INVALID_KEY, "The issuer's signkey isn't an authentication key."); DIDDocument_Destroy(doc); return NULL; } } if (DIDDocument_HasPrivateKey(doc, signkey)!= 1) { DIDError_Set(DIDERR_NOT_EXISTS, "Missing private key paired with signkey of issuer."); DIDDocument_Destroy(doc); return NULL; } issuer = (Issuer*)calloc(1, sizeof(Issuer)); if (!issuer) { DIDError_Set(DIDERR_OUT_OF_MEMORY, "Malloc buffer for issuer failed."); DIDDocument_Destroy(doc); return NULL; } issuer->signer = doc; DIDURL_Copy(&issuer->signkey, signkey); return issuer; DIDERROR_FINALIZE(); } void Issuer_Destroy(Issuer *issuer) { DIDERROR_INITIALIZE(); if (!issuer) return; if (issuer->signer) DIDDocument_Destroy(issuer->signer); free(issuer); DIDERROR_FINALIZE(); } DID *Issuer_GetSigner(Issuer *issuer) { DIDERROR_INITIALIZE(); CHECK_ARG(!issuer, "No issuer argument.", NULL); return &issuer->signer->did; DIDERROR_FINALIZE(); } DIDURL *Issuer_GetSignKey(Issuer *issuer) { DIDERROR_INITIALIZE(); CHECK_ARG(!issuer, "No issuer argument.", NULL); return &issuer->signkey; DIDERROR_FINALIZE(); } static void add_type(Credential *credential, const char *type) { char *pos, *copy; assert(credential); assert(type && *type); pos = strstr(type, "#"); if (pos) { if (Features_IsEnabledJsonLdContext() && !contains_content(credential->context.contexts, credential->context.size, type, pos - type)) { credential->context.contexts[credential->context.size] = (char*)calloc(1, pos - type + 1); strncpy(credential->context.contexts[credential->context.size++], type, pos - type); } copy = pos + 1; } else { copy = (char*)type; } if (!contains_content(credential->type.types, credential->type.size, copy, strlen(copy))) credential->type.types[credential->type.size++] = strdup(copy); } static int add_default_type(Credential *credential) { const char *defaults[2] = { W3C_CREDENTIAL_CONTEXT, ELASTOS_CREDENTIAL_CONTEXT }; assert(credential); if (Features_IsEnabledJsonLdContext()) { credential->context.contexts[0] = strdup(defaults[0]); credential->context.contexts[1] = strdup(defaults[1]); credential->context.size = 2; } credential->type.types[credential->type.size++] = strdup(DEFAULT_CREDENTIAL_TYPE); return 0; } static bool check_types(const char **types, size_t size) { int i; assert(types); assert(size > 0); for (i = 0; i < size; i++) { if (Features_IsEnabledJsonLdContext()) { if (!strstr(types[i], "#")) { return false; } } } return true; } Credential *Issuer_Generate_Credential(Issuer *issuer, DID *owner, DIDURL *credid, const char **types, size_t typesize, json_t *json, time_t expires, const char *storepass) { Credential *cred = NULL; const char *data; char signature[SIGNATURE_BYTES * 2]; DIDDocument *doc = NULL; size_t i; int rc; assert(issuer && owner && credid); assert(types && typesize > 0); assert(json); assert(expires > 0); assert(storepass && *storepass); if (DID_Equals(owner, &credid->did) != 1) { DIDError_Set(DIDERR_INVALID_ARGS, "Credential owner isn't match with credential did."); goto errorExit; } //check types if (!check_types(types, typesize)) { DIDError_Set(DIDERR_INVALID_ARGS, "The type must has context."); goto errorExit; } cred = (Credential*)calloc(1, sizeof(Credential)); if (!cred) { DIDError_Set(DIDERR_OUT_OF_MEMORY, "Malloc buffer for credential failed."); goto errorExit; } if (!DIDURL_Copy(&cred->id, credid)) goto errorExit; //subject DID_Copy(&cred->subject.id, owner); cred->subject.properties = json_deep_copy(json); //add types if (Features_IsEnabledJsonLdContext()) { cred->context.contexts = (char**)calloc(typesize + 2, sizeof(char*)); if (!cred->context.contexts) { DIDError_Set(DIDERR_OUT_OF_MEMORY, "Malloc buffer for contexts failed."); goto errorExit; } } cred->type.types = (char**)calloc(typesize + 1, sizeof(char*)); if (!cred->type.types) { DIDError_Set(DIDERR_OUT_OF_MEMORY, "Malloc buffer for types failed."); goto errorExit; } if (add_default_type(cred) == -1) goto errorExit; for (i = 0; i < typesize; i++) add_type(cred, types[i]); //set issuer DID_Copy(&cred->issuer, &issuer->signer->did); //expire and issue date cred->expirationDate = expires; time(&cred->issuanceDate); //proof data = Credential_ToJson_ForSign(cred, false, true); if (!data) goto errorExit; rc = DIDDocument_Sign(issuer->signer, &issuer->signkey, storepass, signature, 1, (unsigned char*)data, strlen(data)); free((void*)data); if (rc) { DIDError_Set(DIDERR_SIGN_ERROR, "Sign credential failed."); goto errorExit; } strcpy(cred->proof.type, ProofType); DIDURL_Copy(&cred->proof.verificationMethod, &issuer->signkey); strcpy(cred->proof.signatureValue, signature); return cred; errorExit: if (cred) Credential_Destroy(cred); else json_decref(json); if (doc) DIDDocument_Destroy(doc); return NULL; } Credential *Issuer_CreateCredential(Issuer *issuer, DID *owner, DIDURL *credid, const char **types, size_t typesize, Property *subject, int size, time_t expires, const char *storepass) { Credential *cred; json_t *root; int i; DIDERROR_INITIALIZE(); CHECK_ARG(!issuer, "No issuer object.", NULL); CHECK_ARG(!owner, "No owner of credential.", NULL); CHECK_ARG(!credid, "No credential id.", NULL); CHECK_ARG(!types || typesize == 0, "No types for credential.", NULL); CHECK_ARG(!subject || size <= 0, "No subject for credential.", NULL); CHECK_ARG(expires <= 0, "No expires time for credential, please specify one.", NULL); CHECK_PASSWORD(storepass, NULL); root = json_object(); if (!root) { DIDError_Set(DIDERR_OUT_OF_MEMORY, "Create credential's property json failed."); return NULL; } for (i = 0; i < size; i++) { int rc = json_object_set_new(root, subject[i].key, json_string(subject[i].value)); if (rc < 0) { DIDError_Set(DIDERR_OUT_OF_MEMORY, "Add credential's property failed."); json_decref(root); return NULL; } } cred = Issuer_Generate_Credential(issuer, owner, credid, types, typesize, root, expires, storepass); json_decref(root); return cred; DIDERROR_FINALIZE(); } Credential *Issuer_CreateCredentialByString(Issuer *issuer, DID *owner, DIDURL *credid, const char **types, size_t typesize, const char *subject, time_t expires, const char *storepass) { Credential *cred; json_t *root; json_error_t error; DIDERROR_INITIALIZE(); CHECK_ARG(!issuer, "No issuer object.", NULL); CHECK_ARG(!owner, "No owner of credential.", NULL); CHECK_ARG(!credid, "No credential id.", NULL); CHECK_ARG(!types || typesize == 0, "No types for credential.", NULL); CHECK_ARG(!subject || !*subject, "No subject for credential.", NULL); CHECK_ARG(expires <= 0, "No expires time for credential, please specify one.", NULL); CHECK_PASSWORD(storepass, NULL); root = json_loads(subject, JSON_COMPACT, &error); if (!root) { DIDError_Set(DIDERR_OUT_OF_MEMORY, "Deserialize property failed, error: %s.", error.text); return NULL; } cred = Issuer_Generate_Credential(issuer, owner, credid, types, typesize, root, expires, storepass); json_decref(root); return cred; DIDERROR_FINALIZE(); }
29.312676
110
0.649241
[ "object" ]
9ee08ec43f5810f3791e922ce7e277b8896d3fc8
3,370
h
C
android/android_23/frameworks/base/libs/rs/rsFileA3D.h
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_23/frameworks/base/libs/rs/rsFileA3D.h
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_23/frameworks/base/libs/rs/rsFileA3D.h
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ANDROID_RS_FILE_A3D_H #define ANDROID_RS_FILE_A3D_H #include "RenderScript.h" #include "rsFileA3DDecls.h" #include "rsMesh.h" #include <utils/String8.h> #include <stdio.h> // --------------------------------------------------------------------------- namespace android { namespace renderscript { class FileA3D { public: FileA3D(); ~FileA3D(); uint32_t mMajorVersion; uint32_t mMinorVersion; uint64_t mIndexOffset; uint64_t mStringTableOffset; bool mUse64BitOffsets; struct A3DIndexEntry { String8 mID; A3DChunkType mType; uint64_t mOffset; void * mRsObj; }; bool load(Context *rsc, FILE *f); protected: class IO { public: IO(const uint8_t *, bool use64); float loadF() { mPos = (mPos + 3) & (~3); float tmp = reinterpret_cast<const float *>(&mData[mPos])[0]; mPos += sizeof(float); return tmp; } int32_t loadI32() { mPos = (mPos + 3) & (~3); int32_t tmp = reinterpret_cast<const int32_t *>(&mData[mPos])[0]; mPos += sizeof(int32_t); return tmp; } uint32_t loadU32() { mPos = (mPos + 3) & (~3); uint32_t tmp = reinterpret_cast<const uint32_t *>(&mData[mPos])[0]; mPos += sizeof(uint32_t); return tmp; } uint16_t loadU16() { mPos = (mPos + 1) & (~1); uint16_t tmp = reinterpret_cast<const uint16_t *>(&mData[mPos])[0]; mPos += sizeof(uint16_t); return tmp; } uint8_t loadU8() { uint8_t tmp = reinterpret_cast<const uint8_t *>(&mData[mPos])[0]; mPos += sizeof(uint8_t); return tmp; } uint64_t loadOffset(); void loadString(String8 *s); uint64_t getPos() const {return mPos;} const uint8_t * getPtr() const; protected: const uint8_t * mData; uint64_t mPos; bool mUse64; }; bool process(Context *rsc); bool processIndex(Context *rsc, A3DIndexEntry *); void processChunk_Mesh(Context *rsc, IO *io, A3DIndexEntry *ie); void processChunk_Primitive(Context *rsc, IO *io, A3DIndexEntry *ie); void processChunk_Verticies(Context *rsc, IO *io, A3DIndexEntry *ie); void processChunk_Element(Context *rsc, IO *io, A3DIndexEntry *ie); void processChunk_ElementSource(Context *rsc, IO *io, A3DIndexEntry *ie); const uint8_t * mData; void * mAlloc; uint64_t mDataSize; Context * mRsc; Vector<A3DIndexEntry> mIndex; Vector<String8> mStrings; Vector<uint32_t> mStringIndexValues; }; } } #endif //ANDROID_RS_FILE_A3D_H
27.398374
79
0.600593
[ "vector" ]
9ee0eb82445e407781001960c739e346f693a69f
1,491
h
C
crypto/serializer/serializer_local.h
jurocha-ms/openssl
1242f3c798db340397186e178023f1a9fe297df0
[ "Apache-2.0" ]
26
2015-05-07T10:10:43.000Z
2018-09-19T05:34:29.000Z
crypto/serializer/serializer_local.h
jurocha-ms/openssl
1242f3c798db340397186e178023f1a9fe297df0
[ "Apache-2.0" ]
2
2020-04-14T07:54:16.000Z
2020-05-08T12:30:32.000Z
crypto/serializer/serializer_local.h
jurocha-ms/openssl
1242f3c798db340397186e178023f1a9fe297df0
[ "Apache-2.0" ]
35
2019-04-22T12:23:12.000Z
2022-03-12T00:37:18.000Z
/* * Copyright 2019 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/core_numbers.h> #include <openssl/types.h> #include "internal/cryptlib.h" #include "internal/refcount.h" struct ossl_serializer_st { OSSL_PROVIDER *prov; int id; const char *propdef; CRYPTO_REF_COUNT refcnt; CRYPTO_RWLOCK *lock; OSSL_OP_serializer_newctx_fn *newctx; OSSL_OP_serializer_freectx_fn *freectx; OSSL_OP_serializer_set_ctx_params_fn *set_ctx_params; OSSL_OP_serializer_settable_ctx_params_fn *settable_ctx_params; OSSL_OP_serializer_serialize_data_fn *serialize_data; OSSL_OP_serializer_serialize_object_fn *serialize_object; }; struct ossl_serializer_ctx_st { OSSL_SERIALIZER *ser; void *serctx; /* * |object| is the libcrypto object to handle. * |do_output| must have intimate knowledge of this object. */ const void *object; int (*do_output)(OSSL_SERIALIZER_CTX *ctx, BIO *out); /* For any function that needs a passphrase reader */ const UI_METHOD *ui_method; void *ui_data; /* * if caller used OSSL_SERIALIZER_CTX_set_passphrase_cb(), we need * intermediary storage. */ UI_METHOD *allocated_ui_method; };
29.235294
74
0.730382
[ "object" ]
9ee12906d18a494315411b8f7c8523a6098f1012
4,442
h
C
Libraries/ITK/BasicFilters/itkSetOutputVectorToCurrentPositionFilter.h
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
13
2018-07-28T13:36:38.000Z
2021-11-01T19:17:39.000Z
Libraries/ITK/BasicFilters/itkSetOutputVectorToCurrentPositionFilter.h
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
null
null
null
Libraries/ITK/BasicFilters/itkSetOutputVectorToCurrentPositionFilter.h
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
10
2018-08-20T07:06:00.000Z
2021-07-07T07:55:27.000Z
/*============================================================================= NifTK: A software platform for medical image computing. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #ifndef itkSetOutputVectorToCurrentPositionFilter_h #define itkSetOutputVectorToCurrentPositionFilter_h #include <itkInPlaceImageFilter.h> #include <itkVector.h> #include <itkImage.h> namespace itk { /** * \class SetOutputVectorToCurrentPositionFilter * \brief This class takes a vector image as input, and outputs a vector image, where * the vector data value at each voxel is equal to the millimetre or voxel position of that voxel. * * This class is also subclassing InPlaceImageFilter meaning that the input buffer * and output buffer can be the same. If you are using this filter in place, you * run the filter, then us the output pointer, not the input pointer. * */ template < typename TScalarType, unsigned int NDimensions = 3> class ITK_EXPORT SetOutputVectorToCurrentPositionFilter : public InPlaceImageFilter< Image< Vector<TScalarType, NDimensions>, NDimensions>, // Input image Image< Vector<TScalarType, NDimensions>, NDimensions> // Output image > { public: /** Standard "Self" typedef. */ typedef SetOutputVectorToCurrentPositionFilter Self; typedef InPlaceImageFilter<Image< Vector<TScalarType, NDimensions>, NDimensions>, Image< Vector<TScalarType, NDimensions>, NDimensions> > Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Standard typedefs. */ typedef Vector< TScalarType, NDimensions > InputPixelType; typedef Image< InputPixelType, NDimensions > InputImageType; typedef typename InputImageType::IndexType InputImageIndexType; typedef typename InputImageType::RegionType InputImageRegionType; typedef InputPixelType OutputPixelType; typedef InputImageType OutputImageType; typedef typename OutputImageType::PointType OutputImagePointType; /** Method for creation through the object factory. */ itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(SetOutputVectorToCurrentPositionFilter, InPlaceImageFilter); /** Get the number of dimensions we are working in. */ itkStaticConstMacro(Dimension, unsigned int, NDimensions); /** Set/Get a flag controlling output, if true, output is millimetre coordinates, if false, output is in voxels. */ itkSetMacro(OutputIsInMillimetres, bool); itkGetMacro(OutputIsInMillimetres, bool); protected: SetOutputVectorToCurrentPositionFilter(); ~SetOutputVectorToCurrentPositionFilter() {}; void PrintSelf(std::ostream& os, Indent indent) const; // Check before we start. virtual void BeforeThreadedGenerateData(); // The main method to implement in derived classes, note, its threaded. virtual void ThreadedGenerateData( const InputImageRegionType &outputRegionForThread, ThreadIdType threadId); private: /** * Prohibited copy and assignment. */ SetOutputVectorToCurrentPositionFilter(const Self&); void operator=(const Self&); /** Default to true, so output is millimetre coordinates, with respect to origin. If false, output is voxel coordinates. */ bool m_OutputIsInMillimetres; }; // end class } // end namespace #ifndef ITK_MANUAL_INSTANTIATION #include "itkSetOutputVectorToCurrentPositionFilter.txx" #endif #endif
43.126214
127
0.617515
[ "object", "vector" ]
9ee1ac3996a64a1fdbe46c436708431724007012
58,043
h
C
aws-cpp-sdk-mediaconvert/include/aws/mediaconvert/model/Mpeg2Settings.h
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-mediaconvert/include/aws/mediaconvert/model/Mpeg2Settings.h
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-mediaconvert/include/aws/mediaconvert/model/Mpeg2Settings.h
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #pragma once #include <aws/mediaconvert/MediaConvert_EXPORTS.h> #include <aws/mediaconvert/model/Mpeg2AdaptiveQuantization.h> #include <aws/mediaconvert/model/Mpeg2CodecLevel.h> #include <aws/mediaconvert/model/Mpeg2CodecProfile.h> #include <aws/mediaconvert/model/Mpeg2DynamicSubGop.h> #include <aws/mediaconvert/model/Mpeg2FramerateControl.h> #include <aws/mediaconvert/model/Mpeg2FramerateConversionAlgorithm.h> #include <aws/mediaconvert/model/Mpeg2GopSizeUnits.h> #include <aws/mediaconvert/model/Mpeg2InterlaceMode.h> #include <aws/mediaconvert/model/Mpeg2IntraDcPrecision.h> #include <aws/mediaconvert/model/Mpeg2ParControl.h> #include <aws/mediaconvert/model/Mpeg2QualityTuningLevel.h> #include <aws/mediaconvert/model/Mpeg2RateControlMode.h> #include <aws/mediaconvert/model/Mpeg2SceneChangeDetect.h> #include <aws/mediaconvert/model/Mpeg2SlowPal.h> #include <aws/mediaconvert/model/Mpeg2SpatialAdaptiveQuantization.h> #include <aws/mediaconvert/model/Mpeg2Syntax.h> #include <aws/mediaconvert/model/Mpeg2Telecine.h> #include <aws/mediaconvert/model/Mpeg2TemporalAdaptiveQuantization.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace MediaConvert { namespace Model { /** * Required when you set (Codec) under (VideoDescription)>(CodecSettings) to the * value MPEG2.<p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/mediaconvert-2017-08-29/Mpeg2Settings">AWS * API Reference</a></p> */ class AWS_MEDIACONVERT_API Mpeg2Settings { public: Mpeg2Settings(); Mpeg2Settings(Aws::Utils::Json::JsonView jsonValue); Mpeg2Settings& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * Adaptive quantization. Allows intra-frame quantizers to vary to improve visual * quality. */ inline const Mpeg2AdaptiveQuantization& GetAdaptiveQuantization() const{ return m_adaptiveQuantization; } /** * Adaptive quantization. Allows intra-frame quantizers to vary to improve visual * quality. */ inline bool AdaptiveQuantizationHasBeenSet() const { return m_adaptiveQuantizationHasBeenSet; } /** * Adaptive quantization. Allows intra-frame quantizers to vary to improve visual * quality. */ inline void SetAdaptiveQuantization(const Mpeg2AdaptiveQuantization& value) { m_adaptiveQuantizationHasBeenSet = true; m_adaptiveQuantization = value; } /** * Adaptive quantization. Allows intra-frame quantizers to vary to improve visual * quality. */ inline void SetAdaptiveQuantization(Mpeg2AdaptiveQuantization&& value) { m_adaptiveQuantizationHasBeenSet = true; m_adaptiveQuantization = std::move(value); } /** * Adaptive quantization. Allows intra-frame quantizers to vary to improve visual * quality. */ inline Mpeg2Settings& WithAdaptiveQuantization(const Mpeg2AdaptiveQuantization& value) { SetAdaptiveQuantization(value); return *this;} /** * Adaptive quantization. Allows intra-frame quantizers to vary to improve visual * quality. */ inline Mpeg2Settings& WithAdaptiveQuantization(Mpeg2AdaptiveQuantization&& value) { SetAdaptiveQuantization(std::move(value)); return *this;} /** * Average bitrate in bits/second. Required for VBR and CBR. For MS Smooth outputs, * bitrates must be unique when rounded down to the nearest multiple of 1000. */ inline int GetBitrate() const{ return m_bitrate; } /** * Average bitrate in bits/second. Required for VBR and CBR. For MS Smooth outputs, * bitrates must be unique when rounded down to the nearest multiple of 1000. */ inline bool BitrateHasBeenSet() const { return m_bitrateHasBeenSet; } /** * Average bitrate in bits/second. Required for VBR and CBR. For MS Smooth outputs, * bitrates must be unique when rounded down to the nearest multiple of 1000. */ inline void SetBitrate(int value) { m_bitrateHasBeenSet = true; m_bitrate = value; } /** * Average bitrate in bits/second. Required for VBR and CBR. For MS Smooth outputs, * bitrates must be unique when rounded down to the nearest multiple of 1000. */ inline Mpeg2Settings& WithBitrate(int value) { SetBitrate(value); return *this;} /** * Use Level (Mpeg2CodecLevel) to set the MPEG-2 level for the video output. */ inline const Mpeg2CodecLevel& GetCodecLevel() const{ return m_codecLevel; } /** * Use Level (Mpeg2CodecLevel) to set the MPEG-2 level for the video output. */ inline bool CodecLevelHasBeenSet() const { return m_codecLevelHasBeenSet; } /** * Use Level (Mpeg2CodecLevel) to set the MPEG-2 level for the video output. */ inline void SetCodecLevel(const Mpeg2CodecLevel& value) { m_codecLevelHasBeenSet = true; m_codecLevel = value; } /** * Use Level (Mpeg2CodecLevel) to set the MPEG-2 level for the video output. */ inline void SetCodecLevel(Mpeg2CodecLevel&& value) { m_codecLevelHasBeenSet = true; m_codecLevel = std::move(value); } /** * Use Level (Mpeg2CodecLevel) to set the MPEG-2 level for the video output. */ inline Mpeg2Settings& WithCodecLevel(const Mpeg2CodecLevel& value) { SetCodecLevel(value); return *this;} /** * Use Level (Mpeg2CodecLevel) to set the MPEG-2 level for the video output. */ inline Mpeg2Settings& WithCodecLevel(Mpeg2CodecLevel&& value) { SetCodecLevel(std::move(value)); return *this;} /** * Use Profile (Mpeg2CodecProfile) to set the MPEG-2 profile for the video output. */ inline const Mpeg2CodecProfile& GetCodecProfile() const{ return m_codecProfile; } /** * Use Profile (Mpeg2CodecProfile) to set the MPEG-2 profile for the video output. */ inline bool CodecProfileHasBeenSet() const { return m_codecProfileHasBeenSet; } /** * Use Profile (Mpeg2CodecProfile) to set the MPEG-2 profile for the video output. */ inline void SetCodecProfile(const Mpeg2CodecProfile& value) { m_codecProfileHasBeenSet = true; m_codecProfile = value; } /** * Use Profile (Mpeg2CodecProfile) to set the MPEG-2 profile for the video output. */ inline void SetCodecProfile(Mpeg2CodecProfile&& value) { m_codecProfileHasBeenSet = true; m_codecProfile = std::move(value); } /** * Use Profile (Mpeg2CodecProfile) to set the MPEG-2 profile for the video output. */ inline Mpeg2Settings& WithCodecProfile(const Mpeg2CodecProfile& value) { SetCodecProfile(value); return *this;} /** * Use Profile (Mpeg2CodecProfile) to set the MPEG-2 profile for the video output. */ inline Mpeg2Settings& WithCodecProfile(Mpeg2CodecProfile&& value) { SetCodecProfile(std::move(value)); return *this;} /** * Choose Adaptive to improve subjective video quality for high-motion content. * This will cause the service to use fewer B-frames (which infer information based * on other frames) for high-motion portions of the video and more B-frames for * low-motion portions. The maximum number of B-frames is limited by the value you * provide for the setting B frames between reference frames * (numberBFramesBetweenReferenceFrames). */ inline const Mpeg2DynamicSubGop& GetDynamicSubGop() const{ return m_dynamicSubGop; } /** * Choose Adaptive to improve subjective video quality for high-motion content. * This will cause the service to use fewer B-frames (which infer information based * on other frames) for high-motion portions of the video and more B-frames for * low-motion portions. The maximum number of B-frames is limited by the value you * provide for the setting B frames between reference frames * (numberBFramesBetweenReferenceFrames). */ inline bool DynamicSubGopHasBeenSet() const { return m_dynamicSubGopHasBeenSet; } /** * Choose Adaptive to improve subjective video quality for high-motion content. * This will cause the service to use fewer B-frames (which infer information based * on other frames) for high-motion portions of the video and more B-frames for * low-motion portions. The maximum number of B-frames is limited by the value you * provide for the setting B frames between reference frames * (numberBFramesBetweenReferenceFrames). */ inline void SetDynamicSubGop(const Mpeg2DynamicSubGop& value) { m_dynamicSubGopHasBeenSet = true; m_dynamicSubGop = value; } /** * Choose Adaptive to improve subjective video quality for high-motion content. * This will cause the service to use fewer B-frames (which infer information based * on other frames) for high-motion portions of the video and more B-frames for * low-motion portions. The maximum number of B-frames is limited by the value you * provide for the setting B frames between reference frames * (numberBFramesBetweenReferenceFrames). */ inline void SetDynamicSubGop(Mpeg2DynamicSubGop&& value) { m_dynamicSubGopHasBeenSet = true; m_dynamicSubGop = std::move(value); } /** * Choose Adaptive to improve subjective video quality for high-motion content. * This will cause the service to use fewer B-frames (which infer information based * on other frames) for high-motion portions of the video and more B-frames for * low-motion portions. The maximum number of B-frames is limited by the value you * provide for the setting B frames between reference frames * (numberBFramesBetweenReferenceFrames). */ inline Mpeg2Settings& WithDynamicSubGop(const Mpeg2DynamicSubGop& value) { SetDynamicSubGop(value); return *this;} /** * Choose Adaptive to improve subjective video quality for high-motion content. * This will cause the service to use fewer B-frames (which infer information based * on other frames) for high-motion portions of the video and more B-frames for * low-motion portions. The maximum number of B-frames is limited by the value you * provide for the setting B frames between reference frames * (numberBFramesBetweenReferenceFrames). */ inline Mpeg2Settings& WithDynamicSubGop(Mpeg2DynamicSubGop&& value) { SetDynamicSubGop(std::move(value)); return *this;} /** * If you are using the console, use the Framerate setting to specify the frame * rate for this output. If you want to keep the same frame rate as the input * video, choose Follow source. If you want to do frame rate conversion, choose a * frame rate from the dropdown list or choose Custom. The framerates shown in the * dropdown list are decimal approximations of fractions. If you choose Custom, * specify your frame rate as a fraction. If you are creating your transcoding job * sepecification as a JSON file without the console, use FramerateControl to * specify which value the service uses for the frame rate for this output. Choose * INITIALIZE_FROM_SOURCE if you want the service to use the frame rate from the * input. Choose SPECIFIED if you want the service to use the frame rate you * specify in the settings FramerateNumerator and FramerateDenominator. */ inline const Mpeg2FramerateControl& GetFramerateControl() const{ return m_framerateControl; } /** * If you are using the console, use the Framerate setting to specify the frame * rate for this output. If you want to keep the same frame rate as the input * video, choose Follow source. If you want to do frame rate conversion, choose a * frame rate from the dropdown list or choose Custom. The framerates shown in the * dropdown list are decimal approximations of fractions. If you choose Custom, * specify your frame rate as a fraction. If you are creating your transcoding job * sepecification as a JSON file without the console, use FramerateControl to * specify which value the service uses for the frame rate for this output. Choose * INITIALIZE_FROM_SOURCE if you want the service to use the frame rate from the * input. Choose SPECIFIED if you want the service to use the frame rate you * specify in the settings FramerateNumerator and FramerateDenominator. */ inline bool FramerateControlHasBeenSet() const { return m_framerateControlHasBeenSet; } /** * If you are using the console, use the Framerate setting to specify the frame * rate for this output. If you want to keep the same frame rate as the input * video, choose Follow source. If you want to do frame rate conversion, choose a * frame rate from the dropdown list or choose Custom. The framerates shown in the * dropdown list are decimal approximations of fractions. If you choose Custom, * specify your frame rate as a fraction. If you are creating your transcoding job * sepecification as a JSON file without the console, use FramerateControl to * specify which value the service uses for the frame rate for this output. Choose * INITIALIZE_FROM_SOURCE if you want the service to use the frame rate from the * input. Choose SPECIFIED if you want the service to use the frame rate you * specify in the settings FramerateNumerator and FramerateDenominator. */ inline void SetFramerateControl(const Mpeg2FramerateControl& value) { m_framerateControlHasBeenSet = true; m_framerateControl = value; } /** * If you are using the console, use the Framerate setting to specify the frame * rate for this output. If you want to keep the same frame rate as the input * video, choose Follow source. If you want to do frame rate conversion, choose a * frame rate from the dropdown list or choose Custom. The framerates shown in the * dropdown list are decimal approximations of fractions. If you choose Custom, * specify your frame rate as a fraction. If you are creating your transcoding job * sepecification as a JSON file without the console, use FramerateControl to * specify which value the service uses for the frame rate for this output. Choose * INITIALIZE_FROM_SOURCE if you want the service to use the frame rate from the * input. Choose SPECIFIED if you want the service to use the frame rate you * specify in the settings FramerateNumerator and FramerateDenominator. */ inline void SetFramerateControl(Mpeg2FramerateControl&& value) { m_framerateControlHasBeenSet = true; m_framerateControl = std::move(value); } /** * If you are using the console, use the Framerate setting to specify the frame * rate for this output. If you want to keep the same frame rate as the input * video, choose Follow source. If you want to do frame rate conversion, choose a * frame rate from the dropdown list or choose Custom. The framerates shown in the * dropdown list are decimal approximations of fractions. If you choose Custom, * specify your frame rate as a fraction. If you are creating your transcoding job * sepecification as a JSON file without the console, use FramerateControl to * specify which value the service uses for the frame rate for this output. Choose * INITIALIZE_FROM_SOURCE if you want the service to use the frame rate from the * input. Choose SPECIFIED if you want the service to use the frame rate you * specify in the settings FramerateNumerator and FramerateDenominator. */ inline Mpeg2Settings& WithFramerateControl(const Mpeg2FramerateControl& value) { SetFramerateControl(value); return *this;} /** * If you are using the console, use the Framerate setting to specify the frame * rate for this output. If you want to keep the same frame rate as the input * video, choose Follow source. If you want to do frame rate conversion, choose a * frame rate from the dropdown list or choose Custom. The framerates shown in the * dropdown list are decimal approximations of fractions. If you choose Custom, * specify your frame rate as a fraction. If you are creating your transcoding job * sepecification as a JSON file without the console, use FramerateControl to * specify which value the service uses for the frame rate for this output. Choose * INITIALIZE_FROM_SOURCE if you want the service to use the frame rate from the * input. Choose SPECIFIED if you want the service to use the frame rate you * specify in the settings FramerateNumerator and FramerateDenominator. */ inline Mpeg2Settings& WithFramerateControl(Mpeg2FramerateControl&& value) { SetFramerateControl(std::move(value)); return *this;} /** * When set to INTERPOLATE, produces smoother motion during frame rate conversion. */ inline const Mpeg2FramerateConversionAlgorithm& GetFramerateConversionAlgorithm() const{ return m_framerateConversionAlgorithm; } /** * When set to INTERPOLATE, produces smoother motion during frame rate conversion. */ inline bool FramerateConversionAlgorithmHasBeenSet() const { return m_framerateConversionAlgorithmHasBeenSet; } /** * When set to INTERPOLATE, produces smoother motion during frame rate conversion. */ inline void SetFramerateConversionAlgorithm(const Mpeg2FramerateConversionAlgorithm& value) { m_framerateConversionAlgorithmHasBeenSet = true; m_framerateConversionAlgorithm = value; } /** * When set to INTERPOLATE, produces smoother motion during frame rate conversion. */ inline void SetFramerateConversionAlgorithm(Mpeg2FramerateConversionAlgorithm&& value) { m_framerateConversionAlgorithmHasBeenSet = true; m_framerateConversionAlgorithm = std::move(value); } /** * When set to INTERPOLATE, produces smoother motion during frame rate conversion. */ inline Mpeg2Settings& WithFramerateConversionAlgorithm(const Mpeg2FramerateConversionAlgorithm& value) { SetFramerateConversionAlgorithm(value); return *this;} /** * When set to INTERPOLATE, produces smoother motion during frame rate conversion. */ inline Mpeg2Settings& WithFramerateConversionAlgorithm(Mpeg2FramerateConversionAlgorithm&& value) { SetFramerateConversionAlgorithm(std::move(value)); return *this;} /** * Frame rate denominator. */ inline int GetFramerateDenominator() const{ return m_framerateDenominator; } /** * Frame rate denominator. */ inline bool FramerateDenominatorHasBeenSet() const { return m_framerateDenominatorHasBeenSet; } /** * Frame rate denominator. */ inline void SetFramerateDenominator(int value) { m_framerateDenominatorHasBeenSet = true; m_framerateDenominator = value; } /** * Frame rate denominator. */ inline Mpeg2Settings& WithFramerateDenominator(int value) { SetFramerateDenominator(value); return *this;} /** * Frame rate numerator - frame rate is a fraction, e.g. 24000 / 1001 = 23.976 fps. */ inline int GetFramerateNumerator() const{ return m_framerateNumerator; } /** * Frame rate numerator - frame rate is a fraction, e.g. 24000 / 1001 = 23.976 fps. */ inline bool FramerateNumeratorHasBeenSet() const { return m_framerateNumeratorHasBeenSet; } /** * Frame rate numerator - frame rate is a fraction, e.g. 24000 / 1001 = 23.976 fps. */ inline void SetFramerateNumerator(int value) { m_framerateNumeratorHasBeenSet = true; m_framerateNumerator = value; } /** * Frame rate numerator - frame rate is a fraction, e.g. 24000 / 1001 = 23.976 fps. */ inline Mpeg2Settings& WithFramerateNumerator(int value) { SetFramerateNumerator(value); return *this;} /** * Frequency of closed GOPs. In streaming applications, it is recommended that this * be set to 1 so a decoder joining mid-stream will receive an IDR frame as quickly * as possible. Setting this value to 0 will break output segmenting. */ inline int GetGopClosedCadence() const{ return m_gopClosedCadence; } /** * Frequency of closed GOPs. In streaming applications, it is recommended that this * be set to 1 so a decoder joining mid-stream will receive an IDR frame as quickly * as possible. Setting this value to 0 will break output segmenting. */ inline bool GopClosedCadenceHasBeenSet() const { return m_gopClosedCadenceHasBeenSet; } /** * Frequency of closed GOPs. In streaming applications, it is recommended that this * be set to 1 so a decoder joining mid-stream will receive an IDR frame as quickly * as possible. Setting this value to 0 will break output segmenting. */ inline void SetGopClosedCadence(int value) { m_gopClosedCadenceHasBeenSet = true; m_gopClosedCadence = value; } /** * Frequency of closed GOPs. In streaming applications, it is recommended that this * be set to 1 so a decoder joining mid-stream will receive an IDR frame as quickly * as possible. Setting this value to 0 will break output segmenting. */ inline Mpeg2Settings& WithGopClosedCadence(int value) { SetGopClosedCadence(value); return *this;} /** * GOP Length (keyframe interval) in frames or seconds. Must be greater than zero. */ inline double GetGopSize() const{ return m_gopSize; } /** * GOP Length (keyframe interval) in frames or seconds. Must be greater than zero. */ inline bool GopSizeHasBeenSet() const { return m_gopSizeHasBeenSet; } /** * GOP Length (keyframe interval) in frames or seconds. Must be greater than zero. */ inline void SetGopSize(double value) { m_gopSizeHasBeenSet = true; m_gopSize = value; } /** * GOP Length (keyframe interval) in frames or seconds. Must be greater than zero. */ inline Mpeg2Settings& WithGopSize(double value) { SetGopSize(value); return *this;} /** * Indicates if the GOP Size in MPEG2 is specified in frames or seconds. If seconds * the system will convert the GOP Size into a frame count at run time. */ inline const Mpeg2GopSizeUnits& GetGopSizeUnits() const{ return m_gopSizeUnits; } /** * Indicates if the GOP Size in MPEG2 is specified in frames or seconds. If seconds * the system will convert the GOP Size into a frame count at run time. */ inline bool GopSizeUnitsHasBeenSet() const { return m_gopSizeUnitsHasBeenSet; } /** * Indicates if the GOP Size in MPEG2 is specified in frames or seconds. If seconds * the system will convert the GOP Size into a frame count at run time. */ inline void SetGopSizeUnits(const Mpeg2GopSizeUnits& value) { m_gopSizeUnitsHasBeenSet = true; m_gopSizeUnits = value; } /** * Indicates if the GOP Size in MPEG2 is specified in frames or seconds. If seconds * the system will convert the GOP Size into a frame count at run time. */ inline void SetGopSizeUnits(Mpeg2GopSizeUnits&& value) { m_gopSizeUnitsHasBeenSet = true; m_gopSizeUnits = std::move(value); } /** * Indicates if the GOP Size in MPEG2 is specified in frames or seconds. If seconds * the system will convert the GOP Size into a frame count at run time. */ inline Mpeg2Settings& WithGopSizeUnits(const Mpeg2GopSizeUnits& value) { SetGopSizeUnits(value); return *this;} /** * Indicates if the GOP Size in MPEG2 is specified in frames or seconds. If seconds * the system will convert the GOP Size into a frame count at run time. */ inline Mpeg2Settings& WithGopSizeUnits(Mpeg2GopSizeUnits&& value) { SetGopSizeUnits(std::move(value)); return *this;} /** * Percentage of the buffer that should initially be filled (HRD buffer model). */ inline int GetHrdBufferInitialFillPercentage() const{ return m_hrdBufferInitialFillPercentage; } /** * Percentage of the buffer that should initially be filled (HRD buffer model). */ inline bool HrdBufferInitialFillPercentageHasBeenSet() const { return m_hrdBufferInitialFillPercentageHasBeenSet; } /** * Percentage of the buffer that should initially be filled (HRD buffer model). */ inline void SetHrdBufferInitialFillPercentage(int value) { m_hrdBufferInitialFillPercentageHasBeenSet = true; m_hrdBufferInitialFillPercentage = value; } /** * Percentage of the buffer that should initially be filled (HRD buffer model). */ inline Mpeg2Settings& WithHrdBufferInitialFillPercentage(int value) { SetHrdBufferInitialFillPercentage(value); return *this;} /** * Size of buffer (HRD buffer model) in bits. For example, enter five megabits as * 5000000. */ inline int GetHrdBufferSize() const{ return m_hrdBufferSize; } /** * Size of buffer (HRD buffer model) in bits. For example, enter five megabits as * 5000000. */ inline bool HrdBufferSizeHasBeenSet() const { return m_hrdBufferSizeHasBeenSet; } /** * Size of buffer (HRD buffer model) in bits. For example, enter five megabits as * 5000000. */ inline void SetHrdBufferSize(int value) { m_hrdBufferSizeHasBeenSet = true; m_hrdBufferSize = value; } /** * Size of buffer (HRD buffer model) in bits. For example, enter five megabits as * 5000000. */ inline Mpeg2Settings& WithHrdBufferSize(int value) { SetHrdBufferSize(value); return *this;} /** * Use Interlace mode (InterlaceMode) to choose the scan line type for the output. * * Top Field First (TOP_FIELD) and Bottom Field First (BOTTOM_FIELD) produce * interlaced output with the entire output having the same field polarity (top or * bottom first). * Follow, Default Top (FOLLOW_TOP_FIELD) and Follow, Default * Bottom (FOLLOW_BOTTOM_FIELD) use the same field polarity as the source. * Therefore, behavior depends on the input scan type. - If the source is * interlaced, the output will be interlaced with the same polarity as the source * (it will follow the source). The output could therefore be a mix of "top field * first" and "bottom field first". - If the source is progressive, the output * will be interlaced with "top field first" or "bottom field first" polarity, * depending on which of the Follow options you chose. */ inline const Mpeg2InterlaceMode& GetInterlaceMode() const{ return m_interlaceMode; } /** * Use Interlace mode (InterlaceMode) to choose the scan line type for the output. * * Top Field First (TOP_FIELD) and Bottom Field First (BOTTOM_FIELD) produce * interlaced output with the entire output having the same field polarity (top or * bottom first). * Follow, Default Top (FOLLOW_TOP_FIELD) and Follow, Default * Bottom (FOLLOW_BOTTOM_FIELD) use the same field polarity as the source. * Therefore, behavior depends on the input scan type. - If the source is * interlaced, the output will be interlaced with the same polarity as the source * (it will follow the source). The output could therefore be a mix of "top field * first" and "bottom field first". - If the source is progressive, the output * will be interlaced with "top field first" or "bottom field first" polarity, * depending on which of the Follow options you chose. */ inline bool InterlaceModeHasBeenSet() const { return m_interlaceModeHasBeenSet; } /** * Use Interlace mode (InterlaceMode) to choose the scan line type for the output. * * Top Field First (TOP_FIELD) and Bottom Field First (BOTTOM_FIELD) produce * interlaced output with the entire output having the same field polarity (top or * bottom first). * Follow, Default Top (FOLLOW_TOP_FIELD) and Follow, Default * Bottom (FOLLOW_BOTTOM_FIELD) use the same field polarity as the source. * Therefore, behavior depends on the input scan type. - If the source is * interlaced, the output will be interlaced with the same polarity as the source * (it will follow the source). The output could therefore be a mix of "top field * first" and "bottom field first". - If the source is progressive, the output * will be interlaced with "top field first" or "bottom field first" polarity, * depending on which of the Follow options you chose. */ inline void SetInterlaceMode(const Mpeg2InterlaceMode& value) { m_interlaceModeHasBeenSet = true; m_interlaceMode = value; } /** * Use Interlace mode (InterlaceMode) to choose the scan line type for the output. * * Top Field First (TOP_FIELD) and Bottom Field First (BOTTOM_FIELD) produce * interlaced output with the entire output having the same field polarity (top or * bottom first). * Follow, Default Top (FOLLOW_TOP_FIELD) and Follow, Default * Bottom (FOLLOW_BOTTOM_FIELD) use the same field polarity as the source. * Therefore, behavior depends on the input scan type. - If the source is * interlaced, the output will be interlaced with the same polarity as the source * (it will follow the source). The output could therefore be a mix of "top field * first" and "bottom field first". - If the source is progressive, the output * will be interlaced with "top field first" or "bottom field first" polarity, * depending on which of the Follow options you chose. */ inline void SetInterlaceMode(Mpeg2InterlaceMode&& value) { m_interlaceModeHasBeenSet = true; m_interlaceMode = std::move(value); } /** * Use Interlace mode (InterlaceMode) to choose the scan line type for the output. * * Top Field First (TOP_FIELD) and Bottom Field First (BOTTOM_FIELD) produce * interlaced output with the entire output having the same field polarity (top or * bottom first). * Follow, Default Top (FOLLOW_TOP_FIELD) and Follow, Default * Bottom (FOLLOW_BOTTOM_FIELD) use the same field polarity as the source. * Therefore, behavior depends on the input scan type. - If the source is * interlaced, the output will be interlaced with the same polarity as the source * (it will follow the source). The output could therefore be a mix of "top field * first" and "bottom field first". - If the source is progressive, the output * will be interlaced with "top field first" or "bottom field first" polarity, * depending on which of the Follow options you chose. */ inline Mpeg2Settings& WithInterlaceMode(const Mpeg2InterlaceMode& value) { SetInterlaceMode(value); return *this;} /** * Use Interlace mode (InterlaceMode) to choose the scan line type for the output. * * Top Field First (TOP_FIELD) and Bottom Field First (BOTTOM_FIELD) produce * interlaced output with the entire output having the same field polarity (top or * bottom first). * Follow, Default Top (FOLLOW_TOP_FIELD) and Follow, Default * Bottom (FOLLOW_BOTTOM_FIELD) use the same field polarity as the source. * Therefore, behavior depends on the input scan type. - If the source is * interlaced, the output will be interlaced with the same polarity as the source * (it will follow the source). The output could therefore be a mix of "top field * first" and "bottom field first". - If the source is progressive, the output * will be interlaced with "top field first" or "bottom field first" polarity, * depending on which of the Follow options you chose. */ inline Mpeg2Settings& WithInterlaceMode(Mpeg2InterlaceMode&& value) { SetInterlaceMode(std::move(value)); return *this;} /** * Use Intra DC precision (Mpeg2IntraDcPrecision) to set quantization precision for * intra-block DC coefficients. If you choose the value auto, the service will * automatically select the precision based on the per-frame compression ratio. */ inline const Mpeg2IntraDcPrecision& GetIntraDcPrecision() const{ return m_intraDcPrecision; } /** * Use Intra DC precision (Mpeg2IntraDcPrecision) to set quantization precision for * intra-block DC coefficients. If you choose the value auto, the service will * automatically select the precision based on the per-frame compression ratio. */ inline bool IntraDcPrecisionHasBeenSet() const { return m_intraDcPrecisionHasBeenSet; } /** * Use Intra DC precision (Mpeg2IntraDcPrecision) to set quantization precision for * intra-block DC coefficients. If you choose the value auto, the service will * automatically select the precision based on the per-frame compression ratio. */ inline void SetIntraDcPrecision(const Mpeg2IntraDcPrecision& value) { m_intraDcPrecisionHasBeenSet = true; m_intraDcPrecision = value; } /** * Use Intra DC precision (Mpeg2IntraDcPrecision) to set quantization precision for * intra-block DC coefficients. If you choose the value auto, the service will * automatically select the precision based on the per-frame compression ratio. */ inline void SetIntraDcPrecision(Mpeg2IntraDcPrecision&& value) { m_intraDcPrecisionHasBeenSet = true; m_intraDcPrecision = std::move(value); } /** * Use Intra DC precision (Mpeg2IntraDcPrecision) to set quantization precision for * intra-block DC coefficients. If you choose the value auto, the service will * automatically select the precision based on the per-frame compression ratio. */ inline Mpeg2Settings& WithIntraDcPrecision(const Mpeg2IntraDcPrecision& value) { SetIntraDcPrecision(value); return *this;} /** * Use Intra DC precision (Mpeg2IntraDcPrecision) to set quantization precision for * intra-block DC coefficients. If you choose the value auto, the service will * automatically select the precision based on the per-frame compression ratio. */ inline Mpeg2Settings& WithIntraDcPrecision(Mpeg2IntraDcPrecision&& value) { SetIntraDcPrecision(std::move(value)); return *this;} /** * Maximum bitrate in bits/second. For example, enter five megabits per second as * 5000000. */ inline int GetMaxBitrate() const{ return m_maxBitrate; } /** * Maximum bitrate in bits/second. For example, enter five megabits per second as * 5000000. */ inline bool MaxBitrateHasBeenSet() const { return m_maxBitrateHasBeenSet; } /** * Maximum bitrate in bits/second. For example, enter five megabits per second as * 5000000. */ inline void SetMaxBitrate(int value) { m_maxBitrateHasBeenSet = true; m_maxBitrate = value; } /** * Maximum bitrate in bits/second. For example, enter five megabits per second as * 5000000. */ inline Mpeg2Settings& WithMaxBitrate(int value) { SetMaxBitrate(value); return *this;} /** * Enforces separation between repeated (cadence) I-frames and I-frames inserted by * Scene Change Detection. If a scene change I-frame is within I-interval frames of * a cadence I-frame, the GOP is shrunk and/or stretched to the scene change * I-frame. GOP stretch requires enabling lookahead as well as setting I-interval. * The normal cadence resumes for the next GOP. This setting is only used when * Scene Change Detect is enabled. Note: Maximum GOP stretch = GOP size + * Min-I-interval - 1 */ inline int GetMinIInterval() const{ return m_minIInterval; } /** * Enforces separation between repeated (cadence) I-frames and I-frames inserted by * Scene Change Detection. If a scene change I-frame is within I-interval frames of * a cadence I-frame, the GOP is shrunk and/or stretched to the scene change * I-frame. GOP stretch requires enabling lookahead as well as setting I-interval. * The normal cadence resumes for the next GOP. This setting is only used when * Scene Change Detect is enabled. Note: Maximum GOP stretch = GOP size + * Min-I-interval - 1 */ inline bool MinIIntervalHasBeenSet() const { return m_minIIntervalHasBeenSet; } /** * Enforces separation between repeated (cadence) I-frames and I-frames inserted by * Scene Change Detection. If a scene change I-frame is within I-interval frames of * a cadence I-frame, the GOP is shrunk and/or stretched to the scene change * I-frame. GOP stretch requires enabling lookahead as well as setting I-interval. * The normal cadence resumes for the next GOP. This setting is only used when * Scene Change Detect is enabled. Note: Maximum GOP stretch = GOP size + * Min-I-interval - 1 */ inline void SetMinIInterval(int value) { m_minIIntervalHasBeenSet = true; m_minIInterval = value; } /** * Enforces separation between repeated (cadence) I-frames and I-frames inserted by * Scene Change Detection. If a scene change I-frame is within I-interval frames of * a cadence I-frame, the GOP is shrunk and/or stretched to the scene change * I-frame. GOP stretch requires enabling lookahead as well as setting I-interval. * The normal cadence resumes for the next GOP. This setting is only used when * Scene Change Detect is enabled. Note: Maximum GOP stretch = GOP size + * Min-I-interval - 1 */ inline Mpeg2Settings& WithMinIInterval(int value) { SetMinIInterval(value); return *this;} /** * Number of B-frames between reference frames. */ inline int GetNumberBFramesBetweenReferenceFrames() const{ return m_numberBFramesBetweenReferenceFrames; } /** * Number of B-frames between reference frames. */ inline bool NumberBFramesBetweenReferenceFramesHasBeenSet() const { return m_numberBFramesBetweenReferenceFramesHasBeenSet; } /** * Number of B-frames between reference frames. */ inline void SetNumberBFramesBetweenReferenceFrames(int value) { m_numberBFramesBetweenReferenceFramesHasBeenSet = true; m_numberBFramesBetweenReferenceFrames = value; } /** * Number of B-frames between reference frames. */ inline Mpeg2Settings& WithNumberBFramesBetweenReferenceFrames(int value) { SetNumberBFramesBetweenReferenceFrames(value); return *this;} /** * Using the API, enable ParFollowSource if you want the service to use the pixel * aspect ratio from the input. Using the console, do this by choosing Follow * source for Pixel aspect ratio. */ inline const Mpeg2ParControl& GetParControl() const{ return m_parControl; } /** * Using the API, enable ParFollowSource if you want the service to use the pixel * aspect ratio from the input. Using the console, do this by choosing Follow * source for Pixel aspect ratio. */ inline bool ParControlHasBeenSet() const { return m_parControlHasBeenSet; } /** * Using the API, enable ParFollowSource if you want the service to use the pixel * aspect ratio from the input. Using the console, do this by choosing Follow * source for Pixel aspect ratio. */ inline void SetParControl(const Mpeg2ParControl& value) { m_parControlHasBeenSet = true; m_parControl = value; } /** * Using the API, enable ParFollowSource if you want the service to use the pixel * aspect ratio from the input. Using the console, do this by choosing Follow * source for Pixel aspect ratio. */ inline void SetParControl(Mpeg2ParControl&& value) { m_parControlHasBeenSet = true; m_parControl = std::move(value); } /** * Using the API, enable ParFollowSource if you want the service to use the pixel * aspect ratio from the input. Using the console, do this by choosing Follow * source for Pixel aspect ratio. */ inline Mpeg2Settings& WithParControl(const Mpeg2ParControl& value) { SetParControl(value); return *this;} /** * Using the API, enable ParFollowSource if you want the service to use the pixel * aspect ratio from the input. Using the console, do this by choosing Follow * source for Pixel aspect ratio. */ inline Mpeg2Settings& WithParControl(Mpeg2ParControl&& value) { SetParControl(std::move(value)); return *this;} /** * Pixel Aspect Ratio denominator. */ inline int GetParDenominator() const{ return m_parDenominator; } /** * Pixel Aspect Ratio denominator. */ inline bool ParDenominatorHasBeenSet() const { return m_parDenominatorHasBeenSet; } /** * Pixel Aspect Ratio denominator. */ inline void SetParDenominator(int value) { m_parDenominatorHasBeenSet = true; m_parDenominator = value; } /** * Pixel Aspect Ratio denominator. */ inline Mpeg2Settings& WithParDenominator(int value) { SetParDenominator(value); return *this;} /** * Pixel Aspect Ratio numerator. */ inline int GetParNumerator() const{ return m_parNumerator; } /** * Pixel Aspect Ratio numerator. */ inline bool ParNumeratorHasBeenSet() const { return m_parNumeratorHasBeenSet; } /** * Pixel Aspect Ratio numerator. */ inline void SetParNumerator(int value) { m_parNumeratorHasBeenSet = true; m_parNumerator = value; } /** * Pixel Aspect Ratio numerator. */ inline Mpeg2Settings& WithParNumerator(int value) { SetParNumerator(value); return *this;} /** * Use Quality tuning level (Mpeg2QualityTuningLevel) to specifiy whether to use * single-pass or multipass video encoding. */ inline const Mpeg2QualityTuningLevel& GetQualityTuningLevel() const{ return m_qualityTuningLevel; } /** * Use Quality tuning level (Mpeg2QualityTuningLevel) to specifiy whether to use * single-pass or multipass video encoding. */ inline bool QualityTuningLevelHasBeenSet() const { return m_qualityTuningLevelHasBeenSet; } /** * Use Quality tuning level (Mpeg2QualityTuningLevel) to specifiy whether to use * single-pass or multipass video encoding. */ inline void SetQualityTuningLevel(const Mpeg2QualityTuningLevel& value) { m_qualityTuningLevelHasBeenSet = true; m_qualityTuningLevel = value; } /** * Use Quality tuning level (Mpeg2QualityTuningLevel) to specifiy whether to use * single-pass or multipass video encoding. */ inline void SetQualityTuningLevel(Mpeg2QualityTuningLevel&& value) { m_qualityTuningLevelHasBeenSet = true; m_qualityTuningLevel = std::move(value); } /** * Use Quality tuning level (Mpeg2QualityTuningLevel) to specifiy whether to use * single-pass or multipass video encoding. */ inline Mpeg2Settings& WithQualityTuningLevel(const Mpeg2QualityTuningLevel& value) { SetQualityTuningLevel(value); return *this;} /** * Use Quality tuning level (Mpeg2QualityTuningLevel) to specifiy whether to use * single-pass or multipass video encoding. */ inline Mpeg2Settings& WithQualityTuningLevel(Mpeg2QualityTuningLevel&& value) { SetQualityTuningLevel(std::move(value)); return *this;} /** * Use Rate control mode (Mpeg2RateControlMode) to specifiy whether the bitrate is * variable (vbr) or constant (cbr). */ inline const Mpeg2RateControlMode& GetRateControlMode() const{ return m_rateControlMode; } /** * Use Rate control mode (Mpeg2RateControlMode) to specifiy whether the bitrate is * variable (vbr) or constant (cbr). */ inline bool RateControlModeHasBeenSet() const { return m_rateControlModeHasBeenSet; } /** * Use Rate control mode (Mpeg2RateControlMode) to specifiy whether the bitrate is * variable (vbr) or constant (cbr). */ inline void SetRateControlMode(const Mpeg2RateControlMode& value) { m_rateControlModeHasBeenSet = true; m_rateControlMode = value; } /** * Use Rate control mode (Mpeg2RateControlMode) to specifiy whether the bitrate is * variable (vbr) or constant (cbr). */ inline void SetRateControlMode(Mpeg2RateControlMode&& value) { m_rateControlModeHasBeenSet = true; m_rateControlMode = std::move(value); } /** * Use Rate control mode (Mpeg2RateControlMode) to specifiy whether the bitrate is * variable (vbr) or constant (cbr). */ inline Mpeg2Settings& WithRateControlMode(const Mpeg2RateControlMode& value) { SetRateControlMode(value); return *this;} /** * Use Rate control mode (Mpeg2RateControlMode) to specifiy whether the bitrate is * variable (vbr) or constant (cbr). */ inline Mpeg2Settings& WithRateControlMode(Mpeg2RateControlMode&& value) { SetRateControlMode(std::move(value)); return *this;} /** * Scene change detection (inserts I-frames on scene changes). */ inline const Mpeg2SceneChangeDetect& GetSceneChangeDetect() const{ return m_sceneChangeDetect; } /** * Scene change detection (inserts I-frames on scene changes). */ inline bool SceneChangeDetectHasBeenSet() const { return m_sceneChangeDetectHasBeenSet; } /** * Scene change detection (inserts I-frames on scene changes). */ inline void SetSceneChangeDetect(const Mpeg2SceneChangeDetect& value) { m_sceneChangeDetectHasBeenSet = true; m_sceneChangeDetect = value; } /** * Scene change detection (inserts I-frames on scene changes). */ inline void SetSceneChangeDetect(Mpeg2SceneChangeDetect&& value) { m_sceneChangeDetectHasBeenSet = true; m_sceneChangeDetect = std::move(value); } /** * Scene change detection (inserts I-frames on scene changes). */ inline Mpeg2Settings& WithSceneChangeDetect(const Mpeg2SceneChangeDetect& value) { SetSceneChangeDetect(value); return *this;} /** * Scene change detection (inserts I-frames on scene changes). */ inline Mpeg2Settings& WithSceneChangeDetect(Mpeg2SceneChangeDetect&& value) { SetSceneChangeDetect(std::move(value)); return *this;} /** * Enables Slow PAL rate conversion. 23.976fps and 24fps input is relabeled as * 25fps, and audio is sped up correspondingly. */ inline const Mpeg2SlowPal& GetSlowPal() const{ return m_slowPal; } /** * Enables Slow PAL rate conversion. 23.976fps and 24fps input is relabeled as * 25fps, and audio is sped up correspondingly. */ inline bool SlowPalHasBeenSet() const { return m_slowPalHasBeenSet; } /** * Enables Slow PAL rate conversion. 23.976fps and 24fps input is relabeled as * 25fps, and audio is sped up correspondingly. */ inline void SetSlowPal(const Mpeg2SlowPal& value) { m_slowPalHasBeenSet = true; m_slowPal = value; } /** * Enables Slow PAL rate conversion. 23.976fps and 24fps input is relabeled as * 25fps, and audio is sped up correspondingly. */ inline void SetSlowPal(Mpeg2SlowPal&& value) { m_slowPalHasBeenSet = true; m_slowPal = std::move(value); } /** * Enables Slow PAL rate conversion. 23.976fps and 24fps input is relabeled as * 25fps, and audio is sped up correspondingly. */ inline Mpeg2Settings& WithSlowPal(const Mpeg2SlowPal& value) { SetSlowPal(value); return *this;} /** * Enables Slow PAL rate conversion. 23.976fps and 24fps input is relabeled as * 25fps, and audio is sped up correspondingly. */ inline Mpeg2Settings& WithSlowPal(Mpeg2SlowPal&& value) { SetSlowPal(std::move(value)); return *this;} /** * Softness. Selects quantizer matrix, larger values reduce high-frequency content * in the encoded image. */ inline int GetSoftness() const{ return m_softness; } /** * Softness. Selects quantizer matrix, larger values reduce high-frequency content * in the encoded image. */ inline bool SoftnessHasBeenSet() const { return m_softnessHasBeenSet; } /** * Softness. Selects quantizer matrix, larger values reduce high-frequency content * in the encoded image. */ inline void SetSoftness(int value) { m_softnessHasBeenSet = true; m_softness = value; } /** * Softness. Selects quantizer matrix, larger values reduce high-frequency content * in the encoded image. */ inline Mpeg2Settings& WithSoftness(int value) { SetSoftness(value); return *this;} /** * Adjust quantization within each frame based on spatial variation of content * complexity. */ inline const Mpeg2SpatialAdaptiveQuantization& GetSpatialAdaptiveQuantization() const{ return m_spatialAdaptiveQuantization; } /** * Adjust quantization within each frame based on spatial variation of content * complexity. */ inline bool SpatialAdaptiveQuantizationHasBeenSet() const { return m_spatialAdaptiveQuantizationHasBeenSet; } /** * Adjust quantization within each frame based on spatial variation of content * complexity. */ inline void SetSpatialAdaptiveQuantization(const Mpeg2SpatialAdaptiveQuantization& value) { m_spatialAdaptiveQuantizationHasBeenSet = true; m_spatialAdaptiveQuantization = value; } /** * Adjust quantization within each frame based on spatial variation of content * complexity. */ inline void SetSpatialAdaptiveQuantization(Mpeg2SpatialAdaptiveQuantization&& value) { m_spatialAdaptiveQuantizationHasBeenSet = true; m_spatialAdaptiveQuantization = std::move(value); } /** * Adjust quantization within each frame based on spatial variation of content * complexity. */ inline Mpeg2Settings& WithSpatialAdaptiveQuantization(const Mpeg2SpatialAdaptiveQuantization& value) { SetSpatialAdaptiveQuantization(value); return *this;} /** * Adjust quantization within each frame based on spatial variation of content * complexity. */ inline Mpeg2Settings& WithSpatialAdaptiveQuantization(Mpeg2SpatialAdaptiveQuantization&& value) { SetSpatialAdaptiveQuantization(std::move(value)); return *this;} /** * Produces a Type D-10 compatible bitstream (SMPTE 356M-2001). */ inline const Mpeg2Syntax& GetSyntax() const{ return m_syntax; } /** * Produces a Type D-10 compatible bitstream (SMPTE 356M-2001). */ inline bool SyntaxHasBeenSet() const { return m_syntaxHasBeenSet; } /** * Produces a Type D-10 compatible bitstream (SMPTE 356M-2001). */ inline void SetSyntax(const Mpeg2Syntax& value) { m_syntaxHasBeenSet = true; m_syntax = value; } /** * Produces a Type D-10 compatible bitstream (SMPTE 356M-2001). */ inline void SetSyntax(Mpeg2Syntax&& value) { m_syntaxHasBeenSet = true; m_syntax = std::move(value); } /** * Produces a Type D-10 compatible bitstream (SMPTE 356M-2001). */ inline Mpeg2Settings& WithSyntax(const Mpeg2Syntax& value) { SetSyntax(value); return *this;} /** * Produces a Type D-10 compatible bitstream (SMPTE 356M-2001). */ inline Mpeg2Settings& WithSyntax(Mpeg2Syntax&& value) { SetSyntax(std::move(value)); return *this;} /** * Only use Telecine (Mpeg2Telecine) when you set Framerate (Framerate) to 29.970. * Set Telecine (Mpeg2Telecine) to Hard (hard) to produce a 29.97i output from a * 23.976 input. Set it to Soft (soft) to produce 23.976 output and leave * converstion to the player. */ inline const Mpeg2Telecine& GetTelecine() const{ return m_telecine; } /** * Only use Telecine (Mpeg2Telecine) when you set Framerate (Framerate) to 29.970. * Set Telecine (Mpeg2Telecine) to Hard (hard) to produce a 29.97i output from a * 23.976 input. Set it to Soft (soft) to produce 23.976 output and leave * converstion to the player. */ inline bool TelecineHasBeenSet() const { return m_telecineHasBeenSet; } /** * Only use Telecine (Mpeg2Telecine) when you set Framerate (Framerate) to 29.970. * Set Telecine (Mpeg2Telecine) to Hard (hard) to produce a 29.97i output from a * 23.976 input. Set it to Soft (soft) to produce 23.976 output and leave * converstion to the player. */ inline void SetTelecine(const Mpeg2Telecine& value) { m_telecineHasBeenSet = true; m_telecine = value; } /** * Only use Telecine (Mpeg2Telecine) when you set Framerate (Framerate) to 29.970. * Set Telecine (Mpeg2Telecine) to Hard (hard) to produce a 29.97i output from a * 23.976 input. Set it to Soft (soft) to produce 23.976 output and leave * converstion to the player. */ inline void SetTelecine(Mpeg2Telecine&& value) { m_telecineHasBeenSet = true; m_telecine = std::move(value); } /** * Only use Telecine (Mpeg2Telecine) when you set Framerate (Framerate) to 29.970. * Set Telecine (Mpeg2Telecine) to Hard (hard) to produce a 29.97i output from a * 23.976 input. Set it to Soft (soft) to produce 23.976 output and leave * converstion to the player. */ inline Mpeg2Settings& WithTelecine(const Mpeg2Telecine& value) { SetTelecine(value); return *this;} /** * Only use Telecine (Mpeg2Telecine) when you set Framerate (Framerate) to 29.970. * Set Telecine (Mpeg2Telecine) to Hard (hard) to produce a 29.97i output from a * 23.976 input. Set it to Soft (soft) to produce 23.976 output and leave * converstion to the player. */ inline Mpeg2Settings& WithTelecine(Mpeg2Telecine&& value) { SetTelecine(std::move(value)); return *this;} /** * Adjust quantization within each frame based on temporal variation of content * complexity. */ inline const Mpeg2TemporalAdaptiveQuantization& GetTemporalAdaptiveQuantization() const{ return m_temporalAdaptiveQuantization; } /** * Adjust quantization within each frame based on temporal variation of content * complexity. */ inline bool TemporalAdaptiveQuantizationHasBeenSet() const { return m_temporalAdaptiveQuantizationHasBeenSet; } /** * Adjust quantization within each frame based on temporal variation of content * complexity. */ inline void SetTemporalAdaptiveQuantization(const Mpeg2TemporalAdaptiveQuantization& value) { m_temporalAdaptiveQuantizationHasBeenSet = true; m_temporalAdaptiveQuantization = value; } /** * Adjust quantization within each frame based on temporal variation of content * complexity. */ inline void SetTemporalAdaptiveQuantization(Mpeg2TemporalAdaptiveQuantization&& value) { m_temporalAdaptiveQuantizationHasBeenSet = true; m_temporalAdaptiveQuantization = std::move(value); } /** * Adjust quantization within each frame based on temporal variation of content * complexity. */ inline Mpeg2Settings& WithTemporalAdaptiveQuantization(const Mpeg2TemporalAdaptiveQuantization& value) { SetTemporalAdaptiveQuantization(value); return *this;} /** * Adjust quantization within each frame based on temporal variation of content * complexity. */ inline Mpeg2Settings& WithTemporalAdaptiveQuantization(Mpeg2TemporalAdaptiveQuantization&& value) { SetTemporalAdaptiveQuantization(std::move(value)); return *this;} private: Mpeg2AdaptiveQuantization m_adaptiveQuantization; bool m_adaptiveQuantizationHasBeenSet; int m_bitrate; bool m_bitrateHasBeenSet; Mpeg2CodecLevel m_codecLevel; bool m_codecLevelHasBeenSet; Mpeg2CodecProfile m_codecProfile; bool m_codecProfileHasBeenSet; Mpeg2DynamicSubGop m_dynamicSubGop; bool m_dynamicSubGopHasBeenSet; Mpeg2FramerateControl m_framerateControl; bool m_framerateControlHasBeenSet; Mpeg2FramerateConversionAlgorithm m_framerateConversionAlgorithm; bool m_framerateConversionAlgorithmHasBeenSet; int m_framerateDenominator; bool m_framerateDenominatorHasBeenSet; int m_framerateNumerator; bool m_framerateNumeratorHasBeenSet; int m_gopClosedCadence; bool m_gopClosedCadenceHasBeenSet; double m_gopSize; bool m_gopSizeHasBeenSet; Mpeg2GopSizeUnits m_gopSizeUnits; bool m_gopSizeUnitsHasBeenSet; int m_hrdBufferInitialFillPercentage; bool m_hrdBufferInitialFillPercentageHasBeenSet; int m_hrdBufferSize; bool m_hrdBufferSizeHasBeenSet; Mpeg2InterlaceMode m_interlaceMode; bool m_interlaceModeHasBeenSet; Mpeg2IntraDcPrecision m_intraDcPrecision; bool m_intraDcPrecisionHasBeenSet; int m_maxBitrate; bool m_maxBitrateHasBeenSet; int m_minIInterval; bool m_minIIntervalHasBeenSet; int m_numberBFramesBetweenReferenceFrames; bool m_numberBFramesBetweenReferenceFramesHasBeenSet; Mpeg2ParControl m_parControl; bool m_parControlHasBeenSet; int m_parDenominator; bool m_parDenominatorHasBeenSet; int m_parNumerator; bool m_parNumeratorHasBeenSet; Mpeg2QualityTuningLevel m_qualityTuningLevel; bool m_qualityTuningLevelHasBeenSet; Mpeg2RateControlMode m_rateControlMode; bool m_rateControlModeHasBeenSet; Mpeg2SceneChangeDetect m_sceneChangeDetect; bool m_sceneChangeDetectHasBeenSet; Mpeg2SlowPal m_slowPal; bool m_slowPalHasBeenSet; int m_softness; bool m_softnessHasBeenSet; Mpeg2SpatialAdaptiveQuantization m_spatialAdaptiveQuantization; bool m_spatialAdaptiveQuantizationHasBeenSet; Mpeg2Syntax m_syntax; bool m_syntaxHasBeenSet; Mpeg2Telecine m_telecine; bool m_telecineHasBeenSet; Mpeg2TemporalAdaptiveQuantization m_temporalAdaptiveQuantization; bool m_temporalAdaptiveQuantizationHasBeenSet; }; } // namespace Model } // namespace MediaConvert } // namespace Aws
44.959721
194
0.721896
[ "model" ]
9ee1f8f9921bb4bce215ee17efb6acb7dbb5b8aa
4,945
h
C
lib/extras/packed_image.h
cagelight/libjxl
d02ac127e9c5cbe0135b05141ce6712a210c8114
[ "BSD-3-Clause" ]
453
2021-05-25T15:53:07.000Z
2022-03-30T05:32:31.000Z
lib/extras/packed_image.h
cagelight/libjxl
d02ac127e9c5cbe0135b05141ce6712a210c8114
[ "BSD-3-Clause" ]
659
2021-05-25T16:33:46.000Z
2022-03-31T14:59:34.000Z
lib/extras/packed_image.h
cagelight/libjxl
d02ac127e9c5cbe0135b05141ce6712a210c8114
[ "BSD-3-Clause" ]
105
2021-05-25T16:11:10.000Z
2022-03-29T09:52:09.000Z
// Copyright (c) the JPEG XL Project Authors. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #ifndef LIB_EXTRAS_PACKED_IMAGE_H_ #define LIB_EXTRAS_PACKED_IMAGE_H_ // Helper class for storing external (int or float, interleaved) images. This is // the common format used by other libraries and in the libjxl API. #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <memory> #include <string> #include <vector> #include "jxl/codestream_header.h" #include "jxl/types.h" #include "lib/jxl/base/status.h" #include "lib/jxl/common.h" namespace jxl { namespace extras { // Class representing an interleaved image with a bunch of channels. class PackedImage { public: PackedImage(size_t xsize, size_t ysize, const JxlPixelFormat& format) : PackedImage(xsize, ysize, format, CalcStride(format, xsize)) {} PackedImage(size_t xsize, size_t ysize, const JxlPixelFormat& format, size_t stride) : xsize(xsize), ysize(ysize), stride(stride), format(format), pixels_size(ysize * stride), pixels_(malloc(pixels_size), free) {} // Construct the image using the passed pixel buffer. The buffer is owned by // this object and released with free(). PackedImage(size_t xsize, size_t ysize, const JxlPixelFormat& format, void* pixels, size_t pixels_size) : xsize(xsize), ysize(ysize), stride(CalcStride(format, xsize)), format(format), pixels_size(pixels_size), pixels_(pixels, free) { JXL_ASSERT(pixels_size >= stride * ysize); } // The interleaved pixels as defined in the storage format. void* pixels() const { return pixels_.get(); } // The image size in pixels. size_t xsize; size_t ysize; // Whether the y coordinate is flipped (y=0 is the last row). bool flipped_y = false; // The number of bytes per row. size_t stride; // Pixel storage format and buffer size of the pixels_ pointer. JxlPixelFormat format; size_t pixels_size; static size_t BitsPerChannel(JxlDataType data_type) { switch (data_type) { case JXL_TYPE_BOOLEAN: return 1; case JXL_TYPE_UINT8: return 8; case JXL_TYPE_UINT16: return 16; case JXL_TYPE_UINT32: return 32; case JXL_TYPE_FLOAT: return 32; case JXL_TYPE_FLOAT16: return 16; // No default, give compiler error if new type not handled. } return 0; // Indicate invalid data type. } private: static size_t CalcStride(const JxlPixelFormat& format, size_t xsize) { size_t stride = xsize * (BitsPerChannel(format.data_type) * format.num_channels / jxl::kBitsPerByte); if (format.align > 1) { stride = jxl::DivCeil(stride, format.align) * format.align; } return stride; } std::unique_ptr<void, decltype(free)*> pixels_; }; // Helper class representing a frame, as seen from the API. Animations will have // multiple frames, but a single frame can have a color/grayscale channel and // multiple extra channels. The order of the extra channels should be the same // as all other frames in the same image. class PackedFrame { public: template <typename... Args> explicit PackedFrame(Args&&... args) : color(std::forward<Args>(args)...) {} // The Frame metadata. JxlFrameHeader frame_info = {}; std::string name; // Offset of the frame in the image. // TODO(deymo): Add support in the API for this. size_t x0 = 0; size_t y0 = 0; // Whether this frame should be blended with the previous one. // TODO(deymo): Maybe add support for this in the API. bool blend = false; bool use_for_next_frame = false; // The pixel data for the color (or grayscale) channels. PackedImage color; // Extra channel image data. std::vector<PackedImage> extra_channels; }; // Optional metadata associated with a file class PackedMetadata { public: std::vector<uint8_t> exif; std::vector<uint8_t> iptc; std::vector<uint8_t> jumbf; std::vector<uint8_t> xmp; }; // Helper class representing a JXL image file as decoded to pixels from the API. class PackedPixelFile { public: JxlBasicInfo info = {}; // The extra channel metadata information. struct PackedExtraChannel { PackedExtraChannel(const JxlExtraChannelInfo& ec_info, const std::string& name) : ec_info(ec_info), name(name) {} JxlExtraChannelInfo ec_info; std::string name; }; std::vector<PackedExtraChannel> extra_channels_info; // Color information. If the icc is empty, the JxlColorEncoding should be used // instead. std::vector<uint8_t> icc; JxlColorEncoding color_encoding = {}; std::vector<PackedFrame> frames; PackedMetadata metadata; }; } // namespace extras } // namespace jxl #endif // LIB_EXTRAS_PACKED_IMAGE_H_
28.75
80
0.686957
[ "object", "vector" ]
9eec3e04bfbe66bf9b9d0aeeaaa3040b86dabe35
9,769
h
C
toolchain/arm-openwrt-linux/arm-openwrt-linux-muslgnueabi/include/c++/5.2.0/bits/shared_ptr_atomic.h
hoastyle/lib_robot_build
3506b7f569f12ae80f8cfff2998383ca1a3aeea4
[ "MIT" ]
20
2016-05-16T11:09:04.000Z
2021-12-08T09:30:33.000Z
toolchain/arm-openwrt-linux/arm-openwrt-linux-muslgnueabi/include/c++/5.2.0/bits/shared_ptr_atomic.h
hoastyle/lib_robot_build
3506b7f569f12ae80f8cfff2998383ca1a3aeea4
[ "MIT" ]
11
2019-09-01T06:56:02.000Z
2020-04-29T11:46:25.000Z
toolchain/arm-openwrt-linux/arm-openwrt-linux-muslgnueabi/include/c++/5.2.0/bits/shared_ptr_atomic.h
hoastyle/lib_robot_build
3506b7f569f12ae80f8cfff2998383ca1a3aeea4
[ "MIT" ]
11
2016-05-02T09:17:12.000Z
2021-12-08T09:30:35.000Z
// shared_ptr atomic access -*- C++ -*- // Copyright (C) 2014-2015 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, 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 General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. /** @file bits/shared_ptr_atomic.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{memory} */ #ifndef _SHARED_PTR_ATOMIC_H #define _SHARED_PTR_ATOMIC_H 1 #include <bits/atomic_base.h> namespace std _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION /** * @addtogroup pointer_abstractions * @{ */ struct _Sp_locker { _Sp_locker(const _Sp_locker&) = delete; _Sp_locker& operator=(const _Sp_locker&) = delete; #ifdef __GTHREADS explicit _Sp_locker(const void*) noexcept; _Sp_locker(const void*, const void*) noexcept; ~_Sp_locker(); private: unsigned char _M_key1; unsigned char _M_key2; #else explicit _Sp_locker(const void*, const void* = nullptr) { } #endif }; /** * @brief Report whether shared_ptr atomic operations are lock-free. * @param __p A non-null pointer to a shared_ptr object. * @return True if atomic access to @c *__p is lock-free, false otherwise. * @{ */ template<typename _Tp, _Lock_policy _Lp> inline bool atomic_is_lock_free(const __shared_ptr<_Tp, _Lp>* __p) { #ifdef __GTHREADS return __gthread_active_p() == 0; #else return true; #endif } template<typename _Tp> inline bool atomic_is_lock_free(const shared_ptr<_Tp>* __p) { return std::atomic_is_lock_free<_Tp, __default_lock_policy>(__p); } // @} /** * @brief Atomic load for shared_ptr objects. * @param __p A non-null pointer to a shared_ptr object. * @return @c *__p * * The memory order shall not be @c memory_order_release or * @c memory_order_acq_rel. * @{ */ template<typename _Tp> inline shared_ptr<_Tp> atomic_load_explicit(const shared_ptr<_Tp>* __p, memory_order) { _Sp_locker __lock{__p}; return *__p; } template<typename _Tp> inline shared_ptr<_Tp> atomic_load(const shared_ptr<_Tp>* __p) { return std::atomic_load_explicit(__p, memory_order_seq_cst); } template<typename _Tp, _Lock_policy _Lp> inline __shared_ptr<_Tp, _Lp> atomic_load_explicit(const __shared_ptr<_Tp, _Lp>* __p, memory_order) { _Sp_locker __lock{__p}; return *__p; } template<typename _Tp, _Lock_policy _Lp> inline __shared_ptr<_Tp, _Lp> atomic_load(const __shared_ptr<_Tp, _Lp>* __p) { return std::atomic_load_explicit(__p, memory_order_seq_cst); } // @} /** * @brief Atomic store for shared_ptr objects. * @param __p A non-null pointer to a shared_ptr object. * @param __r The value to store. * * The memory order shall not be @c memory_order_acquire or * @c memory_order_acq_rel. * @{ */ template<typename _Tp> inline void atomic_store_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r, memory_order) { _Sp_locker __lock{__p}; __p->swap(__r); // use swap so that **__p not destroyed while lock held } template<typename _Tp> inline void atomic_store(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r) { std::atomic_store_explicit(__p, std::move(__r), memory_order_seq_cst); } template<typename _Tp, _Lock_policy _Lp> inline void atomic_store_explicit(__shared_ptr<_Tp, _Lp>* __p, __shared_ptr<_Tp, _Lp> __r, memory_order) { _Sp_locker __lock{__p}; __p->swap(__r); // use swap so that **__p not destroyed while lock held } template<typename _Tp, _Lock_policy _Lp> inline void atomic_store(__shared_ptr<_Tp, _Lp>* __p, __shared_ptr<_Tp, _Lp> __r) { std::atomic_store_explicit(__p, std::move(__r), memory_order_seq_cst); } // @} /** * @brief Atomic exchange for shared_ptr objects. * @param __p A non-null pointer to a shared_ptr object. * @param __r New value to store in @c *__p. * @return The original value of @c *__p * @{ */ template<typename _Tp> inline shared_ptr<_Tp> atomic_exchange_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r, memory_order) { _Sp_locker __lock{__p}; __p->swap(__r); return __r; } template<typename _Tp> inline shared_ptr<_Tp> atomic_exchange(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r) { return std::atomic_exchange_explicit(__p, std::move(__r), memory_order_seq_cst); } template<typename _Tp, _Lock_policy _Lp> inline __shared_ptr<_Tp, _Lp> atomic_exchange_explicit(__shared_ptr<_Tp, _Lp>* __p, __shared_ptr<_Tp, _Lp> __r, memory_order) { _Sp_locker __lock{__p}; __p->swap(__r); return __r; } template<typename _Tp, _Lock_policy _Lp> inline __shared_ptr<_Tp, _Lp> atomic_exchange(__shared_ptr<_Tp, _Lp>* __p, __shared_ptr<_Tp, _Lp> __r) { return std::atomic_exchange_explicit(__p, std::move(__r), memory_order_seq_cst); } // @} /** * @brief Atomic compare-and-swap for shared_ptr objects. * @param __p A non-null pointer to a shared_ptr object. * @param __v A non-null pointer to a shared_ptr object. * @param __w A non-null pointer to a shared_ptr object. * @return True if @c *__p was equivalent to @c *__v, false otherwise. * * The memory order for failure shall not be @c memory_order_release or * @c memory_order_acq_rel, or stronger than the memory order for success. * @{ */ template<typename _Tp> bool atomic_compare_exchange_strong_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v, shared_ptr<_Tp> __w, memory_order, memory_order) { shared_ptr<_Tp> __x; // goes out of scope after __lock _Sp_locker __lock{__p, __v}; owner_less<shared_ptr<_Tp>> __less; if (*__p == *__v && !__less(*__p, *__v) && !__less(*__v, *__p)) { __x = std::move(*__p); *__p = std::move(__w); return true; } __x = std::move(*__v); *__v = *__p; return false; } template<typename _Tp> inline bool atomic_compare_exchange_strong(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v, shared_ptr<_Tp> __w) { return std::atomic_compare_exchange_strong_explicit(__p, __v, std::move(__w), memory_order_seq_cst, memory_order_seq_cst); } template<typename _Tp> inline bool atomic_compare_exchange_weak_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v, shared_ptr<_Tp> __w, memory_order __success, memory_order __failure) { return std::atomic_compare_exchange_strong_explicit(__p, __v, std::move(__w), __success, __failure); } template<typename _Tp> inline bool atomic_compare_exchange_weak(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v, shared_ptr<_Tp> __w) { return std::atomic_compare_exchange_weak_explicit(__p, __v, std::move(__w), memory_order_seq_cst, memory_order_seq_cst); } template<typename _Tp, _Lock_policy _Lp> bool atomic_compare_exchange_strong_explicit(__shared_ptr<_Tp, _Lp>* __p, __shared_ptr<_Tp, _Lp>* __v, __shared_ptr<_Tp, _Lp> __w, memory_order, memory_order) { __shared_ptr<_Tp, _Lp> __x; // goes out of scope after __lock _Sp_locker __lock{__p, __v}; owner_less<__shared_ptr<_Tp, _Lp>> __less; if (*__p == *__v && !__less(*__p, *__v) && !__less(*__v, *__p)) { __x = std::move(*__p); *__p = std::move(__w); return true; } __x = std::move(*__v); *__v = *__p; return false; } template<typename _Tp, _Lock_policy _Lp> inline bool atomic_compare_exchange_strong(__shared_ptr<_Tp, _Lp>* __p, __shared_ptr<_Tp, _Lp>* __v, __shared_ptr<_Tp, _Lp> __w) { return std::atomic_compare_exchange_strong_explicit(__p, __v, std::move(__w), memory_order_seq_cst, memory_order_seq_cst); } template<typename _Tp, _Lock_policy _Lp> inline bool atomic_compare_exchange_weak_explicit(__shared_ptr<_Tp, _Lp>* __p, __shared_ptr<_Tp, _Lp>* __v, __shared_ptr<_Tp, _Lp> __w, memory_order __success, memory_order __failure) { return std::atomic_compare_exchange_strong_explicit(__p, __v, std::move(__w), __success, __failure); } template<typename _Tp, _Lock_policy _Lp> inline bool atomic_compare_exchange_weak(__shared_ptr<_Tp, _Lp>* __p, __shared_ptr<_Tp, _Lp>* __v, __shared_ptr<_Tp, _Lp> __w) { return std::atomic_compare_exchange_weak_explicit(__p, __v, std::move(__w), memory_order_seq_cst, memory_order_seq_cst); } // @} // @} group pointer_abstractions _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif // _SHARED_PTR_ATOMIC_H
29.513595
78
0.676221
[ "object" ]
9eecb4f6af695469d2be99034abd7b8db43e762c
38,660
h
C
src/server/game/Scripting/ScriptMgr.h
Zone-Emu/ZoneEmuCataclysm
6277efff6cb5adfe8b7a718bf376e81609fa9a6c
[ "OpenSSL" ]
1
2019-03-23T19:32:57.000Z
2019-03-23T19:32:57.000Z
src/server/game/Scripting/ScriptMgr.h
Zone-Emu/ZoneEmuCataclysm
6277efff6cb5adfe8b7a718bf376e81609fa9a6c
[ "OpenSSL" ]
null
null
null
src/server/game/Scripting/ScriptMgr.h
Zone-Emu/ZoneEmuCataclysm
6277efff6cb5adfe8b7a718bf376e81609fa9a6c
[ "OpenSSL" ]
null
null
null
/* * Copyright (C) 2005 - 2012 MaNGOS <http://www.getmangos.com/> * * Copyright (C) 2008 - 2012 Trinity <http://www.trinitycore.org/> * * Copyright (C) 2010 - 2012 ArkCORE <http://www.arkania.net/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef SC_SCRIPTMGR_H #define SC_SCRIPTMGR_H #include "Common.h" #include <ace/Singleton.h> #include "DBCStores.h" #include "Player.h" #include "SharedDefines.h" #include "World.h" #include "Weather.h" #include "Creature.h" class AuctionHouseObject; class AuraScript; class Battleground; class BattlegroundMap; class Channel; class ChatCommand; class Creature; class CreatureAI; class DynamicObject; class GameObject; class Guild; class GridMap; class Group; class InstanceMap; class InstanceScript; class Item; class Map; class OutdoorPvP; class Player; class Quest; class ScriptMgr; class Spell; class SpellScript; class SpellCastTargets; class Transport; class Unit; class Vehicle; class WorldPacket; class WorldSocket; class WorldObject; struct AchievementCriteriaData; struct AuctionEntry; struct Condition; struct ItemPrototype; struct OutdoorPvPData; #define VISIBLE_RANGE (166.0f) //MAX visible range (size of grid) // Generic scripting text function. void DoScriptText(int32 textEntry, WorldObject* pSource, Unit *pTarget = NULL); /* TODO: Add more script type classes. MailScript SessionScript CollisionScript ArenaTeamScript */ /* Standard procedure when adding new script type classes: First of all, define the actual class, and have it inherit from ScriptObject, like so: class MyScriptType : public ScriptObject { uint32 _someId; private: void RegisterSelf(); protected: MyScriptType(const char* name, uint32 someId) : ScriptObject(name), _someId(someId) { ScriptMgr::ScriptRegistry<MyScriptType>::AddScript(this); } public: // If a virtual function in your script type class is not necessarily // required to be overridden, just declare it virtual with an empty // body. If, on the other hand, it's logical only to override it (i.e. // if it's the only method in the class), make it pure virtual, by adding // = 0 to it. virtual void OnSomeEvent(uint32 someArg1, std::string& someArg2) { } // This is a pure virtual function: virtual void OnAnotherEvent(uint32 someArg) = 0; } Next, you need to add a specialization for ScriptRegistry. Put this in the bottom of ScriptMgr.cpp: template class ScriptMgr::ScriptRegistry<MyScriptType>; Now, add a cleanup routine in ScriptMgr::~ScriptMgr: SCR_CLEAR(MyScriptType); Now your script type is good to go with the script system. What you need to do now is add functions to ScriptMgr that can be called from the core to actually trigger certain events. For example, in ScriptMgr.h: void OnSomeEvent(uint32 someArg1, std::string& someArg2); void OnAnotherEvent(uint32 someArg); In ScriptMgr.cpp: void ScriptMgr::OnSomeEvent(uint32 someArg1, std::string& someArg2) { FOREACH_SCRIPT(MyScriptType)->OnSomeEvent(someArg1, someArg2); } void ScriptMgr::OnAnotherEvent(uint32 someArg) { FOREACH_SCRIPT(MyScriptType)->OnAnotherEvent(someArg1, someArg2); } Now you simply call these two functions from anywhere in the core to trigger the event on all registered scripts of that type. */ class ScriptObject { friend class ScriptMgr; public: // Do not override this in scripts; it should be overridden by the various script type classes. It indicates // whether or not this script type must be assigned in the database. virtual bool IsDatabaseBound() const { return false; } const std::string& GetName() const { return _name; } protected: ScriptObject(const char* name) : _name(std::string(name)) { } virtual ~ScriptObject() { } private: const std::string _name; }; template<class TObject> class UpdatableScript { protected: UpdatableScript() { } public: virtual void OnUpdate(TObject* /*obj*/, uint32 /*diff*/) { } }; class SpellScriptLoader: public ScriptObject { protected: SpellScriptLoader(const char* name); public: bool IsDatabaseBound() const { return true; } // Should return a fully valid SpellScript pointer. virtual SpellScript* GetSpellScript() const { return NULL; } ; // Should return a fully valid AuraScript pointer. virtual AuraScript* GetAuraScript() const { return NULL; } ; }; class ServerScript: public ScriptObject { protected: ServerScript(const char* name); public: // Called when reactive socket I/O is started (WorldSocketMgr). virtual void OnNetworkStart() { } // Called when reactive I/O is stopped. virtual void OnNetworkStop() { } // Called when a remote socket establishes a connection to the server. Do not store the socket object. virtual void OnSocketOpen(WorldSocket* /*socket*/) { } // Called when a socket is closed. Do not store the socket object, and do not rely on the connection // being open; it is not. virtual void OnSocketClose(WorldSocket* /*socket*/, bool /*wasNew*/) { } // Called when a packet is sent to a client. The packet object is a copy of the original packet, so reading // and modifying it is safe. virtual void OnPacketSend(WorldSocket* /*socket*/, WorldPacket& /*packet*/) { } // Called when a (valid) packet is received by a client. The packet object is a copy of the original packet, so // reading and modifying it is safe. virtual void OnPacketReceive(WorldSocket* /*socket*/, WorldPacket& /*packet*/) { } // Called when an invalid (unknown opcode) packet is received by a client. The packet is a reference to the orignal // packet; not a copy. This allows you to actually handle unknown packets (for whatever purpose). virtual void OnUnknownPacketReceive(WorldSocket* /*socket*/, WorldPacket& /*packet*/) { } }; class WorldScript: public ScriptObject, public UpdatableScript<void> { protected: WorldScript(const char* name); public: // Called when the open/closed state of the world changes. virtual void OnOpenStateChange(bool /*open*/) { } // Called after the world configuration is (re)loaded. virtual void OnConfigLoad(bool /*reload*/) { } // Called before the message of the day is changed. virtual void OnMotdChange(std::string& /*newMotd*/) { } // Called when a world shutdown is initiated. virtual void OnShutdownInitiate(ShutdownExitCode /*code*/, ShutdownMask /*mask*/) { } // Called when a world shutdown is cancelled. virtual void OnShutdownCancel() { } // Called on every world tick (don't execute too heavy code here). virtual void OnUpdate(void* /*null*/, uint32 /*diff*/) { } // Called when the world is started. virtual void OnStartup() { } // Called when the world is actually shut down. virtual void OnShutdown() { } }; class FormulaScript: public ScriptObject { protected: FormulaScript(const char* name); public: // Called after calculating honor. virtual void OnHonorCalculation(float& /*honor*/, uint8 /*level*/, float /*multiplier*/) { } // Called after gray level calculation. virtual void OnGrayLevelCalculation(uint8& /*grayLevel*/, uint8 /*playerLevel*/) { } // Called after calculating experience color. virtual void OnColorCodeCalculation(XPColorChar& /*color*/, uint8 /*playerLevel*/, uint8 /*mobLevel*/) { } // Called after calculating zero difference. virtual void OnZeroDifferenceCalculation(uint8& /*diff*/, uint8 /*playerLevel*/) { } // Called after calculating base experience gain. virtual void OnBaseGainCalculation(uint32& /*gain*/, uint8 /*playerLevel*/, uint8 /*mobLevel*/, ContentLevels /*content*/) { } // Called after calculating experience gain. virtual void OnGainCalculation(uint32& /*gain*/, Player* /*player*/, Unit* /*unit*/) { } // Called when calculating the experience rate for group experience. virtual void OnGroupRateCalculation(float& /*rate*/, uint32 /*count*/, bool /*isRaid*/) { } }; template<class TMap> class MapScript: public UpdatableScript<TMap> { MapEntry const* _mapEntry; protected: MapScript(uint32 mapId) : _mapEntry(sMapStore.LookupEntry(mapId)) { if (!_mapEntry) sLog->outError("Invalid MapScript for %u; no such map ID.", mapId); } public: // Gets the MapEntry structure associated with this script. Can return NULL. MapEntry const* GetEntry() { return _mapEntry; } // Called when the map is created. virtual void OnCreate(TMap* /*map*/) { } // Called just before the map is destroyed. virtual void OnDestroy(TMap* /*map*/) { } // Called when a grid map is loaded. virtual void OnLoadGridMap(TMap* /*map*/, GridMap* /*gmap*/, uint32 /*gx*/, uint32 /*gy*/) { } // Called when a grid map is unloaded. virtual void OnUnloadGridMap(TMap* /*map*/, GridMap* /*gmap*/, uint32 /*gx*/, uint32 /*gy*/) { } // Called when a player enters the map. virtual void OnPlayerEnter(TMap* /*map*/, Player* /*player*/) { } // Called when a player leaves the map. virtual void OnPlayerLeave(TMap* /*map*/, Player* /*player*/) { } // Called on every map update tick. virtual void OnUpdate(TMap* /*map*/, uint32 /*diff*/) { } }; class WorldMapScript: public ScriptObject, public MapScript<Map> { protected: WorldMapScript(const char* name, uint32 mapId); }; class InstanceMapScript: public ScriptObject, public MapScript<InstanceMap> { protected: InstanceMapScript(const char* name, uint32 mapId); public: bool IsDatabaseBound() const { return true; } // Gets an InstanceScript object for this instance. virtual InstanceScript* GetInstanceScript(InstanceMap* /*map*/) const { return NULL; } }; class BattlegroundMapScript: public ScriptObject, public MapScript< BattlegroundMap> { protected: BattlegroundMapScript(const char* name, uint32 mapId); }; class ItemScript: public ScriptObject { protected: ItemScript(const char* name); public: bool IsDatabaseBound() const { return true; } // Called when a dummy spell effect is triggered on the item. virtual bool OnDummyEffect(Unit* /*caster*/, uint32 /*spellId*/, SpellEffIndex /*effIndex*/, Item* /*target*/) { return false; } // Called when a player accepts a quest from the item. virtual bool OnQuestAccept(Player* /*player*/, Item* /*item*/, Quest const* /*quest*/) { return false; } // Called when a player uses the item. virtual bool OnUse(Player* /*player*/, Item* /*item*/, SpellCastTargets const& /*targets*/) { return false; } // Called when the item expires (is destroyed). virtual bool OnExpire(Player* /*player*/, ItemPrototype const* /*proto*/) { return false; } }; class CreatureScript: public ScriptObject, public UpdatableScript<Creature> { protected: CreatureScript(const char* name); public: bool IsDatabaseBound() const { return true; } // Called when a dummy spell effect is triggered on the creature. virtual bool OnDummyEffect(Unit* /*caster*/, uint32 /*spellId*/, SpellEffIndex /*effIndex*/, Creature* /*target*/) { return false; } // Called when a player opens a gossip dialog with the creature. virtual bool OnGossipHello(Player* /*player*/, Creature* /*creature*/) { return false; } // Called when a player selects a gossip item in the creature's gossip menu. virtual bool OnGossipSelect(Player* /*player*/, Creature* /*creature*/, uint32 /*sender*/, uint32 /*action*/) { return false; } // Called when a player selects a gossip with a code in the creature's gossip menu. virtual bool OnGossipSelectCode(Player* /*player*/, Creature* /*creature*/, uint32 /*sender*/, uint32 /*action*/, const char* /*code*/) { return false; } // Called when a player accepts a quest from the creature. virtual bool OnQuestAccept(Player* /*player*/, Creature* /*creature*/, Quest const* /*quest*/) { return false; } // Called when a player selects a quest in the creature's quest menu. virtual bool OnQuestSelect(Player* /*player*/, Creature* /*creature*/, Quest const* /*quest*/) { return false; } // Called when a player completes a quest with the creature. virtual bool OnQuestComplete(Player* /*player*/, Creature* /*creature*/, Quest const* /*quest*/) { return false; } // Called when a player selects a quest reward. virtual bool OnQuestReward(Player* /*player*/, Creature* /*creature*/, Quest const* /*quest*/, uint32 /*opt*/) { return false; } // Called when the dialog status between a player and the creature is requested. virtual uint32 GetDialogStatus(Player* /*player*/, Creature* /*creature*/) { return 100; } // Called when a CreatureAI object is needed for the creature. virtual CreatureAI* GetAI(Creature* /*creature*/) const { return NULL; } // Called when a new Creature will eb created virtual Creature * GetCreatureScriptedClass() const { return NULL; } }; class GameObjectScript: public ScriptObject, public UpdatableScript<GameObject> { protected: GameObjectScript(const char* name); public: bool IsDatabaseBound() const { return true; } // Called when a dummy spell effect is triggered on the gameobject. virtual bool OnDummyEffect(Unit* /*caster*/, uint32 /*spellId*/, SpellEffIndex /*effIndex*/, GameObject* /*target*/) { return false; } // Called when a player opens a gossip dialog with the gameobject. virtual bool OnGossipHello(Player* /*player*/, GameObject* /*go*/) { return false; } // Called when a player selects a gossip item in the gameobject's gossip menu. virtual bool OnGossipSelect(Player* /*player*/, GameObject* /*go*/, uint32 /*sender*/, uint32 /*action*/) { return false; } // Called when a player selects a gossip with a code in the gameobject's gossip menu. virtual bool OnGossipSelectCode(Player* /*player*/, GameObject* /*go*/, uint32 /*sender*/, uint32 /*action*/, const char* /*code*/) { return false; } // Called when a player accepts a quest from the gameobject. virtual bool OnQuestAccept(Player* /*player*/, GameObject* /*go*/, Quest const* /*quest*/) { return false; } // Called when a player selects a quest reward. virtual bool OnQuestReward(Player* /*player*/, GameObject* /*go*/, Quest const* /*quest*/, uint32 /*opt*/) { return false; } // Called when the dialog status between a player and the gameobject is requested. virtual uint32 GetDialogStatus(Player* /*player*/, GameObject* /*go*/) { return 100; } // Called when the gameobject is destroyed (destructible buildings only). virtual void OnDestroyed(Player* /*player*/, GameObject* /*go*/, uint32 /*eventId*/) { } // Called when the game object is damaged (destructible buildings only). virtual void OnDamaged(GameObject* /*go*/, Player* /*player*/) { } }; class AreaTriggerScript: public ScriptObject { protected: AreaTriggerScript(const char* name); public: bool IsDatabaseBound() const { return true; } // Called when the area trigger is activated by a player. virtual bool OnTrigger(Player* /*player*/, AreaTriggerEntry const* /*trigger*/) { return false; } }; class BattlegroundScript: public ScriptObject { protected: BattlegroundScript(const char* name); public: bool IsDatabaseBound() const { return true; } // Should return a fully valid Battleground object for the type ID. virtual Battleground* GetBattleground() const = 0; }; class OutdoorPvPScript: public ScriptObject { protected: OutdoorPvPScript(const char* name); public: bool IsDatabaseBound() const { return true; } // Should return a fully valid OutdoorPvP object for the type ID. virtual OutdoorPvP* GetOutdoorPvP() const = 0; }; class CommandScript: public ScriptObject { protected: CommandScript(const char* name); public: // Should return a pointer to a valid command table (ChatCommand array) to be used by ChatHandler. virtual ChatCommand* GetCommands() const = 0; }; class WeatherScript: public ScriptObject, public UpdatableScript<Weather> { protected: WeatherScript(const char* name); public: bool IsDatabaseBound() const { return true; } // Called when the weather changes in the zone this script is associated with. virtual void OnChange(Weather* /*weather*/, WeatherState /*state*/, float /*grade*/) { } }; class AuctionHouseScript: public ScriptObject { protected: AuctionHouseScript(const char* name); public: // Called when an auction is added to an auction house. virtual void OnAuctionAdd(AuctionHouseObject* /*ah*/, AuctionEntry* /*entry*/) { } // Called when an auction is removed from an auction house. virtual void OnAuctionRemove(AuctionHouseObject* /*ah*/, AuctionEntry* /*entry*/) { } // Called when an auction was succesfully completed. virtual void OnAuctionSuccessful(AuctionHouseObject* /*ah*/, AuctionEntry* /*entry*/) { } // Called when an auction expires. virtual void OnAuctionExpire(AuctionHouseObject* /*ah*/, AuctionEntry* /*entry*/) { } }; class ConditionScript: public ScriptObject { protected: ConditionScript(const char* name); public: bool IsDatabaseBound() const { return true; } // Called when a single condition is checked for a player. virtual bool OnConditionCheck(Condition* /*condition*/, Player* /*player*/, Unit* /*invoker*/) { return true; } }; class VehicleScript: public ScriptObject { protected: VehicleScript(const char* name); public: // Called after a vehicle is installed. virtual void OnInstall(Vehicle* /*veh*/) { } // Called after a vehicle is uninstalled. virtual void OnUninstall(Vehicle* /*veh*/) { } // Called after a vehicle dies. virtual void OnDie(Vehicle* /*veh*/) { } // Called when a vehicle resets. virtual void OnReset(Vehicle* /*veh*/) { } // Called after an accessory is installed in a vehicle. virtual void OnInstallAccessory(Vehicle* /*veh*/, Creature* /*accessory*/) { } // Called after a passenger is added to a vehicle. virtual void OnAddPassenger(Vehicle* /*veh*/, Unit* /*passenger*/, int8 /*seatId*/) { } // Called after a passenger is removed from a vehicle. virtual void OnRemovePassenger(Vehicle* /*veh*/, Unit* /*passenger*/) { } }; class DynamicObjectScript: public ScriptObject, public UpdatableScript< DynamicObject> { protected: DynamicObjectScript(const char* name); }; class TransportScript: public ScriptObject, public UpdatableScript<Transport> { protected: TransportScript(const char* name); public: bool IsDatabaseBound() const { return true; } // Called when a player boards the transport. virtual void OnAddPassenger(Transport* /*transport*/, Player* /*player*/) { } // Called when a creature boards the transport. virtual void OnAddCreaturePassenger(Transport* /*transport*/, Creature* /*creature*/) { } // Called when a player exits the transport. virtual void OnRemovePassenger(Transport* /*transport*/, Player* /*player*/) { } // Called when a transport moves. virtual void OnRelocate(Transport* /*transport*/, uint32 /*waypointId*/, uint32 /*mapId*/, float /*x*/, float /*y*/, float /*z*/) { } }; class AchievementCriteriaScript: public ScriptObject { protected: AchievementCriteriaScript(const char* name); public: bool IsDatabaseBound() const { return true; } // Called when an additional criteria is checked. virtual bool OnCheck(Player* source, Unit* target) = 0; }; class PlayerScript: public ScriptObject { protected: PlayerScript(const char* name); public: // Called when a player kills another player virtual void OnPVPKill(Player* /*killer*/, Player* /*killed*/) { } // Called when a player kills a creature virtual void OnCreatureKill(Player* /*killer*/, Creature* /*killed*/) { } // Called when a player is killed by a creature virtual void OnPlayerKilledByCreature(Creature* /*killer*/, Player* /*killed*/) { } // Called when a player's level changes (right before the level is applied) virtual void OnLevelChanged(Player* /*player*/, uint8 /*newLevel*/) { } // Called when a player's free talent points change (right before the change is applied) virtual void OnFreeTalentPointsChanged(Player* /*player*/, uint32 /*points*/) { } // Called when a player's talent points are reset (right before the reset is done) virtual void OnTalentsReset(Player* /*player*/, bool /*no_cost*/) { } // Called when a player's money is modified (before the modification is done) virtual void OnMoneyChanged(Player* /*player*/, int32& /*amount*/) { } // Called when a player gains XP (before anything is given) virtual void OnGiveXP(Player* /*player*/, uint32& /*amount*/, Unit* /*victim*/) { } // Called when a player's reputation changes (before it is actually changed) virtual void OnReputationChange(Player* /*player*/, uint32 /*factionID*/, int32& /*standing*/, bool /*incremental*/) { } // Called when a duel is requested virtual void OnDuelRequest(Player* /*target*/, Player* /*challenger*/) { } // Called when a duel starts (after 3s countdown) virtual void OnDuelStart(Player* /*player1*/, Player* /*player2*/) { } // Called when a duel ends virtual void OnDuelEnd(Player* /*winner*/, Player* /*looser*/, DuelCompleteType /*type*/) { } // The following methods are called when a player sends a chat message virtual void OnChat(Player* /*player*/, uint32 /*type*/, uint32 /*lang*/, std::string /*msg*/) { } virtual void OnChat(Player* /*player*/, uint32 /*type*/, uint32 /*lang*/, std::string /*msg*/, Player* /*receiver*/) { } virtual void OnChat(Player* /*player*/, uint32 /*type*/, uint32 /*lang*/, std::string /*msg*/, Group* /*group*/) { } virtual void OnChat(Player* /*player*/, uint32 /*type*/, uint32 /*lang*/, std::string /*msg*/, Guild* /*guild*/) { } virtual void OnChat(Player* /*player*/, uint32 /*type*/, uint32 /*lang*/, std::string /*msg*/, Channel* /*channel*/) { } // Both of the below are called on emote opcodes virtual void OnEmote(Player* /*player*/, uint32 /*emote*/) { } virtual void OnTextEmote(Player* /*player*/, uint32 /*text_emote*/, uint32 /*emoteNum*/, uint64 /*guid*/) { } // Called in Spell::cast virtual void OnSpellCast(Player* /*player*/, Spell * /*spell*/, bool /*skipCheck*/) { } // Called when a player logs in or out virtual void OnLogin(Player* /*player*/) { } virtual void OnLogout(Player* /*player*/) { } // Called when a player is created/deleted virtual void OnCreate(Player* /*player*/) { } virtual void OnDelete(uint64 /*guid*/) { } // Called when a player is binded to an instance virtual void OnBindToInstance(Player* /*player*/, Difficulty /*difficulty*/, uint32 /*mapid*/, bool /*permanent*/) { } virtual void OnDamageDealt(Player* /*player*/, Unit* /*victim*/, uint32& /*damage*/, DamageEffectType /*damageType*/, SpellEntry const* /*spellProto*/) { } virtual void OnSpellCastWithProto(Player* /*player*/, SpellEntry const* /*spellProto*/) { } virtual void OnAura(Player* /*player*/, SpellEntry const* /*spellProto*/) { } }; class GuildScript: public ScriptObject { protected: GuildScript(const char* name); public: bool IsDatabaseBound() const { return false; } virtual void OnAddMember(Guild* /*guild*/, Player* /*player*/, uint8& /*plRank*/) { } virtual void OnRemoveMember(Guild* /*guild*/, Player* /*player*/, bool /*isDisbanding*/, bool /*isKicked*/) { } virtual void OnMOTDChanged(Guild* /*guild*/, const std::string& /*newMotd*/) { } virtual void OnInfoChanged(Guild* /*guild*/, const std::string& /*newInfo*/) { } virtual void OnCreate(Guild* /*guild*/, Player* /*leader*/, const std::string& /*name*/) { } virtual void OnDisband(Guild* /*guild*/) { } virtual void OnMemberWitdrawMoney(Guild* /*guild*/, Player* /*player*/, uint32& /*amount*/, bool /*isRepair*/) { } virtual void OnMemberDepositMoney(Guild* /*guild*/, Player* /*player*/, uint32& /*amount*/) { } virtual void OnItemMove(Guild* /*guild*/, Player* /*player*/, Item* /*pItem*/, bool /*isSrcBank*/, uint8 /*srcContainer*/, uint8 /*srcSlotId*/, bool /*isDestBank*/, uint8 /*destContainer*/, uint8 /*destSlotId*/) { } virtual void OnEvent(Guild* /*guild*/, uint8 /*eventType*/, uint32 /*playerGuid1*/, uint32 /*playerGuid2*/, uint8 /*newRank*/) { } virtual void OnBankEvent(Guild* /*guild*/, uint8 /*eventType*/, uint8 /*tabId*/, uint32 /*playerGuid*/, uint32 /*itemOrMoney*/, uint16 /*itemStackCount*/, uint8 /*destTabId*/) { } }; class GroupScript: public ScriptObject { protected: GroupScript(const char* name); public: bool IsDatabaseBound() const { return false; } virtual void OnAddMember(Group* /*group*/, uint64 /*guid*/) { } virtual void OnInviteMember(Group* /*group*/, uint64 /*guid*/) { } virtual void OnRemoveMember(Group* /*group*/, uint64 /*guid*/, RemoveMethod& /*method*/, uint64 /*kicker*/, const char* /*reason*/) { } virtual void OnChangeLeader(Group* /*group*/, uint64 /*newLeaderGuid*/, uint64 /*oldLeaderGuid*/) { } virtual void OnDisband(Group* /*group*/) { } }; // Placed here due to ScriptRegistry::AddScript dependency. #define sScriptMgr ACE_Singleton<ScriptMgr, ACE_Null_Mutex>::instance() // Manages registration, loading, and execution of scripts. class ScriptMgr { friend class ACE_Singleton<ScriptMgr, ACE_Null_Mutex> ; friend class ScriptObject; ScriptMgr(); virtual ~ScriptMgr(); uint32 _scriptCount; public: /* Initialization */ void Initialize(); void LoadDatabase(); void FillSpellSummary(); const char* ScriptsVersion() const { return "Integrated Trinity Scripts"; } void IncrementScriptCount() { ++_scriptCount; } uint32 GetScriptCount() const { return _scriptCount; } public: /* Unloading */ void Unload(); public: /* SpellScriptLoader */ void CreateSpellScripts(uint32 spell_id, std::list<SpellScript*>& script_vector); void CreateAuraScripts(uint32 spell_id, std::list<AuraScript*>& script_vector); void CreateSpellScriptLoaders( uint32 spell_id, std::vector< std::pair<SpellScriptLoader*, std::multimap<uint32, uint32>::iterator> >& script_vector); public: /* ServerScript */ void OnNetworkStart(); void OnNetworkStop(); void OnSocketOpen(WorldSocket* socket); void OnSocketClose(WorldSocket* socket, bool wasNew); void OnPacketReceive(WorldSocket* socket, WorldPacket packet); void OnPacketSend(WorldSocket* socket, WorldPacket packet); void OnUnknownPacketReceive(WorldSocket* socket, WorldPacket packet); public: /* WorldScript */ void OnOpenStateChange(bool open); void OnConfigLoad(bool reload); void OnMotdChange(std::string& newMotd); void OnShutdownInitiate(ShutdownExitCode code, ShutdownMask mask); void OnShutdownCancel(); void OnWorldUpdate(uint32 diff); void OnStartup(); void OnShutdown(); public: /* FormulaScript */ void OnHonorCalculation(float& honor, uint8 level, float multiplier); void OnGrayLevelCalculation(uint8& grayLevel, uint8 playerLevel); void OnColorCodeCalculation(XPColorChar& color, uint8 playerLevel, uint8 mobLevel); void OnZeroDifferenceCalculation(uint8& diff, uint8 playerLevel); void OnBaseGainCalculation(uint32& gain, uint8 playerLevel, uint8 mobLevel, ContentLevels content); void OnGainCalculation(uint32& gain, Player* player, Unit* unit); void OnGroupRateCalculation(float& rate, uint32 count, bool isRaid); public: /* MapScript */ void OnCreateMap(Map* map); void OnDestroyMap(Map* map); void OnLoadGridMap(Map* map, GridMap* gmap, uint32 gx, uint32 gy); void OnUnloadGridMap(Map* map, GridMap* gmap, uint32 gx, uint32 gy); void OnPlayerEnterMap(Map* map, Player* player); void OnPlayerLeaveMap(Map* map, Player* player); void OnMapUpdate(Map* map, uint32 diff); public: /* InstanceMapScript */ InstanceScript* CreateInstanceData(InstanceMap* map); public: /* ItemScript */ bool OnDummyEffect(Unit* caster, uint32 spellId, SpellEffIndex effIndex, Item* target); bool OnQuestAccept(Player* player, Item* item, Quest const* quest); bool OnItemUse(Player* player, Item* item, SpellCastTargets const& targets); bool OnItemExpire(Player* player, ItemPrototype const* proto); public: /* CreatureScript */ bool OnDummyEffect(Unit* caster, uint32 spellId, SpellEffIndex effIndex, Creature* target); bool OnGossipHello(Player* player, Creature* creature); bool OnGossipSelect(Player* player, Creature* creature, uint32 sender, uint32 action); bool OnGossipSelectCode(Player* player, Creature* creature, uint32 sender, uint32 action, const char* code); bool OnQuestAccept(Player* player, Creature* creature, Quest const* quest); bool OnQuestSelect(Player* player, Creature* creature, Quest const* quest); bool OnQuestComplete(Player* player, Creature* creature, Quest const* quest); bool OnQuestReward(Player* player, Creature* creature, Quest const* quest, uint32 opt); uint32 GetDialogStatus(Player* player, Creature* creature); CreatureAI* GetCreatureAI(Creature* creature); Creature* GetCreatureScriptedClass(uint32 scriptID); void OnCreatureUpdate(Creature* creature, uint32 diff); public: /* GameObjectScript */ bool OnDummyEffect(Unit* caster, uint32 spellId, SpellEffIndex effIndex, GameObject* target); bool OnGossipHello(Player* player, GameObject* go); bool OnGossipSelect(Player* player, GameObject* go, uint32 sender, uint32 action); bool OnGossipSelectCode(Player* player, GameObject* go, uint32 sender, uint32 action, const char* code); bool OnQuestAccept(Player* player, GameObject* go, Quest const* quest); bool OnQuestReward(Player* player, GameObject* go, Quest const* quest, uint32 opt); uint32 GetDialogStatus(Player* player, GameObject* go); void OnGameObjectDestroyed(Player* player, GameObject* go, uint32 eventId); void OnGameObjectDamaged(GameObject* go, Player* player); void OnGameObjectUpdate(GameObject* go, uint32 diff); public: /* AreaTriggerScript */ bool OnAreaTrigger(Player* player, AreaTriggerEntry const* trigger); public: /* BattlegroundScript */ Battleground* CreateBattleground(BattlegroundTypeId typeId); public: /* OutdoorPvPScript */ OutdoorPvP* CreateOutdoorPvP(OutdoorPvPData const* data); public: /* CommandScript */ std::vector<ChatCommand*> GetChatCommands(); public: /* WeatherScript */ void OnWeatherChange(Weather* weather, WeatherState state, float grade); void OnWeatherUpdate(Weather* weather, uint32 diff); public: /* AuctionHouseScript */ void OnAuctionAdd(AuctionHouseObject* ah, AuctionEntry* entry); void OnAuctionRemove(AuctionHouseObject* ah, AuctionEntry* entry); void OnAuctionSuccessful(AuctionHouseObject* ah, AuctionEntry* entry); void OnAuctionExpire(AuctionHouseObject* ah, AuctionEntry* entry); public: /* ConditionScript */ bool OnConditionCheck(Condition* condition, Player* player, Unit* invoker); public: /* VehicleScript */ void OnInstall(Vehicle* veh); void OnUninstall(Vehicle* veh); void OnDie(Vehicle* veh); void OnReset(Vehicle* veh); void OnInstallAccessory(Vehicle* veh, Creature* accessory); void OnAddPassenger(Vehicle* veh, Unit* passenger, int8 seatId); void OnRemovePassenger(Vehicle* veh, Unit* passenger); public: /* DynamicObjectScript */ void OnDynamicObjectUpdate(DynamicObject* dynobj, uint32 diff); public: /* TransportScript */ void OnAddPassenger(Transport* transport, Player* player); void OnAddCreaturePassenger(Transport* transport, Creature* creature); void OnRemovePassenger(Transport* transport, Player* player); void OnTransportUpdate(Transport* transport, uint32 diff); void OnRelocate(Transport* transport, uint32 waypointId, uint32 mapId, float x, float y, float z); public: /* AchievementCriteriaScript */ bool OnCriteriaCheck(AchievementCriteriaData const* data, Player* source, Unit* target); public: /* PlayerScript */ void OnPVPKill(Player *killer, Player *killed); void OnCreatureKill(Player *killer, Creature *killed); void OnPlayerKilledByCreature(Creature *killer, Player *killed); void OnPlayerLevelChanged(Player *player, uint8 newLevel); void OnPlayerFreeTalentPointsChanged(Player *player, uint32 newPoints); void OnPlayerTalentsReset(Player *player, bool no_cost); void OnPlayerMoneyChanged(Player *player, int32& amount); void OnGivePlayerXP(Player *player, uint32& amount, Unit *victim); void OnPlayerReputationChange(Player *player, uint32 factionID, int32& standing, bool incremental); void OnPlayerDuelRequest(Player* target, Player* challenger); void OnPlayerDuelStart(Player* player1, Player* player2); void OnPlayerDuelEnd(Player* winner, Player* looser, DuelCompleteType type); void OnPlayerChat(Player* player, uint32 type, uint32 lang, std::string msg); void OnPlayerChat(Player* player, uint32 type, uint32 lang, std::string msg, Player* receiver); void OnPlayerChat(Player* player, uint32 type, uint32 lang, std::string msg, Group* group); void OnPlayerChat(Player* player, uint32 type, uint32 lang, std::string msg, Guild* guild); void OnPlayerChat(Player* player, uint32 type, uint32 lang, std::string msg, Channel* channel); void OnPlayerEmote(Player* player, uint32 emote); void OnPlayerTextEmote(Player* player, uint32 text_emote, uint32 emoteNum, uint64 guid); void OnPlayerSpellCast(Player* player, Spell *spell, bool skipCheck); void OnPlayerLogin(Player* player); void OnPlayerLogout(Player* player); void OnPlayerCreate(Player* player); void OnPlayerDelete(uint64 guid); void OnPlayerBindToInstance(Player* player, Difficulty difficulty, uint32 mapid, bool permanent); void OnPlayerDamageDealt(Player* player, Unit* victim, uint32& damage, DamageEffectType damageType, SpellEntry const *spellProto); void OnPlayerSpellCastWithProto(Player* player, SpellEntry const *spellProto); void OnPlayerAura(Player* player, SpellEntry const* spellProto); public: /* GuildScript */ void OnGuildAddMember(Guild *guild, Player *player, uint8& plRank); void OnGuildRemoveMember(Guild *guild, Player *player, bool isDisbanding, bool isKicked); void OnGuildMOTDChanged(Guild *guild, const std::string& newMotd); void OnGuildInfoChanged(Guild *guild, const std::string& newInfo); void OnGuildCreate(Guild *guild, Player* leader, const std::string& name); void OnGuildDisband(Guild *guild); void OnGuildMemberWitdrawMoney(Guild* guild, Player* player, uint32 &amount, bool isRepair); void OnGuildMemberDepositMoney(Guild* guild, Player* player, uint32 &amount); void OnGuildItemMove(Guild* guild, Player* player, Item* pItem, bool isSrcBank, uint8 srcContainer, uint8 srcSlotId, bool isDestBank, uint8 destContainer, uint8 destSlotId); void OnGuildEvent(Guild* guild, uint8 eventType, uint32 playerGuid1, uint32 playerGuid2, uint8 newRank); void OnGuildBankEvent(Guild* guild, uint8 eventType, uint8 tabId, uint32 playerGuid, uint32 itemOrMoney, uint16 itemStackCount, uint8 destTabId); public: /* GroupScript */ void OnGroupAddMember(Group* group, uint64 guid); void OnGroupInviteMember(Group* group, uint64 guid); void OnGroupRemoveMember(Group* group, uint64 guid, RemoveMethod method, uint64 kicker, const char* reason); void OnGroupChangeLeader(Group* group, uint64 newLeaderGuid, uint64 oldLeaderGuid); void OnGroupDisband(Group* group); public: /* ScriptRegistry */ // This is the global static registry of scripts. template<class TScript> class ScriptRegistry { // Counter used for code-only scripts. static uint32 _scriptIdCounter; public: typedef std::map<uint32, TScript*> ScriptMap; typedef typename ScriptMap::iterator ScriptMapIterator; // The actual list of scripts. This will be accessed concurrently, so it must not be modified // after server startup. static ScriptMap ScriptPointerList; static void AddScript(TScript* const script) { ASSERT(script); // See if the script is using the same memory as another script. If this happens, it means that // someone forgot to allocate new memory for a script. for (ScriptMapIterator it = ScriptPointerList.begin(); it != ScriptPointerList.end(); ++it) { if (it->second == script) { sLog->outError( "Script '%s' has same memory pointer as '%s'.", script->GetName().c_str(), it->second->GetName().c_str()); return; } } if (script->IsDatabaseBound()) { // Get an ID for the script. An ID only exists if it's a script that is assigned in the database // through a script name (or similar). uint32 id = GetScriptId(script->GetName().c_str()); if (id) { // Try to find an existing script. bool existing = false; for (ScriptMapIterator it = ScriptPointerList.begin(); it != ScriptPointerList.end(); ++it) { // If the script names match... if (it->second->GetName() == script->GetName()) { // ... It exists. existing = true; break; } } // If the script isn't assigned -> assign it! if (!existing) { ScriptPointerList[id] = script; sScriptMgr->IncrementScriptCount(); } else { // If the script is already assigned -> delete it! sLog->outError( "Script '%s' already assigned with the same script name, so the script can't work.", script->GetName().c_str()); ASSERT(false); // Error that should be fixed ASAP. } } else { // The script uses a script name from database, but isn't assigned to anything. if (script->GetName().find("example") == std::string::npos && script->GetName().find("smart") == std::string::npos) sLog->outErrorDb( "Script named '%s' does not have a script name assigned in database.", script->GetName().c_str()); } } else { // We're dealing with a code-only script; just add it. ScriptPointerList[_scriptIdCounter++] = script; sScriptMgr->IncrementScriptCount(); } } // Gets a script by its ID (assigned by ObjectMgr). static TScript* GetScriptById(uint32 id) { ScriptMapIterator it = ScriptPointerList.find(id); if (it != ScriptPointerList.end()) return it->second; return NULL; } }; }; #endif
28.055152
116
0.716994
[ "object", "vector" ]
9ef0ca514e45750ac7ac3ac2deed51b1bd893906
7,043
h
C
dnn/src/naive/warp_perspective/opr_impl.h
WestCityInstitute/MegEngine
f91881ffdc051ab49314b1bd12c4a07a862dc9c6
[ "Apache-2.0" ]
2
2020-03-26T08:26:29.000Z
2020-06-01T14:41:38.000Z
dnn/src/naive/warp_perspective/opr_impl.h
ted51/MegEngine
f91881ffdc051ab49314b1bd12c4a07a862dc9c6
[ "Apache-2.0" ]
null
null
null
dnn/src/naive/warp_perspective/opr_impl.h
ted51/MegEngine
f91881ffdc051ab49314b1bd12c4a07a862dc9c6
[ "Apache-2.0" ]
1
2020-11-09T06:29:51.000Z
2020-11-09T06:29:51.000Z
/** * \file dnn/src/naive/warp_perspective/opr_impl.h * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2020 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #pragma once #include "megdnn/oprs.h" #include "src/common/utils.h" namespace megdnn { namespace naive { class WarpPerspectiveForwardImpl: public WarpPerspectiveForward { protected: using Format = Param::Format; template <typename ctype, typename mtype> struct KernParam { Format format; BorderMode bmode; float border_val; size_t n_src, n_mat, c, ih, iw, oh, ow; ctype *sptr, *dptr; mtype *mptr; int *midx_ptr; //!< can be null Workspace workspace; static KernParam from_tensors( Format format, BorderMode bmode, float border_val, _megdnn_tensor_in src, _megdnn_tensor_in mat, _megdnn_tensor_in mat_idx, _megdnn_tensor_out dst, _megdnn_workspace workspace) { KernParam ret; ret.format = format; ret.bmode = bmode; ret.border_val = border_val; ret.n_src = src.layout.shape[0]; if (mat_idx.raw_ptr) { megdnn_assert(mat_idx.layout.ndim == 1); ret.n_mat = mat_idx.layout.shape[0]; ret.midx_ptr = mat_idx.ptr<int>(); } else { megdnn_assert(mat_idx.layout.ndim == 0); ret.n_mat = ret.n_src; ret.midx_ptr = nullptr; } if (format == Format::NCHW) { ret.c = src.layout.shape[1]; ret.ih = src.layout.shape[2]; ret.iw = src.layout.shape[3]; ret.oh = dst.layout.shape[2]; ret.ow = dst.layout.shape[3]; } else if (format == Format::NHWC) { ret.c = src.layout.shape[3]; ret.ih = src.layout.shape[1]; ret.iw = src.layout.shape[2]; ret.oh = dst.layout.shape[1]; ret.ow = dst.layout.shape[2]; } else if (format == Format::NCHW4) { ret.c = src.layout.shape[1] * 4; ret.ih = src.layout.shape[2]; ret.iw = src.layout.shape[3]; ret.oh = dst.layout.shape[2]; ret.ow = dst.layout.shape[3]; } else { megdnn_assert(format == Format::NHWCD4); ret.c = src.layout.shape[2] * 4; ret.ih = src.layout.shape[1]; ret.iw = src.layout.shape[3]; ret.oh = dst.layout.shape[1]; ret.ow = dst.layout.shape[3]; } if (src.layout.dtype.enumv() == DTypeEnum::Float32 || MEGDNN_FLOAT16_SELECT( src.layout.dtype.enumv() == DTypeEnum::Float16, false) || src.layout.dtype.enumv() == DTypeEnum::Int8 || src.layout.dtype.enumv() == DTypeEnum::Uint8 || src.layout.dtype.enumv() == DTypeEnum::QuantizedS8 || src.layout.dtype.enumv() == DTypeEnum::Quantized8Asymm) { ret.sptr = src.compatible_ptr<ctype>(); ret.mptr = mat.ptr<mtype>(); ret.dptr = dst.compatible_ptr<ctype>(); } else if (src.layout.dtype.enumv() == DTypeEnum::QuantizedS8) { ret.sptr = src.compatible_ptr<ctype>(); ret.mptr = mat.ptr<mtype>(); ret.dptr = dst.compatible_ptr<ctype>(); } else { ret.sptr = nullptr; ret.mptr = nullptr; ret.dptr = nullptr; } ret.workspace = workspace; return ret; } }; // ctype: C type of input data type. // mtype: C type of transformation matrix data type. template <typename ctype, typename mtype> void kern_naive(const KernParam<ctype, mtype>& kern_param, size_t task_id); public: using WarpPerspectiveForward::WarpPerspectiveForward; void exec(_megdnn_tensor_in src, _megdnn_tensor_in mat, _megdnn_tensor_in mat_idx, _megdnn_tensor_out dst, _megdnn_workspace workspace) override; size_t get_workspace_in_bytes(const TensorLayout&, const TensorLayout&, const TensorLayout&, const TensorLayout&) override { return 0; } private: template <typename ctype, typename mtype> void kern_naive_nhwcd4(const KernParam<ctype, mtype>& kern_param, size_t task_id); }; class WarpPerspectiveBackwardDataImpl : public WarpPerspectiveBackwardData { public: using WarpPerspectiveBackwardData::WarpPerspectiveBackwardData; void exec(_megdnn_tensor_in mat, _megdnn_tensor_in diff, _megdnn_tensor_out grad, _megdnn_workspace workspace) override; size_t get_workspace_in_bytes(const TensorLayout&, const TensorLayout&, const TensorLayout&) override { return 0; } }; class WarpPerspectiveBackwardMatImpl : public WarpPerspectiveBackwardMat { public: using WarpPerspectiveBackwardMat::WarpPerspectiveBackwardMat; void exec(_megdnn_tensor_in src, _megdnn_tensor_in mat, _megdnn_tensor_in diff, _megdnn_tensor_out grad, _megdnn_workspace workspace) override; size_t get_workspace_in_bytes(const TensorLayout&, const TensorLayout&, const TensorLayout&, const TensorLayout&) override { return 0; } }; #define UNPACK_WARP_PERSPECTIVE_FWD_KERN_PARAM(p) \ auto N_SRC = p.n_src, N_MAT = p.n_mat, C = p.c, IH = p.ih, IW = p.iw, \ OH = p.oh, OW = p.ow; \ ctype* __restrict sptr = p.sptr; \ mtype* __restrict mptr = p.mptr; \ ctype* __restrict dptr = p.dptr; \ int* __restrict midx_ptr = p.midx_ptr; \ auto bmode = p.bmode; \ float border_val = p.border_val } // namespace naive } // namespace megdnn // vim: syntax=cpp.doxygen
43.208589
89
0.517961
[ "shape" ]
9ef4ac71ac4419c13fc140b60e2802d302977081
2,696
h
C
server-src/taper-disk-port-source.h
nicksmith/amanda
570c25dde62fed3f17b8e62b83504a5504f2febd
[ "BSD-4-Clause-UC" ]
1
2016-05-09T11:24:01.000Z
2016-05-09T11:24:01.000Z
server-src/taper-disk-port-source.h
nicksmith/amanda
570c25dde62fed3f17b8e62b83504a5504f2febd
[ "BSD-4-Clause-UC" ]
null
null
null
server-src/taper-disk-port-source.h
nicksmith/amanda
570c25dde62fed3f17b8e62b83504a5504f2febd
[ "BSD-4-Clause-UC" ]
null
null
null
/* * Amanda, The Advanced Maryland Automatic Network Disk Archiver * Copyright (c) 2005-2008 Zmanda Inc. * * 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 */ /* The taper disk port source is a taper source (see taper-source.h) used for the case where we are reading directly from a client (PORT-WRITE) and are using a disk buffer to hold split dump parts. */ #include <glib.h> #include <glib-object.h> #include "taper-port-source.h" #ifndef __TAPER_DISK_PORT_SOURCE_H__ #define __TAPER_DISK_PORT_SOURCE_H__ /* * Type checking and casting macros */ #define TAPER_TYPE_DISK_PORT_SOURCE (taper_disk_port_source_get_type()) #define TAPER_DISK_PORT_SOURCE(obj) G_TYPE_CHECK_INSTANCE_CAST((obj), taper_disk_port_source_get_type(), TaperDiskPortSource) #define TAPER_DISK_PORT_SOURCE_CONST(obj) G_TYPE_CHECK_INSTANCE_CAST((obj), taper_disk_port_source_get_type(), TaperDiskPortSource const) #define TAPER_DISK_PORT_SOURCE_CLASS(klass) G_TYPE_CHECK_CLASS_CAST((klass), taper_disk_port_source_get_type(), TaperDiskPortSourceClass) #define TAPER_IS_DISK_PORT_SOURCE(obj) G_TYPE_CHECK_INSTANCE_TYPE((obj), taper_disk_port_source_get_type ()) #define TAPER_DISK_PORT_SOURCE_GET_CLASS(obj) G_TYPE_INSTANCE_GET_CLASS((obj), taper_disk_port_source_get_type(), TaperDiskPortSourceClass) /* Private structure type */ typedef struct _TaperDiskPortSourcePrivate TaperDiskPortSourcePrivate; /* * Main object structure */ #ifndef __TYPEDEF_TAPER_DISK_PORT_SOURCE__ #define __TYPEDEF_TAPER_DISK_PORT_SOURCE__ typedef struct _TaperDiskPortSource TaperDiskPortSource; #endif struct _TaperDiskPortSource { TaperPortSource __parent__; /*< private >*/ guint64 fallback_buffer_size; char * buffer_dir_name; TaperDiskPortSourcePrivate *_priv; }; /* * Class definition */ typedef struct _TaperDiskPortSourceClass TaperDiskPortSourceClass; struct _TaperDiskPortSourceClass { TaperPortSourceClass __parent__; }; /* * Public methods */ GType taper_disk_port_source_get_type (void); #endif
35.473684
139
0.796365
[ "object" ]
9ef54518de83bb1c4d3923156653628246f91be3
3,341
h
C
libtensor/symmetry/product_table_i.h
pjknowles/libtensor
f18e0e33c6c4512e4ea1dde31ed8d74fe536ed24
[ "BSL-1.0" ]
33
2016-02-08T06:05:17.000Z
2021-11-17T01:23:11.000Z
libtensor/symmetry/product_table_i.h
pjknowles/libtensor
f18e0e33c6c4512e4ea1dde31ed8d74fe536ed24
[ "BSL-1.0" ]
5
2016-06-14T15:54:11.000Z
2020-12-07T08:27:20.000Z
libtensor/symmetry/product_table_i.h
pjknowles/libtensor
f18e0e33c6c4512e4ea1dde31ed8d74fe536ed24
[ "BSL-1.0" ]
12
2016-05-19T18:09:38.000Z
2021-02-24T17:35:21.000Z
#ifndef LIBTENSOR_PRODUCT_TABLE_I_H #define LIBTENSOR_PRODUCT_TABLE_I_H #include <set> #include <string> #include <vector> #include "bad_symmetry.h" namespace libtensor { /** \brief Interface for product tables This class defines the interface for a product table of a finite set of labels. The provided functions to access the product table enforce that the table is symmetric. Additionally, two special labels are defined as constants: the identity label (0) and an invalid label ((size_t) -1). The identity label is the label for which the product with any other label l yields only l as result. Any class implementing this interface needs to implement - clone() -- Create an identical copy - get_id() -- Return the unique ID of the current table - is_valid() -- Check if the given label is valid - get_n_labels() -- Return the total number of labels - determine_product() -- Compute the product of two labels - do_check() -- Perform additional checks \ingroup libtensor_symmetry **/ class product_table_i { public: typedef size_t label_t; //!< Label type typedef std::set<label_t> label_set_t; //!< Set of unique labels typedef std::vector<label_t> label_group_t; //!< Group of labels static const char *k_clazz; //!< Class name static const label_t k_invalid; //!< Invalid label static const label_t k_identity; //!< Identity label public: //! \name Constructors / destructors //@{ /** \brief Virtual destructor **/ virtual ~product_table_i() { } /** \brief Creates an identical copy of the product table. **/ virtual product_table_i *clone() const = 0; //@} /** \brief Returns the id identifying the product table. **/ virtual const std::string &get_id() const = 0; /** \brief Returns true if label is valid \param l Label to check **/ virtual bool is_valid(label_t l) const = 0; /** \brief Returns the number of valid labels (which is the smallest label not valid). **/ virtual label_t get_n_labels() const = 0; /** \brief Computes the product of a label group \param lg Label group. \param[out] prod Computed product. The result is the product of all n labels in the group \f$ l_1 \times l_2 \times ... \times l_n \f$ **/ virtual void product(const label_group_t &lg, label_set_t &prod) const = 0; /** \brief Determines if the label is in the product. \param lg Group of labels to take the product of. \param l Label to check against. \return True if label is in the product, else false. **/ virtual bool is_in_product(const label_group_t &lg, label_t l) const = 0; /** \brief Does a consistency check on the table. \throw exception If product table is not set up properly. Checks that the product of any label with the identity label yields the respective label and that all products yield a non-empty set. **/ void check() const throw(bad_symmetry); protected: /** \brief Perform additional consistency check This function is called by \c check() to perform additional checks for the child classes. **/ virtual void do_check() const = 0; }; } #endif // LIBTENSOR_PRODUCT_TABLE_I_H
31.819048
79
0.671955
[ "vector" ]
9ef585d170ce8990f2afdc7e26e4eb3559a662f5
8,392
h
C
include/blaze/blaze/math/lapack/syev.h
mattheww95/sketch
2dc43bc1303823cc726c19d2550c1ca450182298
[ "MIT" ]
104
2018-12-13T11:20:16.000Z
2022-02-11T21:01:02.000Z
include/blaze/blaze/math/lapack/syev.h
mattheww95/sketch
2dc43bc1303823cc726c19d2550c1ca450182298
[ "MIT" ]
16
2019-02-05T05:58:14.000Z
2022-03-09T16:35:12.000Z
include/blaze/blaze/math/lapack/syev.h
mattheww95/sketch
2dc43bc1303823cc726c19d2550c1ca450182298
[ "MIT" ]
10
2019-11-11T14:57:12.000Z
2022-03-07T22:40:00.000Z
//================================================================================================= /*! // \file blaze/math/lapack/syev.h // \brief Header file for the LAPACK symmetric matrix eigenvalue functions (syev) // // Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. 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 names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= #ifndef _BLAZE_MATH_LAPACK_SYEV_H_ #define _BLAZE_MATH_LAPACK_SYEV_H_ //************************************************************************************************* // Includes //************************************************************************************************* #include <memory> #include <blaze/math/Aliases.h> #include <blaze/math/constraints/Adaptor.h> #include <blaze/math/constraints/BLASCompatible.h> #include <blaze/math/constraints/Computation.h> #include <blaze/math/constraints/Contiguous.h> #include <blaze/math/constraints/MutableDataAccess.h> #include <blaze/math/Exception.h> #include <blaze/math/expressions/DenseMatrix.h> #include <blaze/math/expressions/DenseVector.h> #include <blaze/math/lapack/clapack/syev.h> #include <blaze/math/typetraits/IsRowMajorMatrix.h> #include <blaze/util/Assert.h> #include <blaze/util/constraints/Builtin.h> #include <blaze/util/NumericCast.h> namespace blaze { //================================================================================================= // // LAPACK SYMMETRIC MATRIX EIGENVALUE FUNCTIONS (SYEV) // //================================================================================================= //************************************************************************************************* /*!\name LAPACK symmetric matrix eigenvalue functions (syev) */ //@{ template< typename MT, bool SO, typename VT, bool TF > void syev( DenseMatrix<MT,SO>& A, DenseVector<VT,TF>& w, char jobz, char uplo ); //@} //************************************************************************************************* //************************************************************************************************* /*!\brief LAPACK kernel for computing the eigenvalues of the given dense symmetric matrix. // \ingroup lapack_eigenvalue // // \param A The given symmetric matrix. // \param w The resulting vector of eigenvalues. // \param jobz \c 'V' to compute the eigenvectors of \a A, \c 'N' to only compute the eigenvalues. // \param uplo \c 'L' to use the lower part of the matrix, \c 'U' to use the upper part. // \return void // \exception std::invalid_argument Invalid non-square matrix provided. // \exception std::invalid_argument Vector cannot be resized. // \exception std::invalid_argument Invalid jobz argument provided. // \exception std::invalid_argument Invalid uplo argument provided. // \exception std::runtime_error Eigenvalue computation failed. // // This function computes the eigenvalues of a symmetric \a n-by-\a n matrix based on the LAPACK // syev() functions. Optionally, it computes the left or right eigenvectors. // // The real eigenvalues are returned in ascending order in the given vector \a w. \a w is resized // to the correct size (if possible and necessary). In case \a A is a row-major matrix, the left // eigenvectors are returned in the rows of \a A, in case \a A is a column-major matrix, the right // eigenvectors are returned in the columns of \a A. // // The function fails if ... // // - ... the given matrix \a A is not a square matrix; // - ... the given vector \a w is a fixed size vector and the size doesn't match; // - ... the given \a jobz argument is neither \c 'V' nor \c 'N'; // - ... the given \a uplo argument is neither \c 'L' nor \c 'U'; // - ... the eigenvalue computation fails. // // In all failure cases a \a std::invalid_argument exception is thrown. // // Examples: \code using blaze::DynamicMatrix; using blaze::DynamicVector; using blaze::rowMajor; using blaze::columnVector; DynamicMatrix<double,rowMajor> A( 5UL, 5UL ); // The symmetric matrix A // ... Initialization DynamicVector<double,columnVector> w( 5UL ); // The vector for the real eigenvalues syev( A, w, 'V', 'L' ); \endcode // For more information on the syev() functions (i.e. ssyev() and dsyev()) see the LAPACK online // documentation browser: // // http://www.netlib.org/lapack/explore-html/ // // \note This function can only be used if a fitting LAPACK library, which supports this function, // is available and linked to the executable. Otherwise a call to this function will result in a // linker error. */ template< typename MT // Type of the matrix A , bool SO // Storage order of the matrix A , typename VT // Type of the vector w , bool TF > // Transpose flag of the vector w inline void syev( DenseMatrix<MT,SO>& A, DenseVector<VT,TF>& w, char jobz, char uplo ) { BLAZE_CONSTRAINT_MUST_NOT_BE_ADAPTOR_TYPE( MT ); BLAZE_CONSTRAINT_MUST_NOT_BE_COMPUTATION_TYPE( MT ); BLAZE_CONSTRAINT_MUST_HAVE_MUTABLE_DATA_ACCESS( MT ); BLAZE_CONSTRAINT_MUST_BE_CONTIGUOUS_TYPE( MT ); BLAZE_CONSTRAINT_MUST_BE_BLAS_COMPATIBLE_TYPE( ElementType_t<MT> ); BLAZE_CONSTRAINT_MUST_BE_BUILTIN_TYPE( ElementType_t<MT> ); BLAZE_CONSTRAINT_MUST_NOT_BE_COMPUTATION_TYPE( VT ); BLAZE_CONSTRAINT_MUST_HAVE_MUTABLE_DATA_ACCESS( VT ); BLAZE_CONSTRAINT_MUST_BE_CONTIGUOUS_TYPE( VT ); BLAZE_CONSTRAINT_MUST_BE_BLAS_COMPATIBLE_TYPE( ElementType_t<VT> ); BLAZE_CONSTRAINT_MUST_BE_BUILTIN_TYPE( ElementType_t<VT> ); using ET = ElementType_t<MT>; if( !isSquare( *A ) ) { BLAZE_THROW_INVALID_ARGUMENT( "Invalid non-square matrix provided" ); } if( jobz != 'V' && jobz != 'N' ) { BLAZE_THROW_INVALID_ARGUMENT( "Invalid jobz argument provided" ); } if( uplo != 'L' && uplo != 'U' ) { BLAZE_THROW_INVALID_ARGUMENT( "Invalid uplo argument provided" ); } resize( *w, (*A).rows(), false ); blas_int_t n ( numeric_cast<blas_int_t>( (*A).rows() ) ); blas_int_t lda ( numeric_cast<blas_int_t>( (*A).spacing() ) ); blas_int_t info( 0 ); if( n == 0 ) { return; } blas_int_t lwork( 10*n + 2 ); const std::unique_ptr<ET[]> work( new ET[lwork] ); if( IsRowMajorMatrix_v<MT> ) { ( uplo == 'L' )?( uplo = 'U' ):( uplo = 'L' ); } syev( jobz, uplo, n, (*A).data(), lda, (*w).data(), work.get(), lwork, &info ); BLAZE_INTERNAL_ASSERT( info >= 0, "Invalid argument for eigenvalue computation" ); if( info > 0 ) { BLAZE_THROW_LAPACK_ERROR( "Eigenvalue computation failed" ); } } //************************************************************************************************* } // namespace blaze #endif
42.383838
99
0.630601
[ "vector" ]
9ef58e15195764a0c8c75019b45dbe569719ebb9
575
h
C
HHExtend/HHExtend/Main/Classes/Mine/View/MineTestCell.h
YYDreams/HHToolCategory
6eff6a3bb8441841816830c0ba8d813c79a2a438
[ "Apache-2.0" ]
1
2019-11-02T11:19:29.000Z
2019-11-02T11:19:29.000Z
HHExtend/HHExtend/Main/Classes/Mine/View/MineTestCell.h
YYDreams/HHToolCategory
6eff6a3bb8441841816830c0ba8d813c79a2a438
[ "Apache-2.0" ]
null
null
null
HHExtend/HHExtend/Main/Classes/Mine/View/MineTestCell.h
YYDreams/HHToolCategory
6eff6a3bb8441841816830c0ba8d813c79a2a438
[ "Apache-2.0" ]
null
null
null
// // MineTestCell.h // HHExtend // // Created by flowerflower on 2018/4/11. // Copyright © 2018年 花花. All rights reserved. // #import "BaseCell.h" #import "MineTestModel.h" @interface MineTestCell : BaseCell @property(nonatomic,strong) UILabel *titleLabel; // <#注释#> @property(nonatomic,strong) UIButton *minBtn; // <#注释#> @property(nonatomic,strong) UILabel *countLabel; // <#注释#> @property(nonatomic,strong) UIButton *addBtn; // <#注释#> @property(nonatomic,strong) MineTestModel *model; // <#注释#> @property(nonatomic,assign) int count; // <#注释#> @end
19.166667
60
0.676522
[ "model" ]
9ef6b77b696f184a97e631ed7b011be942b74ec0
803
h
C
Source/hittable.h
Idhrendur/RayTracingInSeveralWeekends
76d6d7ff8589729635b2c99cd1ec19217136a5b7
[ "MIT" ]
null
null
null
Source/hittable.h
Idhrendur/RayTracingInSeveralWeekends
76d6d7ff8589729635b2c99cd1ec19217136a5b7
[ "MIT" ]
null
null
null
Source/hittable.h
Idhrendur/RayTracingInSeveralWeekends
76d6d7ff8589729635b2c99cd1ec19217136a5b7
[ "MIT" ]
null
null
null
#ifndef HITTABLE_H #define HITTABLE_H #include "ray.h" #include "vector.h" #include <optional> namespace RayTracer { struct HitRecord { Vector point; Vector normal; float t = 0.0F; bool frontFace = true; void setFaceNormal(const Ray& ray, const Vector& outwardNormal) { frontFace = ray.direction().dot(outwardNormal) < 0; normal = frontFace ? outwardNormal : -outwardNormal; } }; class Hittable { public: Hittable() = default; Hittable(const Hittable&) = default; Hittable(Hittable&&) = default; Hittable& operator=(const Hittable&) = default; Hittable& operator=(Hittable&&) = default; virtual ~Hittable() = default; [[nodiscard]] virtual std::optional<HitRecord> hit(const Ray& ray, float tMin, float tMax) const = 0; }; } // namespace RayTracer #endif // HITTABLE_H
17.085106
102
0.704857
[ "vector" ]
9ef9736fd6be7bb9f7ae3a27975107bda430c605
3,532
h
C
TSGE.h
mahtandakil/AGE
66ee620aa776a5bf784153c709ec24aeef4d1a3b
[ "libtiff", "Libpng", "BSD-3-Clause" ]
1
2018-08-07T15:53:09.000Z
2018-08-07T15:53:09.000Z
TSGE.h
mahtandakil/TSGE
66ee620aa776a5bf784153c709ec24aeef4d1a3b
[ "libtiff", "Libpng", "BSD-3-Clause" ]
null
null
null
TSGE.h
mahtandakil/TSGE
66ee620aa776a5bf784153c709ec24aeef4d1a3b
[ "libtiff", "Libpng", "BSD-3-Clause" ]
null
null
null
/**************************************************************************** * Created for: AGE v1 * Dev line: TSGE v2 * Creation day: 17/07/2015 * Last change: 09/02/2017 ****************************************************************************/ #include "TSGE_definitions.h" #include "TSGE_util.h" #include "dmo/DMOM.h" #include <iostream> using namespace std; #ifndef TSGE_H_INCLUDED #define TSGE_H_INCLUDED //--------------------------------------------------------------------------- class TSGE { public: TSGE(); virtual ~TSGE(); bool tsge_collision_check(TSGE_Cartesian area1, TSGE_Cartesian area2); bool tsge_core_load_libs(); DMOM* tsge_dmom_get(); int tsge_draw_area_create(TSGE_Cartesian coords, bool solid, int window_id = 0); TSGE_Event_Status tsge_event_get_status(); int tsge_event_process(); int tsge_font_delete(int font_id); int tsge_font_deploy(string src, int font_size); int tsge_font_free(int font_id); int tsge_image_delete(int image_id); int tsge_image_deploy(string src, int window_id = 0); int tsge_image_deploy(string src, int x, int y, int window_id = 0); int tsge_image_free(int image_id); int tsge_image_move(int image_id, int x, int y, int window_id = 0); int tsge_image_move_to_draw_area(int image_id, int draw_area_id, int x, int y); TSGE_Cartesian tsge_image_size_get(int image_id); int tsge_image_tag_set(int image_id, string tag); int tsge_label_compose(string text, int font_id, TSGE_Color color, Uint8 mode = TSGE_LABELMODEFLAG_SOLID, TSGE_Color bg_color = {0,0,0,0}); int tsge_line_draw(TSGE_Cartesian point1, TSGE_Cartesian point2, TSGE_Color color, SDL_BlendMode blend_mode = TSGE_BLENDINGFLAG_BLEND, int window_id = 0); void tsge_pause(int miliseconds); int tsge_square_draw(TSGE_Cartesian square, TSGE_Color color, SDL_BlendMode blend_mode = TSGE_BLENDINGFLAG_BLEND, int window_id = 0); TSGE_Cartesian tsge_window_cartesian_get(int window_id = 0); int tsge_window_cartesian_set(TSGE_Cartesian cartesian, int window_id = 0); int tsge_window_clear(int window_id = 0, TSGE_Color color = {0,0,0,255}); int tsge_window_create(string title, TSGE_Cartesian coords, Uint32 wflags = 0, Uint32 rflags = 0); int tsge_window_fading(Uint8 alpha, int window_id = 0, TSGE_Color color = {0,0,0,255}); int tsge_window_position_set(TSGE_Cartesian position, int window_id = 0); int tsge_window_refresh(); int tsge_window_refresh(int window_id); int tsge_window_remove(int window_id); int tsge_window_set_focus(int window_id); int tsge_window_set_visible(int window_id, bool visible); int tsge_window_size_set(TSGE_Cartesian size, int window_id = 0); private: DMOM* dmom; TSGE_DrawAreaIndex* draw_area_index; TSGE_EventIndex* event_index; TSGE_FontIndex* font_index; TSGE_ImageIndex* image_index; SDL_Event sdl_event_handler; TSGE_WindowIndex* window_index; int tsge_font_unload(int font_id); int tsge_image_unload(int image_id); SDL_Surface* tsge_sdlttf_create_surface(string text, TTF_Font* font, TSGE_Color color, Uint8 mode, TSGE_Color bg_color); SDL_Texture* tsge_sdlttf_create_texture(SDL_Surface* temp_surface, SDL_Renderer* render = nullptr); bool tsge_sdltexture_apply(SDL_Texture* texture, SDL_Renderer* render, int x, int y, int w, int h); bool tsge_sdltexture_apply(SDL_Texture* texture, SDL_Renderer* render, int img_x, int img_y, int img_w, int img_h, int dst_x, int dst_y, int dst_w, int dst_h); }; //--------------------------------------------------------------------------- #endif // TSGE_H_INCLUDED
40.136364
160
0.716874
[ "render", "solid" ]
9efbafcef41c45fd3ca0f321cbb648e586698ae7
5,042
h
C
include/llvm/Analysis/ProfileDataLoader.h
nettrino/IntFlow
0400aef5da2c154268d8b020e393c950435395b3
[ "Unlicense" ]
16
2015-09-08T08:49:11.000Z
2019-07-20T14:46:20.000Z
include/llvm/Analysis/ProfileDataLoader.h
nettrino/IntFlow
0400aef5da2c154268d8b020e393c950435395b3
[ "Unlicense" ]
1
2019-02-10T08:27:48.000Z
2019-02-10T08:27:48.000Z
include/llvm/Analysis/ProfileDataLoader.h
nettrino/IntFlow
0400aef5da2c154268d8b020e393c950435395b3
[ "Unlicense" ]
7
2016-05-26T17:31:46.000Z
2020-11-04T06:39:23.000Z
//===- ProfileDataLoader.h - Load & convert profile info ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // The ProfileDataLoader class is used to load profiling data from a dump file. // The ProfileDataT<FType, BType> class is used to store the mapping of this // data to control flow edges. // //===----------------------------------------------------------------------===// #ifndef LLVM_ANALYSIS_PROFILEDATALOADER_H #define LLVM_ANALYSIS_PROFILEDATALOADER_H #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include <string> namespace llvm { class ModulePass; class Function; class BasicBlock; // Helper for dumping edges to dbgs(). raw_ostream& operator<<(raw_ostream &O, std::pair<const BasicBlock *, const BasicBlock *> E); /// \brief The ProfileDataT<FType, BType> class is used to store the mapping of /// profiling data to control flow edges. /// /// An edge is defined by its source and sink basic blocks. template<class FType, class BType> class ProfileDataT { public: // The profiling information defines an Edge by its source and sink basic // blocks. typedef std::pair<const BType*, const BType*> Edge; private: typedef DenseMap<Edge, unsigned> EdgeWeights; /// \brief Count the number of times a transition between two blocks is /// executed. /// /// As a special case, we also hold an edge from the null BasicBlock to the /// entry block to indicate how many times the function was entered. DenseMap<const FType*, EdgeWeights> EdgeInformation; public: /// getFunction() - Returns the Function for an Edge. static const FType *getFunction(Edge e) { // e.first may be NULL assert(((!e.first) || (e.first->getParent() == e.second->getParent())) && "A ProfileData::Edge can not be between two functions"); assert(e.second && "A ProfileData::Edge must have a real sink"); return e.second->getParent(); } /// getEdge() - Creates an Edge between two BasicBlocks. static Edge getEdge(const BType *Src, const BType *Dest) { return Edge(Src, Dest); } /// getEdgeWeight - Return the number of times that a given edge was /// executed. unsigned getEdgeWeight(Edge e) const { const FType *f = getFunction(e); assert((EdgeInformation.find(f) != EdgeInformation.end()) && "No profiling information for function"); EdgeWeights weights = EdgeInformation.find(f)->second; assert((weights.find(e) != weights.end()) && "No profiling information for edge"); return weights.find(e)->second; } /// addEdgeWeight - Add 'weight' to the already stored execution count for /// this edge. void addEdgeWeight(Edge e, unsigned weight) { EdgeInformation[getFunction(e)][e] += weight; } }; typedef ProfileDataT<Function, BasicBlock> ProfileData; //typedef ProfileDataT<MachineFunction, MachineBasicBlock> MachineProfileData; /// The ProfileDataLoader class is used to load raw profiling data from the /// dump file. class ProfileDataLoader { private: /// The name of the file where the raw profiling data is stored. const std::string &Filename; /// A vector of the command line arguments used when the target program was /// run to generate profiling data. One entry per program run. SmallVector<std::string, 1> CommandLines; /// The raw values for how many times each edge was traversed, values from /// multiple program runs are accumulated. SmallVector<unsigned, 32> EdgeCounts; public: /// ProfileDataLoader ctor - Read the specified profiling data file, exiting /// the program if the file is invalid or broken. ProfileDataLoader(const char *ToolName, const std::string &Filename); /// A special value used to represent the weight of an edge which has not /// been counted yet. static const unsigned Uncounted; /// getNumExecutions - Return the number of times the target program was run /// to generate this profiling data. unsigned getNumExecutions() const { return CommandLines.size(); } /// getExecution - Return the command line parameters used to generate the /// i'th set of profiling data. const std::string &getExecution(unsigned i) const { return CommandLines[i]; } const std::string &getFileName() const { return Filename; } /// getRawEdgeCounts - Return the raw profiling data, this is just a list of /// numbers with no mappings to edges. ArrayRef<unsigned> getRawEdgeCounts() const { return EdgeCounts; } }; /// createProfileMetadataLoaderPass - This function returns a Pass that loads /// the profiling information for the module from the specified filename. ModulePass *createProfileMetadataLoaderPass(const std::string &Filename); } // End llvm namespace #endif
36.014286
80
0.687624
[ "vector" ]
9ae30195a7a3702b4b2e5cc5b164e62bb08de5ed
2,286
h
C
ios/Pods/EstimoteSDK/EstimoteSDK/EstimoteSDK.framework/Versions/A/Headers/ESTSettingIBeaconSecureUUIDEnable.h
Chickoff867/TheWarholOutLoud
999ed9be61b447d562fc760bfd4d02c8fefafa43
[ "MIT" ]
92
2016-08-17T18:09:57.000Z
2021-09-06T19:01:53.000Z
ios/Pods/EstimoteSDK/EstimoteSDK/EstimoteSDK.framework/Versions/A/Headers/ESTSettingIBeaconSecureUUIDEnable.h
Chickoff867/TheWarholOutLoud
999ed9be61b447d562fc760bfd4d02c8fefafa43
[ "MIT" ]
1
2017-05-03T20:42:17.000Z
2017-06-13T02:13:05.000Z
ios/Pods/EstimoteSDK/EstimoteSDK/EstimoteSDK.framework/Versions/A/Headers/ESTSettingIBeaconSecureUUIDEnable.h
Chickoff867/TheWarholOutLoud
999ed9be61b447d562fc760bfd4d02c8fefafa43
[ "MIT" ]
15
2016-10-25T14:05:33.000Z
2019-07-16T19:06:23.000Z
// // ______ _ _ _ _____ _____ _ __ // | ____| | | (_) | | / ____| __ \| |/ / // | |__ ___| |_ _ _ __ ___ ___ | |_ ___ | (___ | | | | ' / // | __| / __| __| | '_ ` _ \ / _ \| __/ _ \ \___ \| | | | < // | |____\__ \ |_| | | | | | | (_) | || __/ ____) | |__| | . \ // |______|___/\__|_|_| |_| |_|\___/ \__\___| |_____/|_____/|_|\_\ // // // Copyright (c) 2015 Estimote. All rights reserved. #import <Foundation/Foundation.h> #import "ESTSettingReadWrite.h" @class ESTSettingIBeaconSecureUUIDEnable; NS_ASSUME_NONNULL_BEGIN /** * Block used as a result of read/write setting SecureUUIDEnable operation for iBeacon packet. * * @param enabled SecureUUIDEnable setting carrying value. * @param error Operation error. No error means success. */ typedef void(^ESTSettingIBeaconSecureUUIDEnableCompletionBlock)(ESTSettingIBeaconSecureUUIDEnable * _Nullable enabledSetting, NSError * _Nullable error); /** * ESTSettingIBeaconSecureUUIDEnable represents iBeacon SecureUUIDEnable value. */ @interface ESTSettingIBeaconSecureUUIDEnable : ESTSettingReadWrite <NSCopying> /** * Designated initializer. * * @param enabled iBeacon SecureUUIDEnable value. * * @return Initialized object. */ - (instancetype)initWithValue:(BOOL)enabled; /** * Returns current value of iBeacon SecureUUIDEnable setting. * * @return iBeacon SecureUUIDEnable value. */ - (BOOL)getValue; /** * Method allows to read value of initialized iBeacon SecureUUIDEnable setting object. * * @param completion Block to be invoked when operation is complete. * * @return Initialized operation object. */ - (void)readValueWithCompletion:(ESTSettingIBeaconSecureUUIDEnableCompletionBlock)completion; /** * Method allows to create write operation from already initialized iBeacon SecureUUIDEnable setting object. * Value provided during initialization will be used as a desired value. * * @param enabled SecureUUIDEnable value to be written to the device. * @param completion Block to be invoked when operation is complete. * * @return Initialized operation object. */ - (void)writeValue:(BOOL)enabled completion:(ESTSettingIBeaconSecureUUIDEnableCompletionBlock)completion; @end NS_ASSUME_NONNULL_END
31.75
153
0.694663
[ "object" ]
9ae7db81adba75f7eabc55b85c473b66111db720
16,222
h
C
bin/tcpdump/decnet.h
aaliomer/exos
6a37c41cad910c373322441a9f23cfabdbfae275
[ "BSD-3-Clause" ]
1
2018-01-23T23:07:19.000Z
2018-01-23T23:07:19.000Z
bin/tcpdump/decnet.h
aaliomer/exos
6a37c41cad910c373322441a9f23cfabdbfae275
[ "BSD-3-Clause" ]
null
null
null
bin/tcpdump/decnet.h
aaliomer/exos
6a37c41cad910c373322441a9f23cfabdbfae275
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 1992, 1994, 1996 * 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: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the University of California, * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of * the University nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior * written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * */ typedef unsigned char byte[1]; /* single byte field */ typedef unsigned char word[2]; /* 2 byte field */ typedef unsigned char longword[4]; /* 4 bytes field */ /* * Definitions for DECNET Phase IV protocol headers */ union etheraddress { unsigned char dne_addr[6]; /* full ethernet address */ struct { unsigned char dne_hiord[4]; /* DECnet HIORD prefix */ unsigned char dne_nodeaddr[2]; /* DECnet node address */ } dne_remote; }; typedef union etheraddress etheraddr; /* Ethernet address */ #define HIORD 0x000400aa /* high 32-bits of address (swapped) */ #define AREAMASK 0176000 /* mask for area field */ #define AREASHIFT 10 /* bit-offset for area field */ #define NODEMASK 01777 /* mask for node address field */ #define DN_MAXADDL 20 /* max size of DECnet address */ struct dn_naddr { unsigned short a_len; /* length of address */ unsigned char a_addr[DN_MAXADDL]; /* address as bytes */ }; /* * Define long and short header formats. */ struct shorthdr { byte sh_flags; /* route flags */ word sh_dst; /* destination node address */ word sh_src; /* source node address */ byte sh_visits; /* visit count */ }; struct longhdr { byte lg_flags; /* route flags */ byte lg_darea; /* destination area (reserved) */ byte lg_dsarea; /* destination subarea (reserved) */ etheraddr lg_dst; /* destination id */ byte lg_sarea; /* source area (reserved) */ byte lg_ssarea; /* source subarea (reserved) */ etheraddr lg_src; /* source id */ byte lg_nextl2; /* next level 2 router (reserved) */ byte lg_visits; /* visit count */ byte lg_service; /* service class (reserved) */ byte lg_pt; /* protocol type (reserved) */ }; union routehdr { struct shorthdr rh_short; /* short route header */ struct longhdr rh_long; /* long route header */ }; /* * Define the values of various fields in the protocol messages. * * 1. Data packet formats. */ #define RMF_MASK 7 /* mask for message type */ #define RMF_SHORT 2 /* short message format */ #define RMF_LONG 6 /* long message format */ #ifndef RMF_RQR #define RMF_RQR 010 /* request return to sender */ #define RMF_RTS 020 /* returning to sender */ #define RMF_IE 040 /* intra-ethernet packet */ #endif /* RMR_RQR */ #define RMF_FVER 0100 /* future version flag */ #define RMF_PAD 0200 /* pad field */ #define RMF_PADMASK 0177 /* pad field mask */ #define VIS_MASK 077 /* visit field mask */ /* * 2. Control packet formats. */ #define RMF_CTLMASK 017 /* mask for message type */ #define RMF_CTLMSG 01 /* control message indicator */ #define RMF_INIT 01 /* initialization message */ #define RMF_VER 03 /* verification message */ #define RMF_TEST 05 /* hello and test message */ #define RMF_L1ROUT 07 /* level 1 routing message */ #define RMF_L2ROUT 011 /* level 2 routing message */ #define RMF_RHELLO 013 /* router hello message */ #define RMF_EHELLO 015 /* endnode hello message */ #define TI_L2ROUT 01 /* level 2 router */ #define TI_L1ROUT 02 /* level 1 router */ #define TI_ENDNODE 03 /* endnode */ #define TI_VERIF 04 /* verification required */ #define TI_BLOCK 010 /* blocking requested */ #define VE_VERS 2 /* version number (2) */ #define VE_ECO 0 /* ECO number */ #define VE_UECO 0 /* user ECO number (0) */ #define P3_VERS 1 /* phase III version number (1) */ #define P3_ECO 3 /* ECO number (3) */ #define P3_UECO 0 /* user ECO number (0) */ #define II_L2ROUT 01 /* level 2 router */ #define II_L1ROUT 02 /* level 1 router */ #define II_ENDNODE 03 /* endnode */ #define II_VERIF 04 /* verification required */ #define II_NOMCAST 040 /* no multicast traffic accepted */ #define II_BLOCK 0100 /* blocking requested */ #define II_TYPEMASK 03 /* mask for node type */ #define TESTDATA 0252 /* test data bytes */ #define TESTLEN 1 /* length of transmitted test data */ /* * Define control message formats. */ struct initmsgIII /* phase III initialization message */ { byte inIII_flags; /* route flags */ word inIII_src; /* source node address */ byte inIII_info; /* routing layer information */ word inIII_blksize; /* maximum data link block size */ byte inIII_vers; /* version number */ byte inIII_eco; /* ECO number */ byte inIII_ueco; /* user ECO number */ byte inIII_rsvd; /* reserved image field */ }; struct initmsg /* initialization message */ { byte in_flags; /* route flags */ word in_src; /* source node address */ byte in_info; /* routing layer information */ word in_blksize; /* maximum data link block size */ byte in_vers; /* version number */ byte in_eco; /* ECO number */ byte in_ueco; /* user ECO number */ word in_hello; /* hello timer */ byte in_rsvd; /* reserved image field */ }; struct verifmsg /* verification message */ { byte ve_flags; /* route flags */ word ve_src; /* source node address */ byte ve_fcnval; /* function value image field */ }; struct testmsg /* hello and test message */ { byte te_flags; /* route flags */ word te_src; /* source node address */ byte te_data; /* test data image field */ }; struct l1rout /* level 1 routing message */ { byte r1_flags; /* route flags */ word r1_src; /* source node address */ byte r1_rsvd; /* reserved field */ }; struct l2rout /* level 2 routing message */ { byte r2_flags; /* route flags */ word r2_src; /* source node address */ byte r2_rsvd; /* reserved field */ }; struct rhellomsg /* router hello message */ { byte rh_flags; /* route flags */ byte rh_vers; /* version number */ byte rh_eco; /* ECO number */ byte rh_ueco; /* user ECO number */ etheraddr rh_src; /* source id */ byte rh_info; /* routing layer information */ word rh_blksize; /* maximum data link block size */ byte rh_priority; /* router's priority */ byte rh_area; /* reserved */ word rh_hello; /* hello timer */ byte rh_mpd; /* reserved */ }; struct ehellomsg /* endnode hello message */ { byte eh_flags; /* route flags */ byte eh_vers; /* version number */ byte eh_eco; /* ECO number */ byte eh_ueco; /* user ECO number */ etheraddr eh_src; /* source id */ byte eh_info; /* routing layer information */ word eh_blksize; /* maximum data link block size */ byte eh_area; /* area (reserved) */ byte eh_seed[8]; /* verification seed */ etheraddr eh_router; /* designated router */ word eh_hello; /* hello timer */ byte eh_mpd; /* (reserved) */ byte eh_data; /* test data image field */ }; union controlmsg { struct initmsg cm_init; /* initialization message */ struct verifmsg cm_ver; /* verification message */ struct testmsg cm_test; /* hello and test message */ struct l1rout cm_l1rou; /* level 1 routing message */ struct l2rout cm_l2rout; /* level 2 routing message */ struct rhellomsg cm_rhello; /* router hello message */ struct ehellomsg cm_ehello; /* endnode hello message */ }; /* Macros for decoding routing-info fields */ #define RI_COST(x) ((x)&0777) #define RI_HOPS(x) (((x)>>10)&037) /* * NSP protocol fields and values. */ #define NSP_TYPEMASK 014 /* mask to isolate type code */ #define NSP_SUBMASK 0160 /* mask to isolate subtype code */ #define NSP_SUBSHFT 4 /* shift to move subtype code */ #define MFT_DATA 0 /* data message */ #define MFT_ACK 04 /* acknowledgement message */ #define MFT_CTL 010 /* control message */ #define MFS_ILS 020 /* data or I/LS indicator */ #define MFS_BOM 040 /* beginning of message (data) */ #define MFS_MOM 0 /* middle of message (data) */ #define MFS_EOM 0100 /* end of message (data) */ #define MFS_INT 040 /* interrupt message */ #define MFS_DACK 0 /* data acknowledgement */ #define MFS_IACK 020 /* I/LS acknowledgement */ #define MFS_CACK 040 /* connect acknowledgement */ #define MFS_NOP 0 /* no operation */ #define MFS_CI 020 /* connect initiate */ #define MFS_CC 040 /* connect confirm */ #define MFS_DI 060 /* disconnect initiate */ #define MFS_DC 0100 /* disconnect confirm */ #define MFS_RCI 0140 /* retransmitted connect initiate */ #define SGQ_ACK 0100000 /* ack */ #define SGQ_NAK 0110000 /* negative ack */ #define SGQ_OACK 0120000 /* other channel ack */ #define SGQ_ONAK 0130000 /* other channel negative ack */ #define SGQ_MASK 07777 /* mask to isolate seq # */ #define SGQ_OTHER 020000 /* other channel qualifier */ #define SGQ_DELAY 010000 /* ack delay flag */ #define SGQ_EOM 0100000 /* pseudo flag for end-of-message */ #define LSM_MASK 03 /* mask for modifier field */ #define LSM_NOCHANGE 0 /* no change */ #define LSM_DONOTSEND 1 /* do not send data */ #define LSM_SEND 2 /* send data */ #define LSI_MASK 014 /* mask for interpretation field */ #define LSI_DATA 0 /* data segment or message count */ #define LSI_INTR 4 /* interrupt request count */ #define LSI_INTM 0377 /* funny marker for int. message */ #define COS_MASK 014 /* mask for flow control field */ #define COS_NONE 0 /* no flow control */ #define COS_SEGMENT 04 /* segment flow control */ #define COS_MESSAGE 010 /* message flow control */ #define COS_CRYPTSER 020 /* cryptographic services requested */ #define COS_DEFAULT 1 /* default value for field */ #define COI_MASK 3 /* mask for version field */ #define COI_32 0 /* version 3.2 */ #define COI_31 1 /* version 3.1 */ #define COI_40 2 /* version 4.0 */ #define COI_41 3 /* version 4.1 */ #define MNU_MASK 140 /* mask for session control version */ #define MNU_10 000 /* session V1.0 */ #define MNU_20 040 /* session V2.0 */ #define MNU_ACCESS 1 /* access control present */ #define MNU_USRDATA 2 /* user data field present */ #define MNU_INVKPROXY 4 /* invoke proxy field present */ #define MNU_UICPROXY 8 /* use uic-based proxy */ #define DC_NORESOURCES 1 /* no resource reason code */ #define DC_NOLINK 41 /* no link terminate reason code */ #define DC_COMPLETE 42 /* disconnect complete reason code */ #define DI_NOERROR 0 /* user disconnect */ #define DI_SHUT 3 /* node is shutting down */ #define DI_NOUSER 4 /* destination end user does not exist */ #define DI_INVDEST 5 /* invalid end user destination */ #define DI_REMRESRC 6 /* insufficient remote resources */ #define DI_TPA 8 /* third party abort */ #define DI_PROTOCOL 7 /* protocol error discovered */ #define DI_ABORT 9 /* user abort */ #define DI_LOCALRESRC 32 /* insufficient local resources */ #define DI_REMUSERRESRC 33 /* insufficient remote user resources */ #define DI_BADACCESS 34 /* bad access control information */ #define DI_BADACCNT 36 /* bad ACCOUNT information */ #define DI_CONNECTABORT 38 /* connect request cancelled */ #define DI_TIMEDOUT 38 /* remote node or user crashed */ #define DI_UNREACHABLE 39 /* local timers expired due to ... */ #define DI_BADIMAGE 43 /* bad image data in connect */ #define DI_SERVMISMATCH 54 /* cryptographic service mismatch */ #define UC_OBJREJECT 0 /* object rejected connect */ #define UC_USERDISCONNECT 0 /* user disconnect */ #define UC_RESOURCES 1 /* insufficient resources (local or remote) */ #define UC_NOSUCHNODE 2 /* unrecognized node name */ #define UC_REMOTESHUT 3 /* remote node shutting down */ #define UC_NOSUCHOBJ 4 /* unrecognized object */ #define UC_INVOBJFORMAT 5 /* invalid object name format */ #define UC_OBJTOOBUSY 6 /* object too busy */ #define UC_NETWORKABORT 8 /* network abort */ #define UC_USERABORT 9 /* user abort */ #define UC_INVNODEFORMAT 10 /* invalid node name format */ #define UC_LOCALSHUT 11 /* local node shutting down */ #define UC_ACCESSREJECT 34 /* invalid access control information */ #define UC_NORESPONSE 38 /* no response from object */ #define UC_UNREACHABLE 39 /* node unreachable */ /* * NSP message formats. */ struct nsphdr /* general nsp header */ { byte nh_flags; /* message flags */ word nh_dst; /* destination link address */ word nh_src; /* source link address */ }; struct seghdr /* data segment header */ { byte sh_flags; /* message flags */ word sh_dst; /* destination link address */ word sh_src; /* source link address */ word sh_seq[3]; /* sequence numbers */ }; struct minseghdr /* minimum data segment header */ { byte ms_flags; /* message flags */ word ms_dst; /* destination link address */ word ms_src; /* source link address */ word ms_seq; /* sequence number */ }; struct lsmsg /* link service message (after hdr) */ { byte ls_lsflags; /* link service flags */ byte ls_fcval; /* flow control value */ }; struct ackmsg /* acknowledgement message */ { byte ak_flags; /* message flags */ word ak_dst; /* destination link address */ word ak_src; /* source link address */ word ak_acknum[2]; /* acknowledgement numbers */ }; struct minackmsg /* minimum acknowledgement message */ { byte mk_flags; /* message flags */ word mk_dst; /* destination link address */ word mk_src; /* source link address */ word mk_acknum; /* acknowledgement number */ }; struct ciackmsg /* connect acknowledgement message */ { byte ck_flags; /* message flags */ word ck_dst; /* destination link address */ }; struct cimsg /* connect initiate message */ { byte ci_flags; /* message flags */ word ci_dst; /* destination link address (0) */ word ci_src; /* source link address */ byte ci_services; /* requested services */ byte ci_info; /* information */ word ci_segsize; /* maximum segment size */ }; struct ccmsg /* connect confirm message */ { byte cc_flags; /* message flags */ word cc_dst; /* destination link address */ word cc_src; /* source link address */ byte cc_services; /* requested services */ byte cc_info; /* information */ word cc_segsize; /* maximum segment size */ byte cc_optlen; /* optional data length */ }; struct cnmsg /* generic connect message */ { byte cn_flags; /* message flags */ word cn_dst; /* destination link address */ word cn_src; /* source link address */ byte cn_services; /* requested services */ byte cn_info; /* information */ word cn_segsize; /* maximum segment size */ }; struct dimsg /* disconnect initiate message */ { byte di_flags; /* message flags */ word di_dst; /* destination link address */ word di_src; /* source link address */ word di_reason; /* reason code */ byte di_optlen; /* optional data length */ }; struct dcmsg /* disconnect confirm message */ { byte dc_flags; /* message flags */ word dc_dst; /* destination link address */ word dc_src; /* source link address */ word dc_reason; /* reason code */ };
35.810155
79
0.667304
[ "object" ]
9aea0e2902738f2b774aaa81b8c6a9969cf142cd
53,823
c
C
release/src/linux/linux/fs/cifs/inode.c
ghsecuritylab/tomato_egg
50473a46347f4631eb4878a0f47955cc64c87293
[ "FSFAP" ]
278
2015-11-03T03:01:20.000Z
2022-01-20T18:21:05.000Z
release/src/linux/linux/fs/cifs/inode.c
ghsecuritylab/tomato_egg
50473a46347f4631eb4878a0f47955cc64c87293
[ "FSFAP" ]
374
2015-11-03T12:37:22.000Z
2021-12-17T14:18:08.000Z
release/src/linux/linux/fs/cifs/inode.c
ghsecuritylab/tomato_egg
50473a46347f4631eb4878a0f47955cc64c87293
[ "FSFAP" ]
96
2015-11-22T07:47:26.000Z
2022-01-20T19:52:19.000Z
/* * fs/cifs/inode.c * * Copyright (C) International Business Machines Corp., 2002,2007 * Author(s): Steve French (sfrench@us.ibm.com) * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/fs.h> #include <linux/stat.h> #include <linux/pagemap.h> #include <asm/div64.h> #include "cifsfs.h" #include "cifspdu.h" #include "cifsglob.h" #include "cifsproto.h" #include "cifs_debug.h" #include "cifs_fs_sb.h" #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0) #include <linux/buffer_head.h> #endif void cifs_init_inode(struct inode *inode) { struct cifsInodeInfo *cifs_inode; cifs_inode = CIFS_I(inode); cifs_inode->cifsAttrs = 0x20; /* default */ atomic_set(&cifs_inode->inUse, 0); cifs_inode->time = 0; /* Until the file is open and we have gotten oplock info back from the server, can not assume caching of file data or metadata */ cifs_inode->clientCanCacheRead = FALSE; cifs_inode->clientCanCacheAll = FALSE; inode->i_blksize = CIFS_MAX_MSGSIZE; inode->i_blkbits = 14; /* 2**14 = CIFS_MAX_MSGSIZE */ inode->i_flags = CIFS_INODE_FLAGS; INIT_LIST_HEAD(&cifs_inode->openFileList); } struct inode * get_cifs_inode(struct super_block * sb) { struct inode * newinode = new_inode(sb); cFYI(1,("got new inode %p", newinode)); #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 5, 0) if(newinode) { cifs_init_inode(newinode); } #endif return newinode; } int cifs_get_inode_info_unix(struct inode **pinode, const unsigned char *search_path, struct super_block *sb, int xid) { int rc = 0; FILE_UNIX_BASIC_INFO findData; struct cifsTconInfo *pTcon; struct inode *inode; struct cifs_sb_info *cifs_sb = CIFS_SB(sb); char *tmp_path; pTcon = cifs_sb->tcon; cFYI(1, ("Getting info on %s", search_path)); /* could have done a find first instead but this returns more info */ rc = CIFSSMBUnixQPathInfo(xid, pTcon, search_path, &findData, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); /* dump_mem("\nUnixQPathInfo return data", &findData, sizeof(findData)); */ if (rc) { if (rc == -EREMOTE) { tmp_path = kmalloc(strnlen(pTcon->treeName, MAX_TREE_SIZE + 1) + strnlen(search_path, MAX_PATHCONF) + 1, GFP_KERNEL); if (tmp_path == NULL) { return -ENOMEM; } /* have to skip first of the double backslash of UNC name */ strncpy(tmp_path, pTcon->treeName, MAX_TREE_SIZE); strncat(tmp_path, search_path, MAX_PATHCONF); rc = connect_to_dfs_path(xid, pTcon->ses, /* treename + */ tmp_path, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); kfree(tmp_path); /* BB fix up inode etc. */ } else if (rc) { return rc; } } else { struct cifsInodeInfo *cifsInfo; __u32 type = le32_to_cpu(findData.Type); __u64 num_of_bytes = le64_to_cpu(findData.NumOfBytes); __u64 end_of_file = le64_to_cpu(findData.EndOfFile); /* get new inode */ if (*pinode == NULL) { *pinode = get_cifs_inode(sb); if (*pinode == NULL) return -ENOMEM; /* Is an i_ino of zero legal? */ /* Are there sanity checks we can use to ensure that the server is really filling in that field? */ if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SERVER_INUM) { (*pinode)->i_ino = (unsigned long)findData.UniqueId; } /* note ino incremented to unique num in new_inode */ if (sb->s_flags & MS_NOATIME) (*pinode)->i_flags |= CIFS_INODE_FLAGS; insert_inode_hash(*pinode); } inode = *pinode; cifsInfo = CIFS_I(inode); cFYI(1, ("Old time %ld", cifsInfo->time)); cifsInfo->time = jiffies; cFYI(1, ("New time %ld", cifsInfo->time)); /* this is ok to set on every inode revalidate */ atomic_set(&cifsInfo->inUse,1); inode->i_atime = cifs_NTtimeToUnix(le64_to_cpu(findData.LastAccessTime)); inode->i_mtime = cifs_NTtimeToUnix(le64_to_cpu (findData.LastModificationTime)); inode->i_ctime = cifs_NTtimeToUnix(le64_to_cpu(findData.LastStatusChange)); inode->i_mode = le64_to_cpu(findData.Permissions); /* since we set the inode type below we need to mask off to avoid strange results if bits set above */ inode->i_mode &= ~S_IFMT; if (type == UNIX_FILE) { inode->i_mode |= S_IFREG; } else if (type == UNIX_SYMLINK) { inode->i_mode |= S_IFLNK; } else if (type == UNIX_DIR) { inode->i_mode |= S_IFDIR; } else if (type == UNIX_CHARDEV) { inode->i_mode |= S_IFCHR; inode->i_rdev = MKDEV(le64_to_cpu(findData.DevMajor), le64_to_cpu(findData.DevMinor) & MINORMASK); } else if (type == UNIX_BLOCKDEV) { inode->i_mode |= S_IFBLK; inode->i_rdev = MKDEV(le64_to_cpu(findData.DevMajor), le64_to_cpu(findData.DevMinor) & MINORMASK); } else if (type == UNIX_FIFO) { inode->i_mode |= S_IFIFO; } else if (type == UNIX_SOCKET) { inode->i_mode |= S_IFSOCK; } else { /* safest to call it a file if we do not know */ inode->i_mode |= S_IFREG; cFYI(1,("unknown type %d",type)); } if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_OVERR_UID) inode->i_uid = cifs_sb->mnt_uid; else inode->i_uid = le64_to_cpu(findData.Uid); if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_OVERR_GID) inode->i_gid = cifs_sb->mnt_gid; else inode->i_gid = le64_to_cpu(findData.Gid); inode->i_nlink = le64_to_cpu(findData.Nlinks); spin_lock(&inode->i_lock); if (is_size_safe_to_change(cifsInfo, end_of_file)) { /* can not safely change the file size here if the client is writing to it due to potential races */ i_size_write(inode, end_of_file); /* blksize needs to be multiple of two. So safer to default to blksize and blkbits set in superblock so 2**blkbits and blksize will match rather than setting to: (pTcon->ses->server->maxBuf - MAX_CIFS_HDR_SIZE) & 0xFFFFFE00;*/ /* This seems incredibly stupid but it turns out that i_blocks is not related to (i_size / i_blksize), instead 512 byte size is required for calculating num blocks */ /* 512 bytes (2**9) is the fake blocksize that must be used */ /* for this calculation */ inode->i_blocks = (512 - 1 + num_of_bytes) >> 9; } spin_unlock(&inode->i_lock); if (num_of_bytes < end_of_file) cFYI(1, ("allocation size less than end of file")); cFYI(1, ("Size %ld and blocks %llu", (unsigned long) inode->i_size, (unsigned long long)inode->i_blocks)); if (S_ISREG(inode->i_mode)) { cFYI(1, ("File inode")); inode->i_op = &cifs_file_inode_ops; if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_DIRECT_IO) { if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_BRL) inode->i_fop = &cifs_file_direct_nobrl_ops; else inode->i_fop = &cifs_file_direct_ops; } else if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_BRL) inode->i_fop = &cifs_file_nobrl_ops; else /* not direct, send byte range locks */ inode->i_fop = &cifs_file_ops; inode->i_data.a_ops = &cifs_addr_ops; #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0) /* check if server can support readpages */ if (pTcon->ses->server->maxBuf < PAGE_CACHE_SIZE + MAX_CIFS_HDR_SIZE) inode->i_data.a_ops = &cifs_addr_ops_smallbuf; #endif } else if (S_ISDIR(inode->i_mode)) { cFYI(1, ("Directory inode")); inode->i_op = &cifs_dir_inode_ops; inode->i_fop = &cifs_dir_ops; } else if (S_ISLNK(inode->i_mode)) { cFYI(1, ("Symbolic Link inode")); inode->i_op = &cifs_symlink_inode_ops; /* tmp_inode->i_fop = */ /* do not need to set to anything */ } else { cFYI(1, ("Init special inode")); init_special_inode(inode, inode->i_mode, inode->i_rdev); } } return rc; } static int decode_sfu_inode(struct inode * inode, __u64 size, const unsigned char *path, struct cifs_sb_info *cifs_sb, int xid) { int rc; int oplock = FALSE; __u16 netfid; struct cifsTconInfo *pTcon = cifs_sb->tcon; char buf[24]; unsigned int bytes_read; char * pbuf; pbuf = buf; if (size == 0) { inode->i_mode |= S_IFIFO; return 0; } else if (size < 8) { return -EINVAL; /* EOPNOTSUPP? */ } rc = CIFSSMBOpen(xid, pTcon, path, FILE_OPEN, GENERIC_READ, CREATE_NOT_DIR, &netfid, &oplock, NULL, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); if (rc==0) { int buf_type = CIFS_NO_BUFFER; /* Read header */ rc = CIFSSMBRead(xid, pTcon, netfid, 24 /* length */, 0 /* offset */, &bytes_read, &pbuf, &buf_type); if ((rc == 0) && (bytes_read >= 8)) { if (memcmp("IntxBLK", pbuf, 8) == 0) { cFYI(1,("Block device")); inode->i_mode |= S_IFBLK; if (bytes_read == 24) { /* we have enough to decode dev num */ __u64 mjr; /* major */ __u64 mnr; /* minor */ mjr = le64_to_cpu(*(__le64 *)(pbuf+8)); mnr = le64_to_cpu(*(__le64 *)(pbuf+16)); inode->i_rdev = MKDEV(mjr, mnr); } } else if (memcmp("IntxCHR", pbuf, 8) == 0) { cFYI(1,("Char device")); inode->i_mode |= S_IFCHR; if (bytes_read == 24) { /* we have enough to decode dev num */ __u64 mjr; /* major */ __u64 mnr; /* minor */ mjr = le64_to_cpu(*(__le64 *)(pbuf+8)); mnr = le64_to_cpu(*(__le64 *)(pbuf+16)); inode->i_rdev = MKDEV(mjr, mnr); } } else if (memcmp("IntxLNK", pbuf, 7) == 0) { cFYI(1,("Symlink")); inode->i_mode |= S_IFLNK; } else { inode->i_mode |= S_IFREG; /* file? */ rc = -EOPNOTSUPP; } } else { inode->i_mode |= S_IFREG; /* then it is a file */ rc = -EOPNOTSUPP; /* or some unknown SFU type */ } CIFSSMBClose(xid, pTcon, netfid); } return rc; } #define SFBITS_MASK (S_ISVTX | S_ISGID | S_ISUID) /* SETFILEBITS valid bits */ static int get_sfu_uid_mode(struct inode * inode, const unsigned char *path, struct cifs_sb_info *cifs_sb, int xid) { #ifdef CONFIG_CIFS_XATTR ssize_t rc; char ea_value[4]; __u32 mode; rc = CIFSSMBQueryEA(xid, cifs_sb->tcon, path, "SETFILEBITS", ea_value, 4 /* size of buf */, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); if (rc < 0) return (int)rc; else if (rc > 3) { mode = le32_to_cpu(*((__le32 *)ea_value)); inode->i_mode &= ~SFBITS_MASK; cFYI(1,("special bits 0%o org mode 0%o", mode, inode->i_mode)); inode->i_mode = (mode & SFBITS_MASK) | inode->i_mode; cFYI(1,("special mode bits 0%o", mode)); return 0; } else { return 0; } #else return -EOPNOTSUPP; #endif } int cifs_get_inode_info(struct inode **pinode, const unsigned char *search_path, FILE_ALL_INFO *pfindData, struct super_block *sb, int xid) { int rc = 0; struct cifsTconInfo *pTcon; struct inode *inode; struct cifs_sb_info *cifs_sb = CIFS_SB(sb); char *tmp_path; char *buf = NULL; int adjustTZ = FALSE; pTcon = cifs_sb->tcon; cFYI(1,("Getting info on %s", search_path)); if ((pfindData == NULL) && (*pinode != NULL)) { if (CIFS_I(*pinode)->clientCanCacheRead) { cFYI(1,("No need to revalidate cached inode sizes")); return rc; } } /* if file info not passed in then get it from server */ if (pfindData == NULL) { buf = kmalloc(sizeof(FILE_ALL_INFO), GFP_KERNEL); if (buf == NULL) return -ENOMEM; pfindData = (FILE_ALL_INFO *)buf; /* could do find first instead but this returns more info */ rc = CIFSSMBQPathInfo(xid, pTcon, search_path, pfindData, 0 /* not legacy */, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); /* BB optimize code so we do not make the above call when server claims no NT SMB support and the above call failed at least once - set flag in tcon or mount */ if ((rc == -EOPNOTSUPP) || (rc == -EINVAL)) { rc = SMBQueryInformation(xid, pTcon, search_path, pfindData, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); adjustTZ = TRUE; } } /* dump_mem("\nQPathInfo return data",&findData, sizeof(findData)); */ if (rc) { if (rc == -EREMOTE) { tmp_path = kmalloc(strnlen (pTcon->treeName, MAX_TREE_SIZE + 1) + strnlen(search_path, MAX_PATHCONF) + 1, GFP_KERNEL); if (tmp_path == NULL) { kfree(buf); return -ENOMEM; } strncpy(tmp_path, pTcon->treeName, MAX_TREE_SIZE); strncat(tmp_path, search_path, MAX_PATHCONF); rc = connect_to_dfs_path(xid, pTcon->ses, /* treename + */ tmp_path, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); kfree(tmp_path); /* BB fix up inode etc. */ } else if (rc) { kfree(buf); return rc; } } else { struct cifsInodeInfo *cifsInfo; __u32 attr = le32_to_cpu(pfindData->Attributes); /* get new inode */ if (*pinode == NULL) { *pinode = get_cifs_inode(sb); if (*pinode == NULL) { kfree(buf); return -ENOMEM; } /* Is an i_ino of zero legal? Can we use that to check if the server supports returning inode numbers? Are there other sanity checks we can use to ensure that the server is really filling in that field? */ /* We can not use the IndexNumber field by default from Windows or Samba (in ALL_INFO buf) but we can request it explicitly. It may not be unique presumably if the server has multiple devices mounted under one share */ /* There may be higher info levels that work but are there Windows server or network appliances for which IndexNumber field is not guaranteed unique? */ if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SERVER_INUM){ int rc1 = 0; __u64 inode_num; rc1 = CIFSGetSrvInodeNumber(xid, pTcon, search_path, &inode_num, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); if (rc1) { cFYI(1,("GetSrvInodeNum rc %d", rc1)); /* BB EOPNOSUPP disable SERVER_INUM? */ } else /* do we need cast or hash to ino? */ (*pinode)->i_ino = inode_num; } /* else ino incremented to unique num in new_inode*/ if (sb->s_flags & MS_NOATIME) (*pinode)->i_flags |= CIFS_INODE_FLAGS; insert_inode_hash(*pinode); } inode = *pinode; cifsInfo = CIFS_I(inode); cifsInfo->cifsAttrs = attr; cFYI(1, ("Old time %ld", cifsInfo->time)); cifsInfo->time = jiffies; cFYI(1, ("New time %ld", cifsInfo->time)); /* blksize needs to be multiple of two. So safer to default to blksize and blkbits set in superblock so 2**blkbits and blksize will match rather than setting to: (pTcon->ses->server->maxBuf - MAX_CIFS_HDR_SIZE) & 0xFFFFFE00;*/ /* Linux can not store file creation time so ignore it */ if (pfindData->LastAccessTime) inode->i_atime = cifs_NTtimeToUnix (le64_to_cpu(pfindData->LastAccessTime)); else /* do not need to use current_fs_time - time not stored */ inode->i_atime = CURRENT_TIME; inode->i_mtime = cifs_NTtimeToUnix(le64_to_cpu(pfindData->LastWriteTime)); inode->i_ctime = cifs_NTtimeToUnix(le64_to_cpu(pfindData->ChangeTime)); cFYI(0, ("Attributes came in as 0x%x", attr)); if (adjustTZ && (pTcon->ses) && (pTcon->ses->server)) { #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0) inode->i_ctime.tv_sec += pTcon->ses->server->timeAdj; inode->i_mtime.tv_sec += pTcon->ses->server->timeAdj; #else inode->i_ctime += pTcon->ses->server->timeAdj; inode->i_mtime += pTcon->ses->server->timeAdj; #endif } /* set default mode. will override for dirs below */ if (atomic_read(&cifsInfo->inUse) == 0) /* new inode, can safely set these fields */ inode->i_mode = cifs_sb->mnt_file_mode; else /* since we set the inode type below we need to mask off to avoid strange results if type changes and both get orred in */ inode->i_mode &= ~S_IFMT; /* if (attr & ATTR_REPARSE) */ /* We no longer handle these as symlinks because we could not follow them due to the absolute path with drive letter */ if (attr & ATTR_DIRECTORY) { /* override default perms since we do not do byte range locking on dirs */ inode->i_mode = cifs_sb->mnt_dir_mode; inode->i_mode |= S_IFDIR; } else if ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_UNX_EMUL) && (cifsInfo->cifsAttrs & ATTR_SYSTEM) && /* No need to le64 convert size of zero */ (pfindData->EndOfFile == 0)) { inode->i_mode = cifs_sb->mnt_file_mode; inode->i_mode |= S_IFIFO; /* BB Finish for SFU style symlinks and devices */ } else if ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_UNX_EMUL) && (cifsInfo->cifsAttrs & ATTR_SYSTEM)) { if (decode_sfu_inode(inode, le64_to_cpu(pfindData->EndOfFile), search_path, cifs_sb, xid)) { cFYI(1,("Unrecognized sfu inode type")); } cFYI(1,("sfu mode 0%o",inode->i_mode)); } else { inode->i_mode |= S_IFREG; /* treat the dos attribute of read-only as read-only mode e.g. 555 */ if (cifsInfo->cifsAttrs & ATTR_READONLY) inode->i_mode &= ~(S_IWUGO); else if ((inode->i_mode & S_IWUGO) == 0) /* the ATTR_READONLY flag may have been */ /* changed on server -- set any w bits */ /* allowed by mnt_file_mode */ inode->i_mode |= (S_IWUGO & cifs_sb->mnt_file_mode); /* BB add code here - validate if device or weird share or device type? */ } spin_lock(&inode->i_lock); if (is_size_safe_to_change(cifsInfo, le64_to_cpu(pfindData->EndOfFile))) { /* can not safely shrink the file size here if the client is writing to it due to potential races */ i_size_write(inode,le64_to_cpu(pfindData->EndOfFile)); /* 512 bytes (2**9) is the fake blocksize that must be used for this calculation */ inode->i_blocks = (512 - 1 + le64_to_cpu( pfindData->AllocationSize)) >> 9; } spin_unlock(&inode->i_lock); inode->i_nlink = le32_to_cpu(pfindData->NumberOfLinks); /* BB fill in uid and gid here? with help from winbind? or retrieve from NTFS stream extended attribute */ if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_UNX_EMUL) { /* fill in uid, gid, mode from server ACL */ /* BB FIXME this should also take into account the * default uid specified on mount if present */ get_sfu_uid_mode(inode, search_path, cifs_sb, xid); } else if (atomic_read(&cifsInfo->inUse) == 0) { inode->i_uid = cifs_sb->mnt_uid; inode->i_gid = cifs_sb->mnt_gid; /* set so we do not keep refreshing these fields with bad data after user has changed them in memory */ atomic_set(&cifsInfo->inUse,1); } if (S_ISREG(inode->i_mode)) { cFYI(1, ("File inode")); inode->i_op = &cifs_file_inode_ops; if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_DIRECT_IO) { if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_BRL) inode->i_fop = &cifs_file_direct_nobrl_ops; else inode->i_fop = &cifs_file_direct_ops; } else if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_BRL) inode->i_fop = &cifs_file_nobrl_ops; else /* not direct, send byte range locks */ inode->i_fop = &cifs_file_ops; inode->i_data.a_ops = &cifs_addr_ops; #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0) if (pTcon->ses->server->maxBuf < PAGE_CACHE_SIZE + MAX_CIFS_HDR_SIZE) inode->i_data.a_ops = &cifs_addr_ops_smallbuf; #endif } else if (S_ISDIR(inode->i_mode)) { cFYI(1, ("Directory inode")); inode->i_op = &cifs_dir_inode_ops; inode->i_fop = &cifs_dir_ops; } else if (S_ISLNK(inode->i_mode)) { cFYI(1, ("Symbolic Link inode")); inode->i_op = &cifs_symlink_inode_ops; } else { init_special_inode(inode, inode->i_mode, inode->i_rdev); } } kfree(buf); return rc; } /* gets root inode */ void cifs_read_inode(struct inode *inode) { int xid; struct cifs_sb_info *cifs_sb; #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 5, 0) cifs_init_inode(inode); #endif cifs_sb = CIFS_SB(inode->i_sb); xid = GetXid(); if (cifs_sb->tcon->ses->capabilities & CAP_UNIX) cifs_get_inode_info_unix(&inode, "", inode->i_sb,xid); else cifs_get_inode_info(&inode, "", NULL, inode->i_sb,xid); /* can not call macro FreeXid here since in a void func */ _FreeXid(xid); } int cifs_unlink(struct inode *inode, struct dentry *direntry) { int rc = 0; int xid; struct cifs_sb_info *cifs_sb; struct cifsTconInfo *pTcon; char *full_path = NULL; struct cifsInodeInfo *cifsInode; FILE_BASIC_INFO *pinfo_buf; cFYI(1, ("cifs_unlink, inode = 0x%p", inode)); xid = GetXid(); if (inode) cifs_sb = CIFS_SB(inode->i_sb); else cifs_sb = CIFS_SB(direntry->d_sb); pTcon = cifs_sb->tcon; /* Unlink can be called from rename so we can not grab the sem here since we deadlock otherwise */ /* down(&direntry->d_sb->s_vfs_rename_sem);*/ full_path = build_path_from_dentry(direntry); /* up(&direntry->d_sb->s_vfs_rename_sem);*/ if (full_path == NULL) { FreeXid(xid); return -ENOMEM; } rc = CIFSSMBDelFile(xid, pTcon, full_path, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); if (!rc) { if (direntry->d_inode) direntry->d_inode->i_nlink--; } else if (rc == -ENOENT) { d_drop(direntry); } else if (rc == -ETXTBSY) { int oplock = FALSE; __u16 netfid; rc = CIFSSMBOpen(xid, pTcon, full_path, FILE_OPEN, DELETE, CREATE_NOT_DIR | CREATE_DELETE_ON_CLOSE, &netfid, &oplock, NULL, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); if (rc==0) { CIFSSMBRenameOpenFile(xid, pTcon, netfid, NULL, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); CIFSSMBClose(xid, pTcon, netfid); if (direntry->d_inode) direntry->d_inode->i_nlink--; } } else if (rc == -EACCES) { /* try only if r/o attribute set in local lookup data? */ pinfo_buf = kzalloc(sizeof(FILE_BASIC_INFO), GFP_KERNEL); if (pinfo_buf) { /* ATTRS set to normal clears r/o bit */ pinfo_buf->Attributes = cpu_to_le32(ATTR_NORMAL); if (!(pTcon->ses->flags & CIFS_SES_NT4)) rc = CIFSSMBSetTimes(xid, pTcon, full_path, pinfo_buf, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); else rc = -EOPNOTSUPP; if (rc == -EOPNOTSUPP) { int oplock = FALSE; __u16 netfid; /* rc = CIFSSMBSetAttrLegacy(xid, pTcon, full_path, (__u16)ATTR_NORMAL, cifs_sb->local_nls); For some strange reason it seems that NT4 eats the old setattr call without actually setting the attributes so on to the third attempted workaround */ /* BB could scan to see if we already have it open and pass in pid of opener to function */ rc = CIFSSMBOpen(xid, pTcon, full_path, FILE_OPEN, SYNCHRONIZE | FILE_WRITE_ATTRIBUTES, 0, &netfid, &oplock, NULL, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); if (rc==0) { rc = CIFSSMBSetFileTimes(xid, pTcon, pinfo_buf, netfid); CIFSSMBClose(xid, pTcon, netfid); } } kfree(pinfo_buf); } if (rc==0) { rc = CIFSSMBDelFile(xid, pTcon, full_path, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); if (!rc) { if (direntry->d_inode) direntry->d_inode->i_nlink--; } else if (rc == -ETXTBSY) { int oplock = FALSE; __u16 netfid; rc = CIFSSMBOpen(xid, pTcon, full_path, FILE_OPEN, DELETE, CREATE_NOT_DIR | CREATE_DELETE_ON_CLOSE, &netfid, &oplock, NULL, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); if (rc==0) { CIFSSMBRenameOpenFile(xid, pTcon, netfid, NULL, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); CIFSSMBClose(xid, pTcon, netfid); if (direntry->d_inode) direntry->d_inode->i_nlink--; } /* BB if rc = -ETXTBUSY goto the rename logic BB */ } } } if (direntry->d_inode) { cifsInode = CIFS_I(direntry->d_inode); cifsInode->time = 0; /* will force revalidate to get info when needed */ direntry->d_inode->i_ctime = current_fs_time(inode->i_sb); } if (inode) { inode->i_ctime = inode->i_mtime = current_fs_time(inode->i_sb); cifsInode = CIFS_I(inode); cifsInode->time = 0; /* force revalidate of dir as well */ } kfree(full_path); FreeXid(xid); return rc; } static void posix_fill_in_inode(struct inode *tmp_inode, FILE_UNIX_BASIC_INFO *pData, int *pobject_type, int isNewInode) { loff_t local_size; #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0) struct timespec local_mtime; #else time_t local_mtime; #endif struct cifsInodeInfo *cifsInfo = CIFS_I(tmp_inode); struct cifs_sb_info *cifs_sb = CIFS_SB(tmp_inode->i_sb); __u32 type = le32_to_cpu(pData->Type); __u64 num_of_bytes = le64_to_cpu(pData->NumOfBytes); __u64 end_of_file = le64_to_cpu(pData->EndOfFile); cifsInfo->time = jiffies; atomic_inc(&cifsInfo->inUse); /* save mtime and size */ local_mtime = tmp_inode->i_mtime; local_size = tmp_inode->i_size; tmp_inode->i_atime = cifs_NTtimeToUnix(le64_to_cpu(pData->LastAccessTime)); tmp_inode->i_mtime = cifs_NTtimeToUnix(le64_to_cpu(pData->LastModificationTime)); tmp_inode->i_ctime = cifs_NTtimeToUnix(le64_to_cpu(pData->LastStatusChange)); tmp_inode->i_mode = le64_to_cpu(pData->Permissions); /* since we set the inode type below we need to mask off type to avoid strange results if bits above were corrupt */ tmp_inode->i_mode &= ~S_IFMT; if (type == UNIX_FILE) { *pobject_type = DT_REG; tmp_inode->i_mode |= S_IFREG; } else if (type == UNIX_SYMLINK) { *pobject_type = DT_LNK; tmp_inode->i_mode |= S_IFLNK; } else if (type == UNIX_DIR) { *pobject_type = DT_DIR; tmp_inode->i_mode |= S_IFDIR; } else if (type == UNIX_CHARDEV) { *pobject_type = DT_CHR; tmp_inode->i_mode |= S_IFCHR; tmp_inode->i_rdev = MKDEV(le64_to_cpu(pData->DevMajor), le64_to_cpu(pData->DevMinor) & MINORMASK); } else if (type == UNIX_BLOCKDEV) { *pobject_type = DT_BLK; tmp_inode->i_mode |= S_IFBLK; tmp_inode->i_rdev = MKDEV(le64_to_cpu(pData->DevMajor), le64_to_cpu(pData->DevMinor) & MINORMASK); } else if (type == UNIX_FIFO) { *pobject_type = DT_FIFO; tmp_inode->i_mode |= S_IFIFO; } else if (type == UNIX_SOCKET) { *pobject_type = DT_SOCK; tmp_inode->i_mode |= S_IFSOCK; } else { /* safest to just call it a file */ *pobject_type = DT_REG; tmp_inode->i_mode |= S_IFREG; cFYI(1,("unknown inode type %d",type)); } #ifdef CONFIG_CIFS_DEBUG2 cFYI(1,("object type: %d", type)); #endif tmp_inode->i_uid = le64_to_cpu(pData->Uid); tmp_inode->i_gid = le64_to_cpu(pData->Gid); tmp_inode->i_nlink = le64_to_cpu(pData->Nlinks); spin_lock(&tmp_inode->i_lock); if (is_size_safe_to_change(cifsInfo, end_of_file)) { /* can not safely change the file size here if the client is writing to it due to potential races */ i_size_write(tmp_inode, end_of_file); /* 512 bytes (2**9) is the fake blocksize that must be used */ /* for this calculation, not the real blocksize */ tmp_inode->i_blocks = (512 - 1 + num_of_bytes) >> 9; } spin_unlock(&tmp_inode->i_lock); if (S_ISREG(tmp_inode->i_mode)) { cFYI(1, ("File inode")); tmp_inode->i_op = &cifs_file_inode_ops; if(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_DIRECT_IO) { if(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_BRL) tmp_inode->i_fop = &cifs_file_direct_nobrl_ops; else tmp_inode->i_fop = &cifs_file_direct_ops; } else if(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_BRL) tmp_inode->i_fop = &cifs_file_nobrl_ops; else tmp_inode->i_fop = &cifs_file_ops; if((cifs_sb->tcon) && (cifs_sb->tcon->ses) && (cifs_sb->tcon->ses->server->maxBuf < PAGE_CACHE_SIZE + MAX_CIFS_HDR_SIZE)) tmp_inode->i_data.a_ops = &cifs_addr_ops_smallbuf; else tmp_inode->i_data.a_ops = &cifs_addr_ops; if(isNewInode) return; /* No sense invalidating pages for new inode since we have not started caching readahead file data yet */ if (timespec_equal(&tmp_inode->i_mtime, &local_mtime) && (local_size == tmp_inode->i_size)) { cFYI(1, ("inode exists but unchanged")); } else { /* file may have changed on server */ cFYI(1, ("invalidate inode, readdir detected change")); invalidate_remote_inode(tmp_inode); } } else if (S_ISDIR(tmp_inode->i_mode)) { cFYI(1, ("Directory inode")); tmp_inode->i_op = &cifs_dir_inode_ops; tmp_inode->i_fop = &cifs_dir_ops; } else if (S_ISLNK(tmp_inode->i_mode)) { cFYI(1, ("Symbolic Link inode")); tmp_inode->i_op = &cifs_symlink_inode_ops; /* tmp_inode->i_fop = *//* do not need to set to anything */ } else { cFYI(1, ("Special inode")); init_special_inode(tmp_inode, tmp_inode->i_mode, tmp_inode->i_rdev); } } int cifs_mkdir(struct inode *inode, struct dentry *direntry, int mode) { int rc = 0; int xid; struct cifs_sb_info *cifs_sb; struct cifsTconInfo *pTcon; char *full_path = NULL; struct inode *newinode = NULL; cFYI(1, ("In cifs_mkdir, mode = 0x%x inode = 0x%p", mode, inode)); xid = GetXid(); cifs_sb = CIFS_SB(inode->i_sb); pTcon = cifs_sb->tcon; full_path = build_path_from_dentry(direntry); if (full_path == NULL) { FreeXid(xid); return -ENOMEM; } if((pTcon->ses->capabilities & CAP_UNIX) && (CIFS_UNIX_POSIX_PATH_OPS_CAP & le64_to_cpu(pTcon->fsUnixInfo.Capability))) { u32 oplock = 0; FILE_UNIX_BASIC_INFO * pInfo = kzalloc(sizeof(FILE_UNIX_BASIC_INFO), GFP_KERNEL); if(pInfo == NULL) { rc = -ENOMEM; goto mkdir_out; } mode &= ~current->fs->umask; rc = CIFSPOSIXCreate(xid, pTcon, SMB_O_DIRECTORY | SMB_O_CREAT, mode, NULL /* netfid */, pInfo, &oplock, full_path, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); if (rc == -EOPNOTSUPP) { kfree(pInfo); goto mkdir_retry_old; } else if (rc) { cFYI(1, ("posix mkdir returned 0x%x", rc)); d_drop(direntry); } else { int obj_type; if (pInfo->Type == -1) /* no return info - go query */ { kfree(pInfo); goto mkdir_get_info; } /*BB check (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SET_UID ) to see if need to set uid/gid */ inode->i_nlink++; if (pTcon->nocase) direntry->d_op = &cifs_ci_dentry_ops; else direntry->d_op = &cifs_dentry_ops; newinode = new_inode(inode->i_sb); if (newinode == NULL) { kfree(pInfo); goto mkdir_get_info; } /* Is an i_ino of zero legal? */ /* Are there sanity checks we can use to ensure that the server is really filling in that field? */ if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SERVER_INUM) { newinode->i_ino = (unsigned long)pInfo->UniqueId; } /* note ino incremented to unique num in new_inode */ if(inode->i_sb->s_flags & MS_NOATIME) newinode->i_flags |= CIFS_INODE_FLAGS; newinode->i_nlink = 2; insert_inode_hash(newinode); d_instantiate(direntry, newinode); /* we already checked in POSIXCreate whether frame was long enough */ posix_fill_in_inode(direntry->d_inode, pInfo, &obj_type, 1 /* NewInode */); #ifdef CONFIG_CIFS_DEBUG2 cFYI(1,("instantiated dentry %p %s to inode %p", direntry, direntry->d_name.name, newinode)); if(newinode->i_nlink != 2) cFYI(1,("unexpected number of links %d", newinode->i_nlink)); #endif } kfree(pInfo); goto mkdir_out; } mkdir_retry_old: /* BB add setting the equivalent of mode via CreateX w/ACLs */ rc = CIFSSMBMkDir(xid, pTcon, full_path, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); if (rc) { cFYI(1, ("cifs_mkdir returned 0x%x", rc)); d_drop(direntry); } else { mkdir_get_info: inode->i_nlink++; if (pTcon->ses->capabilities & CAP_UNIX) rc = cifs_get_inode_info_unix(&newinode, full_path, inode->i_sb,xid); else rc = cifs_get_inode_info(&newinode, full_path, NULL, inode->i_sb,xid); if (pTcon->nocase) direntry->d_op = &cifs_ci_dentry_ops; else direntry->d_op = &cifs_dentry_ops; d_instantiate(direntry, newinode); /* setting nlink not necessary except in cases where we * failed to get it from the server or was set bogus */ if ((direntry->d_inode) && (direntry->d_inode->i_nlink < 2)) direntry->d_inode->i_nlink = 2; if (cifs_sb->tcon->ses->capabilities & CAP_UNIX) { mode &= ~current->fs->umask; if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SET_UID) { CIFSSMBUnixSetPerms(xid, pTcon, full_path, mode, (__u64)current->fsuid, (__u64)current->fsgid, 0 /* dev_t */, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); } else { CIFSSMBUnixSetPerms(xid, pTcon, full_path, mode, (__u64)-1, (__u64)-1, 0 /* dev_t */, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); } } else { /* BB to be implemented via Windows secrty descriptors eg CIFSSMBWinSetPerms(xid, pTcon, full_path, mode, -1, -1, local_nls); */ if(direntry->d_inode) { direntry->d_inode->i_mode = mode; direntry->d_inode->i_mode |= S_IFDIR; if(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SET_UID) { direntry->d_inode->i_uid = current->fsuid; direntry->d_inode->i_gid = current->fsgid; } } } } mkdir_out: kfree(full_path); FreeXid(xid); return rc; } int cifs_rmdir(struct inode *inode, struct dentry *direntry) { int rc = 0; int xid; struct cifs_sb_info *cifs_sb; struct cifsTconInfo *pTcon; char *full_path = NULL; struct cifsInodeInfo *cifsInode; cFYI(1, ("cifs_rmdir, inode = 0x%p", inode)); xid = GetXid(); cifs_sb = CIFS_SB(inode->i_sb); pTcon = cifs_sb->tcon; full_path = build_path_from_dentry(direntry); if (full_path == NULL) { FreeXid(xid); return -ENOMEM; } rc = CIFSSMBRmDir(xid, pTcon, full_path, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); if (!rc) { inode->i_nlink--; spin_lock(&direntry->d_inode->i_lock); i_size_write(direntry->d_inode,0); direntry->d_inode->i_nlink = 0; spin_unlock(&direntry->d_inode->i_lock); } cifsInode = CIFS_I(direntry->d_inode); cifsInode->time = 0; /* force revalidate to go get info when needed */ direntry->d_inode->i_ctime = inode->i_ctime = inode->i_mtime = current_fs_time(inode->i_sb); kfree(full_path); FreeXid(xid); return rc; } int cifs_rename(struct inode *source_inode, struct dentry *source_direntry, struct inode *target_inode, struct dentry *target_direntry) { char *fromName; char *toName; struct cifs_sb_info *cifs_sb_source; struct cifs_sb_info *cifs_sb_target; struct cifsTconInfo *pTcon; int xid; int rc = 0; xid = GetXid(); cifs_sb_target = CIFS_SB(target_inode->i_sb); cifs_sb_source = CIFS_SB(source_inode->i_sb); pTcon = cifs_sb_source->tcon; if (pTcon != cifs_sb_target->tcon) { FreeXid(xid); return -EXDEV; /* BB actually could be allowed if same server, but different share. Might eventually add support for this */ } /* we already have the rename sem so we do not need to grab it again here to protect the path integrity */ fromName = build_path_from_dentry(source_direntry); toName = build_path_from_dentry(target_direntry); if ((fromName == NULL) || (toName == NULL)) { rc = -ENOMEM; goto cifs_rename_exit; } rc = CIFSSMBRename(xid, pTcon, fromName, toName, cifs_sb_source->local_nls, cifs_sb_source->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); if (rc == -EEXIST) { /* check if they are the same file because rename of hardlinked files is a noop */ FILE_UNIX_BASIC_INFO *info_buf_source; FILE_UNIX_BASIC_INFO *info_buf_target; info_buf_source = kmalloc(2 * sizeof(FILE_UNIX_BASIC_INFO), GFP_KERNEL); if (info_buf_source != NULL) { info_buf_target = info_buf_source + 1; if (pTcon->ses->capabilities & CAP_UNIX) rc = CIFSSMBUnixQPathInfo(xid, pTcon, fromName, info_buf_source, cifs_sb_source->local_nls, cifs_sb_source->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); /* else rc is still EEXIST so will fall through to unlink the target and retry rename */ if (rc == 0) { rc = CIFSSMBUnixQPathInfo(xid, pTcon, toName, info_buf_target, cifs_sb_target->local_nls, /* remap based on source sb */ cifs_sb_source->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); } if ((rc == 0) && (info_buf_source->UniqueId == info_buf_target->UniqueId)) { /* do not rename since the files are hardlinked which is a noop */ } else { /* we either can not tell the files are hardlinked (as with Windows servers) or files are not hardlinked so delete the target manually before renaming to follow POSIX rather than Windows semantics */ cifs_unlink(target_inode, target_direntry); rc = CIFSSMBRename(xid, pTcon, fromName, toName, cifs_sb_source->local_nls, cifs_sb_source->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); } kfree(info_buf_source); } /* if we can not get memory just leave rc as EEXIST */ } if (rc) { cFYI(1, ("rename rc %d", rc)); } if ((rc == -EIO) || (rc == -EEXIST)) { int oplock = FALSE; __u16 netfid; /* BB FIXME Is Generic Read correct for rename? */ /* if renaming directory - we should not say CREATE_NOT_DIR, need to test renaming open directory, also GENERIC_READ might not right be right access to request */ rc = CIFSSMBOpen(xid, pTcon, fromName, FILE_OPEN, GENERIC_READ, CREATE_NOT_DIR, &netfid, &oplock, NULL, cifs_sb_source->local_nls, cifs_sb_source->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); if (rc==0) { rc = CIFSSMBRenameOpenFile(xid, pTcon, netfid, toName, cifs_sb_source->local_nls, cifs_sb_source->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); CIFSSMBClose(xid, pTcon, netfid); } } cifs_rename_exit: kfree(fromName); kfree(toName); FreeXid(xid); return rc; } int cifs_revalidate(struct dentry *direntry) { int xid; int rc = 0; char *full_path; struct cifs_sb_info *cifs_sb; struct cifsInodeInfo *cifsInode; loff_t local_size; #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0) struct timespec local_mtime; #else time_t local_mtime; #endif int invalidate_inode = FALSE; if (direntry->d_inode == NULL) return -ENOENT; cifsInode = CIFS_I(direntry->d_inode); if (cifsInode == NULL) return -ENOENT; /* no sense revalidating inode info on file that no one can write */ if (CIFS_I(direntry->d_inode)->clientCanCacheRead) return rc; xid = GetXid(); cifs_sb = CIFS_SB(direntry->d_sb); /* can not safely grab the rename sem here if rename calls revalidate since that would deadlock */ full_path = build_path_from_dentry(direntry); if (full_path == NULL) { FreeXid(xid); return -ENOMEM; } cFYI(1, ("Revalidate: %s inode 0x%p count %d dentry: 0x%p d_time %ld " "jiffies %ld", full_path, direntry->d_inode, direntry->d_inode->i_count.counter, direntry, direntry->d_time, jiffies)); if (cifsInode->time == 0) { /* was set to zero previously to force revalidate */ } else if (time_before(jiffies, cifsInode->time + HZ) && lookupCacheEnabled) { if ((S_ISREG(direntry->d_inode->i_mode) == 0) || (direntry->d_inode->i_nlink == 1)) { kfree(full_path); FreeXid(xid); return rc; } else { cFYI(1, ("Have to revalidate file due to hardlinks")); } } /* save mtime and size */ local_mtime = direntry->d_inode->i_mtime; local_size = direntry->d_inode->i_size; if (cifs_sb->tcon->ses->capabilities & CAP_UNIX) { rc = cifs_get_inode_info_unix(&direntry->d_inode, full_path, direntry->d_sb,xid); if (rc) { cFYI(1, ("error on getting revalidate info %d", rc)); /* if (rc != -ENOENT) rc = 0; */ /* BB should we cache info on certain errors? */ } } else { rc = cifs_get_inode_info(&direntry->d_inode, full_path, NULL, direntry->d_sb,xid); if (rc) { cFYI(1, ("error on getting revalidate info %d", rc)); /* if (rc != -ENOENT) rc = 0; */ /* BB should we cache info on certain errors? */ } } /* should we remap certain errors, access denied?, to zero */ /* if not oplocked, we invalidate inode pages if mtime or file size had changed on server */ if (timespec_equal(&local_mtime,&direntry->d_inode->i_mtime) && (local_size == direntry->d_inode->i_size)) { cFYI(1, ("cifs_revalidate - inode unchanged")); } else { /* file may have changed on server */ if (cifsInode->clientCanCacheRead) { /* no need to invalidate inode pages since we were the only ones who could have modified the file and the server copy is staler than ours */ } else { invalidate_inode = TRUE; } } /* can not grab this sem since kernel filesys locking documentation indicates i_mutex may be taken by the kernel on lookup and rename which could deadlock if we grab the i_mutex here as well */ /* mutex_lock(&direntry->d_inode->i_mutex);*/ /* need to write out dirty pages here */ if (direntry->d_inode->i_mapping) { /* do we need to lock inode until after invalidate completes below? */ filemap_fdatawrite(direntry->d_inode->i_mapping); } if (invalidate_inode) { /* shrink_dcache not necessary now that cifs dentry ops are exported for negative dentries */ /* if(S_ISDIR(direntry->d_inode->i_mode)) shrink_dcache_parent(direntry); */ if (S_ISREG(direntry->d_inode->i_mode)) { if (direntry->d_inode->i_mapping) filemap_fdatawait(direntry->d_inode->i_mapping); /* may eventually have to do this for open files too */ if (list_empty(&(cifsInode->openFileList))) { /* changed on server - flush read ahead pages */ cFYI(1, ("Invalidating read ahead data on " "closed file")); invalidate_remote_inode(direntry->d_inode); } } } /* mutex_unlock(&direntry->d_inode->i_mutex); */ kfree(full_path); FreeXid(xid); return rc; } #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0) int cifs_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat) { int err = cifs_revalidate(dentry); if (!err) { generic_fillattr(dentry->d_inode, stat); stat->blksize = CIFS_MAX_MSGSIZE; } return err; } #endif static int cifs_truncate_page(struct address_space *mapping, loff_t from) { #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0) pgoff_t index = from >> PAGE_CACHE_SHIFT; #else unsigned long index = from >> PAGE_CACHE_SHIFT; #endif unsigned offset = from & (PAGE_CACHE_SIZE - 1); struct page *page; char *kaddr; int rc = 0; page = grab_cache_page(mapping, index); if (!page) return -ENOMEM; kaddr = kmap_atomic(page, KM_USER0); memset(kaddr + offset, 0, PAGE_CACHE_SIZE - offset); flush_dcache_page(page); kunmap_atomic(kaddr, KM_USER0); unlock_page(page); page_cache_release(page); return rc; } #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 0) static int cifs_vmtruncate(struct inode * inode, loff_t offset) { struct address_space *mapping = inode->i_mapping; unsigned long limit; spin_lock(&inode->i_lock); if (inode->i_size < offset) goto do_expand; /* * truncation of in-use swapfiles is disallowed - it would cause * subsequent swapout to scribble on the now-freed blocks. */ if (IS_SWAPFILE(inode)) { spin_unlock(&inode->i_lock); goto out_busy; } i_size_write(inode, offset); spin_unlock(&inode->i_lock); /* * unmap_mapping_range is called twice, first simply for efficiency * so that truncate_inode_pages does fewer single-page unmaps. However * after this first call, and before truncate_inode_pages finishes, * it is possible for private pages to be COWed, which remain after * truncate_inode_pages finishes, hence the second unmap_mapping_range * call must be made for correctness. */ unmap_mapping_range(mapping, offset + PAGE_SIZE - 1, 0, 1); truncate_inode_pages(mapping, offset); unmap_mapping_range(mapping, offset + PAGE_SIZE - 1, 0, 1); goto out_truncate; do_expand: limit = current->signal->rlim[RLIMIT_FSIZE].rlim_cur; if (limit != RLIM_INFINITY && offset > limit) { spin_unlock(&inode->i_lock); goto out_sig; } if (offset > inode->i_sb->s_maxbytes) { spin_unlock(&inode->i_lock); goto out_big; } i_size_write(inode, offset); spin_unlock(&inode->i_lock); out_truncate: if (inode->i_op && inode->i_op->truncate) inode->i_op->truncate(inode); return 0; out_sig: send_sig(SIGXFSZ, current, 0); out_big: return -EFBIG; out_busy: return -ETXTBSY; } #endif int cifs_setattr(struct dentry *direntry, struct iattr *attrs) { int xid; struct cifs_sb_info *cifs_sb; struct cifsTconInfo *pTcon; char *full_path = NULL; int rc = -EACCES; struct cifsFileInfo *open_file = NULL; FILE_BASIC_INFO time_buf; int set_time = FALSE; int set_dosattr = FALSE; __u64 mode = 0xFFFFFFFFFFFFFFFFULL; __u64 uid = 0xFFFFFFFFFFFFFFFFULL; __u64 gid = 0xFFFFFFFFFFFFFFFFULL; struct cifsInodeInfo *cifsInode; xid = GetXid(); cFYI(1, ("setattr on file %s attrs->iavalid 0x%x", direntry->d_name.name, attrs->ia_valid)); cifs_sb = CIFS_SB(direntry->d_inode->i_sb); pTcon = cifs_sb->tcon; if ((cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_PERM) == 0) { /* check if we have permission to change attrs */ rc = inode_change_ok(direntry->d_inode, attrs); if(rc < 0) { FreeXid(xid); return rc; } else rc = 0; } full_path = build_path_from_dentry(direntry); if (full_path == NULL) { FreeXid(xid); return -ENOMEM; } cifsInode = CIFS_I(direntry->d_inode); /* BB check if we need to refresh inode from server now ? BB */ /* need to flush data before changing file size on server */ #if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 15) filemap_write_and_wait(direntry->d_inode->i_mapping); #else filemap_fdatawrite(direntry->d_inode->i_mapping); filemap_fdatawait(direntry->d_inode->i_mapping); #endif if (attrs->ia_valid & ATTR_SIZE) { /* To avoid spurious oplock breaks from server, in the case of inodes that we already have open, avoid doing path based setting of file size if we can do it by handle. This keeps our caching token (oplock) and avoids timeouts when the local oplock break takes longer to flush writebehind data than the SMB timeout for the SetPathInfo request would allow */ open_file = find_writable_file(cifsInode); if (open_file) { __u16 nfid = open_file->netfid; __u32 npid = open_file->pid; rc = CIFSSMBSetFileSize(xid, pTcon, attrs->ia_size, nfid, npid, FALSE); atomic_dec(&open_file->wrtPending); cFYI(1,("SetFSize for attrs rc = %d", rc)); if((rc == -EINVAL) || (rc == -EOPNOTSUPP)) { int bytes_written; rc = CIFSSMBWrite(xid, pTcon, nfid, 0, attrs->ia_size, &bytes_written, NULL, NULL, 1 /* 45 seconds */); cFYI(1,("Wrt seteof rc %d", rc)); } } else rc = -EINVAL; if (rc != 0) { /* Set file size by pathname rather than by handle either because no valid, writeable file handle for it was found or because there was an error setting it by handle */ rc = CIFSSMBSetEOF(xid, pTcon, full_path, attrs->ia_size, FALSE, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); cFYI(1, ("SetEOF by path (setattrs) rc = %d", rc)); if((rc == -EINVAL) || (rc == -EOPNOTSUPP)) { __u16 netfid; int oplock = FALSE; rc = SMBLegacyOpen(xid, pTcon, full_path, FILE_OPEN, SYNCHRONIZE | FILE_WRITE_ATTRIBUTES, CREATE_NOT_DIR, &netfid, &oplock, NULL, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); if (rc==0) { int bytes_written; rc = CIFSSMBWrite(xid, pTcon, netfid, 0, attrs->ia_size, &bytes_written, NULL, NULL, 1 /* 45 sec */); cFYI(1,("wrt seteof rc %d",rc)); CIFSSMBClose(xid, pTcon, netfid); } } } /* Server is ok setting allocation size implicitly - no need to call: CIFSSMBSetEOF(xid, pTcon, full_path, attrs->ia_size, TRUE, cifs_sb->local_nls); */ if (rc == 0) { #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 0) rc = cifs_vmtruncate(direntry->d_inode, attrs->ia_size); #else rc = vmtruncate(direntry->d_inode, attrs->ia_size); #endif cifs_truncate_page(direntry->d_inode->i_mapping, direntry->d_inode->i_size); } else goto cifs_setattr_exit; } if (attrs->ia_valid & ATTR_UID) { cFYI(1, ("UID changed to %d", attrs->ia_uid)); uid = attrs->ia_uid; } if (attrs->ia_valid & ATTR_GID) { cFYI(1, ("GID changed to %d", attrs->ia_gid)); gid = attrs->ia_gid; } time_buf.Attributes = 0; if (attrs->ia_valid & ATTR_MODE) { cFYI(1, ("Mode changed to 0x%x", attrs->ia_mode)); mode = attrs->ia_mode; } if ((cifs_sb->tcon->ses->capabilities & CAP_UNIX) && (attrs->ia_valid & (ATTR_MODE | ATTR_GID | ATTR_UID))) rc = CIFSSMBUnixSetPerms(xid, pTcon, full_path, mode, uid, gid, 0 /* dev_t */, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); else if (attrs->ia_valid & ATTR_MODE) { rc = 0; if ((mode & S_IWUGO) == 0) /* not writeable */ { if ((cifsInode->cifsAttrs & ATTR_READONLY) == 0) { set_dosattr = TRUE; time_buf.Attributes = cpu_to_le32(cifsInode->cifsAttrs | ATTR_READONLY); } } else if (cifsInode->cifsAttrs & ATTR_READONLY) { /* If file is readonly on server, we would not be able to write to it - so if any write bit is enabled for user or group or other we need to at least try to remove r/o dos attr */ set_dosattr = TRUE; time_buf.Attributes = cpu_to_le32(cifsInode->cifsAttrs & (~ATTR_READONLY)); /* Windows ignores set to zero */ if(time_buf.Attributes == 0) time_buf.Attributes |= cpu_to_le32(ATTR_NORMAL); } /* BB to be implemented - via Windows security descriptors or streams */ /* CIFSSMBWinSetPerms(xid, pTcon, full_path, mode, uid, gid, cifs_sb->local_nls); */ } if (attrs->ia_valid & ATTR_ATIME) { set_time = TRUE; time_buf.LastAccessTime = cpu_to_le64(cifs_UnixTimeToNT(attrs->ia_atime)); } else time_buf.LastAccessTime = 0; if (attrs->ia_valid & ATTR_MTIME) { set_time = TRUE; time_buf.LastWriteTime = cpu_to_le64(cifs_UnixTimeToNT(attrs->ia_mtime)); } else time_buf.LastWriteTime = 0; /* Do not set ctime explicitly unless other time stamps are changed explicitly (i.e. by utime() since we would then have a mix of client and server times */ if (set_time && (attrs->ia_valid & ATTR_CTIME)) { set_time = TRUE; /* Although Samba throws this field away it may be useful to Windows - but we do not want to set ctime unless some other timestamp is changing */ cFYI(1, ("CIFS - CTIME changed")); time_buf.ChangeTime = cpu_to_le64(cifs_UnixTimeToNT(attrs->ia_ctime)); } else time_buf.ChangeTime = 0; if (set_time || set_dosattr) { time_buf.CreationTime = 0; /* do not change */ /* In the future we should experiment - try setting timestamps via Handle (SetFileInfo) instead of by path */ if (!(pTcon->ses->flags & CIFS_SES_NT4)) rc = CIFSSMBSetTimes(xid, pTcon, full_path, &time_buf, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); else rc = -EOPNOTSUPP; if (rc == -EOPNOTSUPP) { int oplock = FALSE; __u16 netfid; cFYI(1, ("calling SetFileInfo since SetPathInfo for " "times not supported by this server")); /* BB we could scan to see if we already have it open and pass in pid of opener to function */ rc = CIFSSMBOpen(xid, pTcon, full_path, FILE_OPEN, SYNCHRONIZE | FILE_WRITE_ATTRIBUTES, CREATE_NOT_DIR, &netfid, &oplock, NULL, cifs_sb->local_nls, cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR); if (rc==0) { rc = CIFSSMBSetFileTimes(xid, pTcon, &time_buf, netfid); CIFSSMBClose(xid, pTcon, netfid); } else { /* BB For even older servers we could convert time_buf into old DOS style which uses two second granularity */ /* rc = CIFSSMBSetTimesLegacy(xid, pTcon, full_path, &time_buf, cifs_sb->local_nls); */ } } /* Even if error on time set, no sense failing the call if the server would set the time to a reasonable value anyway, and this check ensures that we are not being called from sys_utimes in which case we ought to fail the call back to the user when the server rejects the call */ if((rc) && (attrs->ia_valid & (ATTR_MODE | ATTR_GID | ATTR_UID | ATTR_SIZE))) rc = 0; } /* do not need local check to inode_check_ok since the server does that */ if (!rc) rc = inode_setattr(direntry->d_inode, attrs); cifs_setattr_exit: kfree(full_path); FreeXid(xid); return rc; } #if 0 void cifs_delete_inode(struct inode *inode) { cFYI(1, ("In cifs_delete_inode, inode = 0x%p", inode)); /* may have to add back in if and when safe distributed caching of directories added e.g. via FindNotify */ } #endif
30.668376
91
0.670011
[ "object" ]
9aef2081c760a02cb5d7cc0f5e345a09ad576018
11,727
c
C
components/bt/esp_ble_mesh/mesh_models/server/state_binding.c
kzyapkov/esp-idf
625bd5eb1806809ff3cc010ee20d1f750aa778a1
[ "Apache-2.0" ]
5
2020-07-13T05:38:29.000Z
2021-09-17T09:58:13.000Z
components/bt/esp_ble_mesh/mesh_models/server/state_binding.c
kzyapkov/esp-idf
625bd5eb1806809ff3cc010ee20d1f750aa778a1
[ "Apache-2.0" ]
2
2020-01-03T10:29:38.000Z
2020-04-20T10:39:40.000Z
components/bt/esp_ble_mesh/mesh_models/server/state_binding.c
kzyapkov/esp-idf
625bd5eb1806809ff3cc010ee20d1f750aa778a1
[ "Apache-2.0" ]
1
2020-11-14T04:33:28.000Z
2020-11-14T04:33:28.000Z
/* Bluetooth: Mesh Generic OnOff, Generic Level, Lighting & Vendor Models * * Copyright (c) 2018 Vikrant More * Additional Copyright (c) 2018 Espressif Systems (Shanghai) PTE LTD * * SPDX-License-Identifier: Apache-2.0 */ #include <errno.h> #include "mesh_common.h" #include "model_opcode.h" #include "state_binding.h" #include "state_transition.h" #define MINDIFF (2.25e-308) static float bt_mesh_sqrt(float square) { float root = 0.0, last = 0.0, diff = 0.0; root = square / 3.0; diff = 1; if (square <= 0) { return 0; } do { last = root; root = (root + square / root) / 2.0; diff = root - last; } while (diff > MINDIFF || diff < -MINDIFF); return root; } static s32_t bt_mesh_ceiling(float num) { s32_t inum = (s32_t)num; if (num == (float)inum) { return inum; } return inum + 1; } u16_t bt_mesh_convert_lightness_actual_to_linear(u16_t actual) { float tmp = ((float) actual / UINT16_MAX); return bt_mesh_ceiling(UINT16_MAX * tmp * tmp); } u16_t bt_mesh_convert_lightness_linear_to_actual(u16_t linear) { return (u16_t) (UINT16_MAX * bt_mesh_sqrt(((float) linear / UINT16_MAX))); } s16_t bt_mesh_convert_temperature_to_gen_level(u16_t temp, u16_t min, u16_t max) { float tmp = (temp - min) * UINT16_MAX / (max - min); return (s16_t) (tmp + INT16_MIN); } u16_t bt_mesh_covert_gen_level_to_temperature(s16_t level, u16_t min, u16_t max) { float diff = (float) (max - min) / UINT16_MAX; u16_t tmp = (u16_t) ((level - INT16_MIN) * diff); return (u16_t) (min + tmp); } s16_t bt_mesh_convert_hue_to_level(u16_t hue) { return (s16_t) (hue + INT16_MIN); } u16_t bt_mesh_convert_level_to_hue(s16_t level) { return (u16_t) (level - INT16_MIN); } s16_t bt_mesh_convert_saturation_to_level(u16_t saturation) { return (s16_t) (saturation + INT16_MIN); } u16_t bt_mesh_convert_level_to_saturation(s16_t level) { return (u16_t) (level - INT16_MIN); } int bt_mesh_update_binding_state(struct bt_mesh_model *model, bt_mesh_server_state_type_t type, bt_mesh_server_state_value_t *value) { if (model == NULL || model->user_data == NULL || value == NULL || type > BIND_STATE_MAX) { BT_ERR("%s, Invalid parameter", __func__); return -EINVAL; } switch (type) { case GENERIC_ONOFF_STATE: { if (model->id != BLE_MESH_MODEL_ID_GEN_ONOFF_SRV) { BT_ERR("%s, Not a Generic OnOff Server Model, id 0x%04x", __func__, model->id); return -EINVAL; } struct bt_mesh_gen_onoff_srv *srv = model->user_data; bt_mesh_server_stop_transition(&srv->transition); srv->state.onoff = value->gen_onoff.onoff; gen_onoff_publish(model); break; } case GENERIC_LEVEL_STATE: { if (model->id != BLE_MESH_MODEL_ID_GEN_LEVEL_SRV) { BT_ERR("%s, Not a Generic Level Server Model, id 0x%04x", __func__, model->id); return -EINVAL; } struct bt_mesh_gen_level_srv *srv = model->user_data; bt_mesh_server_stop_transition(&srv->transition); srv->state.level = value->gen_level.level; gen_level_publish(model); break; } case GENERIC_ONPOWERUP_STATE: { if (model->id != BLE_MESH_MODEL_ID_GEN_POWER_ONOFF_SRV) { BT_ERR("%s, Not a Generic Power OnOff Server Model, id 0x%04x", __func__, model->id); return -EINVAL; } struct bt_mesh_gen_power_onoff_srv *srv = model->user_data; if (srv->state == NULL) { BT_ERR("%s, Invalid Generic Power OnOff Server state", __func__); return -EINVAL; } srv->state->onpowerup = value->gen_onpowerup.onpowerup; gen_onpowerup_publish(model); break; } case GENERIC_POWER_ACTUAL_STATE: { if (model->id != BLE_MESH_MODEL_ID_GEN_POWER_LEVEL_SRV) { BT_ERR("%s, Not a Generic Power Level Server Model, id 0x%04x", __func__, model->id); return -EINVAL; } struct bt_mesh_gen_power_level_srv *srv = model->user_data; if (srv->state == NULL) { BT_ERR("%s, Invalid Generic Power Level Server state", __func__); return -EINVAL; } bt_mesh_server_stop_transition(&srv->transition); srv->state->power_actual = value->gen_power_actual.power; /** * Whenever the Generic Power Actual state is changed to a non-zero value * as a result of a non-transactional message or a completed sequence of * transactional messages, the value of the Generic Power Last state shall * be set to the value of the Generic Power Actual state. */ if (srv->state->power_actual) { srv->state->power_last = srv->state->power_actual; } gen_power_level_publish(model, BLE_MESH_MODEL_OP_GEN_POWER_LEVEL_STATUS); break; } case LIGHT_LIGHTNESS_ACTUAL_STATE: { if (model->id != BLE_MESH_MODEL_ID_LIGHT_LIGHTNESS_SRV) { BT_ERR("%s, Not a Light Lightness Server Model, id 0x%04x", __func__, model->id); return -EINVAL; } struct bt_mesh_light_lightness_srv *srv = model->user_data; if (srv->state == NULL) { BT_ERR("%s, Invalid Light Lightness Server state", __func__); return -EINVAL; } bt_mesh_server_stop_transition(&srv->actual_transition); srv->state->lightness_actual = value->light_lightness_actual.lightness; /** * Whenever the Light Lightness Actual state is changed with a non-transactional * message or a completed sequence of transactional messages to a non-zero value, * the value of the Light Lightness Last shall be set to the value of the Light * Lightness Actual. */ if (srv->state->lightness_actual) { srv->state->lightness_last = srv->state->lightness_actual; } light_lightness_publish(model, BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_STATUS); break; } case LIGHT_LIGHTNESS_LINEAR_STATE: { if (model->id != BLE_MESH_MODEL_ID_LIGHT_LIGHTNESS_SRV) { BT_ERR("%s, Not a Light Lightness Server Model, id 0x%04x", __func__, model->id); return -EINVAL; } struct bt_mesh_light_lightness_srv *srv = model->user_data; if (srv->state == NULL) { BT_ERR("%s, Invalid Light Lightness Server state", __func__); return -EINVAL; } bt_mesh_server_stop_transition(&srv->linear_transition); srv->state->lightness_linear = value->light_lightness_linear.lightness; light_lightness_publish(model, BLE_MESH_MODEL_OP_LIGHT_LIGHTNESS_LINEAR_STATUS); break; } case LIGHT_CTL_LIGHTNESS_STATE: { if (model->id != BLE_MESH_MODEL_ID_LIGHT_CTL_SRV) { BT_ERR("%s, Not a Light CTL Server Model, id 0x%04x", __func__, model->id); return -EINVAL; } struct bt_mesh_light_ctl_srv *srv = model->user_data; if (srv->state == NULL) { BT_ERR("%s, Invalid Light CTL Server state", __func__); return -EINVAL; } bt_mesh_server_stop_transition(&srv->transition); srv->state->lightness = value->light_ctl_lightness.lightness; light_ctl_publish(model, BLE_MESH_MODEL_OP_LIGHT_CTL_STATUS); break; } case LIGHT_CTL_TEMP_DELTA_UV_STATE: { if (model->id != BLE_MESH_MODEL_ID_LIGHT_CTL_TEMP_SRV) { BT_ERR("%s, Not a Light CTL Temperature Server Model, id 0x%04x", __func__, model->id); return -EINVAL; } struct bt_mesh_light_ctl_temp_srv *srv = model->user_data; if (srv->state == NULL) { BT_ERR("%s, Invalid Light CTL Temperature Server state", __func__); return -EINVAL; } bt_mesh_server_stop_transition(&srv->transition); srv->state->temperature = value->light_ctl_temp_delta_uv.temperature; srv->state->delta_uv = value->light_ctl_temp_delta_uv.delta_uv; light_ctl_publish(model, BLE_MESH_MODEL_OP_LIGHT_CTL_TEMPERATURE_STATUS); break; } case LIGHT_HSL_LIGHTNESS_STATE: { if (model->id != BLE_MESH_MODEL_ID_LIGHT_HSL_SRV) { BT_ERR("%s, Not a Light HSL Server Model, id 0x%04x", __func__, model->id); return -EINVAL; } struct bt_mesh_light_hsl_srv *srv = model->user_data; if (srv->state == NULL) { BT_ERR("%s, Invalid Light HSL Server state", __func__); return -EINVAL; } bt_mesh_server_stop_transition(&srv->transition); srv->state->lightness = value->light_hsl_lightness.lightness; light_hsl_publish(model, BLE_MESH_MODEL_OP_LIGHT_HSL_STATUS); break; } case LIGHT_HSL_HUE_STATE: { if (model->id != BLE_MESH_MODEL_ID_LIGHT_HSL_HUE_SRV) { BT_ERR("%s, Not a Light HSL Hue Server Model, id 0x%04x", __func__, model->id); return -EINVAL; } struct bt_mesh_light_hsl_hue_srv *srv = model->user_data; if (srv->state == NULL) { BT_ERR("%s, Invalid Light HSL Hue Server state", __func__); return -EINVAL; } bt_mesh_server_stop_transition(&srv->transition); srv->state->hue = value->light_hsl_hue.hue; light_hsl_publish(model, BLE_MESH_MODEL_OP_LIGHT_HSL_HUE_STATUS); break; } case LIGHT_HSL_SATURATION_STATE: { if (model->id != BLE_MESH_MODEL_ID_LIGHT_HSL_SAT_SRV) { BT_ERR("%s, Not a Light HSL Saturation Server Model, id 0x%04x", __func__, model->id); return -EINVAL; } struct bt_mesh_light_hsl_sat_srv *srv = model->user_data; if (srv->state == NULL) { BT_ERR("%s, Invalid Light HSL Saturation Server state", __func__); return -EINVAL; } bt_mesh_server_stop_transition(&srv->transition); srv->state->saturation = value->light_hsl_saturation.saturation; light_hsl_publish(model, BLE_MESH_MODEL_OP_LIGHT_HSL_SATURATION_STATUS); break; } case LIGHT_XYL_LIGHTNESS_STATE: { if (model->id != BLE_MESH_MODEL_ID_LIGHT_XYL_SRV) { BT_ERR("%s, Not a Light xyL Server Model, id 0x%04x", __func__, model->id); return -EINVAL; } struct bt_mesh_light_xyl_srv *srv = model->user_data; if (srv->state == NULL) { BT_ERR("%s, Invalid Light xyL Server state", __func__); return -EINVAL; } bt_mesh_server_stop_transition(&srv->transition); srv->state->lightness = value->light_xyl_lightness.lightness; light_xyl_publish(model, BLE_MESH_MODEL_OP_LIGHT_XYL_STATUS); break; } case LIGHT_LC_LIGHT_ONOFF_STATE: { if (model->id != BLE_MESH_MODEL_ID_LIGHT_LC_SRV) { BT_ERR("%s, Not a Light LC Server Model, id 0x%04x", __func__, model->id); return -EINVAL; } struct bt_mesh_light_lc_srv *srv = model->user_data; if (srv->lc == NULL) { BT_ERR("%s, Invalid Light LC Server state", __func__); return -EINVAL; } bt_mesh_server_stop_transition(&srv->transition); srv->lc->state.light_onoff = value->light_lc_light_onoff.onoff; light_lc_publish(model, BLE_MESH_MODEL_OP_LIGHT_LC_LIGHT_ONOFF_STATUS); break; } default: BT_WARN("%s, Unknown binding state type 0x%02x", __func__, type); return -EINVAL; } return 0; }
34.289474
99
0.629743
[ "mesh", "model" ]
9af1050d08992205ce2b9a519b4e89dc05681c31
1,408
h
C
Source/URoboSim/Public/control_msgs/FollowJointTrajectoryResult.h
K4R-IAI/URoboSim
0b8769761ce77fe493f37e1ec488ed50d66402ec
[ "BSD-3-Clause" ]
1
2021-04-11T13:03:58.000Z
2021-04-11T13:03:58.000Z
Source/URoboSim/Public/control_msgs/FollowJointTrajectoryResult.h
artnie/URoboSim
0b8769761ce77fe493f37e1ec488ed50d66402ec
[ "BSD-3-Clause" ]
null
null
null
Source/URoboSim/Public/control_msgs/FollowJointTrajectoryResult.h
artnie/URoboSim
0b8769761ce77fe493f37e1ec488ed50d66402ec
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include "ROSBridgeMsg.h" namespace control_msgs { class FollowJointTrajectoryResult : public FROSBridgeMsg { int32 ErrorCode; public: FollowJointTrajectoryResult() { MsgType = "control_msgs/FollowJointTrajectoryResult"; } FollowJointTrajectoryResult ( int32 InErrorCode ): ErrorCode(InErrorCode) { MsgType = "control_msgs/FollowJointTrajectoryResult"; } ~FollowJointTrajectoryResult() override {} int32 GetErrorCode() const { return ErrorCode; } void SetErrorCode(int32 InErrorCode) { ErrorCode = InErrorCode; } virtual void FromJson(TSharedPtr<FJsonObject> JsonObject) override { ErrorCode = JsonObject->GetNumberField(TEXT("error_code")); } static FollowJointTrajectoryResult GetFromJson(TSharedPtr<FJsonObject> JsonObject) { FollowJointTrajectoryResult Result; Result.FromJson(JsonObject); return Result; } virtual TSharedPtr<FJsonObject> ToJsonObject() const override { TSharedPtr<FJsonObject> Object = MakeShareable<FJsonObject>(new FJsonObject()); Object->SetNumberField(TEXT("error_code"), ErrorCode); return Object; } virtual FString ToYamlString() const override { FString OutputString; TSharedRef< TJsonWriter<> > Writer = TJsonWriterFactory<>::Create(&OutputString); FJsonSerializer::Serialize(ToJsonObject().ToSharedRef(), Writer); return OutputString; } }; }
21.333333
84
0.740057
[ "object" ]
9af2ba6a82b9981e33b42bb19245b223ec60dc75
93,929
c
C
source/blender/editors/space_outliner/outliner_tools.c
noorbeast/blender
9dc69b3848b46f4fbf3daa3360a3b975f4e1565f
[ "Naumen", "Condor-1.1", "MS-PL" ]
2
2020-07-09T22:45:42.000Z
2020-07-10T06:28:03.000Z
source/blender/editors/space_outliner/outliner_tools.c
noorbeast/blender
9dc69b3848b46f4fbf3daa3360a3b975f4e1565f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
source/blender/editors/space_outliner/outliner_tools.c
noorbeast/blender
9dc69b3848b46f4fbf3daa3360a3b975f4e1565f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2004 Blender Foundation. * All rights reserved. */ /** \file * \ingroup spoutliner */ #include "MEM_guardedalloc.h" #include "CLG_log.h" #include "DNA_anim_types.h" #include "DNA_armature_types.h" #include "DNA_collection_types.h" #include "DNA_constraint_types.h" #include "DNA_gpencil_types.h" #include "DNA_hair_types.h" #include "DNA_light_types.h" #include "DNA_linestyle_types.h" #include "DNA_material_types.h" #include "DNA_mesh_types.h" #include "DNA_meta_types.h" #include "DNA_modifier_types.h" #include "DNA_object_types.h" #include "DNA_pointcloud_types.h" #include "DNA_scene_types.h" #include "DNA_sequence_types.h" #include "DNA_simulation_types.h" #include "DNA_volume_types.h" #include "DNA_world_types.h" #include "BLI_blenlib.h" #include "BLI_ghash.h" #include "BLI_utildefines.h" #include "BKE_anim_data.h" #include "BKE_animsys.h" #include "BKE_armature.h" #include "BKE_collection.h" #include "BKE_constraint.h" #include "BKE_context.h" #include "BKE_fcurve.h" #include "BKE_global.h" #include "BKE_idtype.h" #include "BKE_layer.h" #include "BKE_lib_id.h" #include "BKE_lib_override.h" #include "BKE_lib_query.h" #include "BKE_main.h" #include "BKE_object.h" #include "BKE_report.h" #include "BKE_scene.h" #include "BKE_screen.h" #include "DEG_depsgraph.h" #include "DEG_depsgraph_build.h" #include "ED_object.h" #include "ED_outliner.h" #include "ED_scene.h" #include "ED_screen.h" #include "ED_sequencer.h" #include "ED_undo.h" #include "WM_api.h" #include "WM_message.h" #include "WM_types.h" #include "UI_interface.h" #include "UI_resources.h" #include "UI_view2d.h" #include "RNA_access.h" #include "RNA_define.h" #include "RNA_enum_types.h" #include "SEQ_sequencer.h" #include "outliner_intern.h" static CLG_LogRef LOG = {"ed.outliner.tools"}; /* -------------------------------------------------------------------- */ /** \name ID/Library/Data Set/Un-link Utilities * \{ */ static void get_element_operation_type( TreeElement *te, int *scenelevel, int *objectlevel, int *idlevel, int *datalevel) { TreeStoreElem *tselem = TREESTORE(te); if (tselem->flag & TSE_SELECTED) { /* Layer collection points to collection ID. */ if (!ELEM(tselem->type, TSE_SOME_ID, TSE_LAYER_COLLECTION)) { if (*datalevel == 0) { *datalevel = tselem->type; } else if (*datalevel != tselem->type) { *datalevel = -1; } } else { const int idcode = (int)GS(tselem->id->name); bool is_standard_id = false; switch ((ID_Type)idcode) { case ID_SCE: *scenelevel = 1; break; case ID_OB: *objectlevel = 1; break; case ID_ME: case ID_CU: case ID_MB: case ID_LT: case ID_LA: case ID_AR: case ID_CA: case ID_SPK: case ID_MA: case ID_TE: case ID_IP: case ID_IM: case ID_SO: case ID_KE: case ID_WO: case ID_AC: case ID_TXT: case ID_GR: case ID_LS: case ID_LI: case ID_VF: case ID_NT: case ID_BR: case ID_PA: case ID_GD: case ID_MC: case ID_MSK: case ID_PAL: case ID_PC: case ID_CF: case ID_WS: case ID_LP: case ID_HA: case ID_PT: case ID_VO: case ID_SIM: is_standard_id = true; break; case ID_WM: case ID_SCR: /* Those are ignored here. */ /* Note: while Screens should be manageable here, deleting a screen used by a workspace * will cause crashes when trying to use that workspace, so for now let's play minimal, * safe change. */ break; } if (idcode == ID_NLA) { /* Fake one, not an actual ID type... */ is_standard_id = true; } if (is_standard_id) { if (*idlevel == 0) { *idlevel = idcode; } else if (*idlevel != idcode) { *idlevel = -1; } if (ELEM(*datalevel, TSE_VIEW_COLLECTION_BASE, TSE_SCENE_COLLECTION_BASE)) { *datalevel = 0; } } } } } static TreeElement *get_target_element(SpaceOutliner *space_outliner) { TreeElement *te = outliner_find_element_with_flag(&space_outliner->tree, TSE_ACTIVE); BLI_assert(te); return te; } static void unlink_action_fn(bContext *C, ReportList *UNUSED(reports), Scene *UNUSED(scene), TreeElement *UNUSED(te), TreeStoreElem *tsep, TreeStoreElem *UNUSED(tselem), void *UNUSED(user_data)) { /* just set action to NULL */ BKE_animdata_set_action(CTX_wm_reports(C), tsep->id, NULL); } static void unlink_material_fn(bContext *UNUSED(C), ReportList *UNUSED(reports), Scene *UNUSED(scene), TreeElement *te, TreeStoreElem *tsep, TreeStoreElem *UNUSED(tselem), void *UNUSED(user_data)) { Material **matar = NULL; int a, totcol = 0; if (GS(tsep->id->name) == ID_OB) { Object *ob = (Object *)tsep->id; totcol = ob->totcol; matar = ob->mat; } else if (GS(tsep->id->name) == ID_ME) { Mesh *me = (Mesh *)tsep->id; totcol = me->totcol; matar = me->mat; } else if (GS(tsep->id->name) == ID_CU) { Curve *cu = (Curve *)tsep->id; totcol = cu->totcol; matar = cu->mat; } else if (GS(tsep->id->name) == ID_MB) { MetaBall *mb = (MetaBall *)tsep->id; totcol = mb->totcol; matar = mb->mat; } else if (GS(tsep->id->name) == ID_HA) { Hair *hair = (Hair *)tsep->id; totcol = hair->totcol; matar = hair->mat; } else if (GS(tsep->id->name) == ID_PT) { PointCloud *pointcloud = (PointCloud *)tsep->id; totcol = pointcloud->totcol; matar = pointcloud->mat; } else if (GS(tsep->id->name) == ID_VO) { Volume *volume = (Volume *)tsep->id; totcol = volume->totcol; matar = volume->mat; } else { BLI_assert(0); } if (LIKELY(matar != NULL)) { for (a = 0; a < totcol; a++) { if (a == te->index && matar[a]) { id_us_min(&matar[a]->id); matar[a] = NULL; } } } } static void unlink_texture_fn(bContext *UNUSED(C), ReportList *UNUSED(reports), Scene *UNUSED(scene), TreeElement *te, TreeStoreElem *tsep, TreeStoreElem *UNUSED(tselem), void *UNUSED(user_data)) { MTex **mtex = NULL; int a; if (GS(tsep->id->name) == ID_LS) { FreestyleLineStyle *ls = (FreestyleLineStyle *)tsep->id; mtex = ls->mtex; } else { return; } for (a = 0; a < MAX_MTEX; a++) { if (a == te->index && mtex[a]) { if (mtex[a]->tex) { id_us_min(&mtex[a]->tex->id); mtex[a]->tex = NULL; } } } } static void unlink_collection_fn(bContext *C, ReportList *UNUSED(reports), Scene *UNUSED(scene), TreeElement *UNUSED(te), TreeStoreElem *tsep, TreeStoreElem *tselem, void *UNUSED(user_data)) { Main *bmain = CTX_data_main(C); Collection *collection = (Collection *)tselem->id; if (tsep) { if (GS(tsep->id->name) == ID_OB) { Object *ob = (Object *)tsep->id; ob->instance_collection = NULL; DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM); DEG_relations_tag_update(bmain); } else if (GS(tsep->id->name) == ID_GR) { Collection *parent = (Collection *)tsep->id; id_fake_user_set(&collection->id); BKE_collection_child_remove(bmain, parent, collection); DEG_id_tag_update(&parent->id, ID_RECALC_COPY_ON_WRITE); DEG_relations_tag_update(bmain); } else if (GS(tsep->id->name) == ID_SCE) { Scene *scene = (Scene *)tsep->id; Collection *parent = scene->master_collection; id_fake_user_set(&collection->id); BKE_collection_child_remove(bmain, parent, collection); DEG_id_tag_update(&scene->id, ID_RECALC_COPY_ON_WRITE); DEG_relations_tag_update(bmain); } } } static void unlink_object_fn(bContext *C, ReportList *UNUSED(reports), Scene *UNUSED(scene), TreeElement *te, TreeStoreElem *tsep, TreeStoreElem *tselem, void *UNUSED(user_data)) { if (tsep && tsep->id) { Main *bmain = CTX_data_main(C); Object *ob = (Object *)tselem->id; if (GS(tsep->id->name) == ID_OB) { /* Parented objects need to find which collection to unlink from. */ TreeElement *te_parent = te->parent; while (tsep && GS(tsep->id->name) == ID_OB) { te_parent = te_parent->parent; tsep = te_parent ? TREESTORE(te_parent) : NULL; } } if (tsep && tsep->id) { if (GS(tsep->id->name) == ID_GR) { Collection *parent = (Collection *)tsep->id; BKE_collection_object_remove(bmain, parent, ob, true); DEG_id_tag_update(&parent->id, ID_RECALC_COPY_ON_WRITE); DEG_relations_tag_update(bmain); } else if (GS(tsep->id->name) == ID_SCE) { Scene *scene = (Scene *)tsep->id; Collection *parent = scene->master_collection; BKE_collection_object_remove(bmain, parent, ob, true); DEG_id_tag_update(&scene->id, ID_RECALC_COPY_ON_WRITE); DEG_relations_tag_update(bmain); } } } } static void unlink_world_fn(bContext *UNUSED(C), ReportList *UNUSED(reports), Scene *UNUSED(scene), TreeElement *UNUSED(te), TreeStoreElem *tsep, TreeStoreElem *tselem, void *UNUSED(user_data)) { Scene *parscene = (Scene *)tsep->id; World *wo = (World *)tselem->id; /* need to use parent scene not just scene, otherwise may end up getting wrong one */ id_us_min(&wo->id); parscene->world = NULL; } static void outliner_do_libdata_operation(bContext *C, ReportList *reports, Scene *scene, SpaceOutliner *space_outliner, ListBase *lb, outliner_operation_fn operation_fn, void *user_data) { LISTBASE_FOREACH (TreeElement *, te, lb) { TreeStoreElem *tselem = TREESTORE(te); if (tselem->flag & TSE_SELECTED) { if (((tselem->type == TSE_SOME_ID) && (te->idcode != 0)) || tselem->type == TSE_LAYER_COLLECTION) { TreeStoreElem *tsep = te->parent ? TREESTORE(te->parent) : NULL; operation_fn(C, reports, scene, te, tsep, tselem, user_data); } } if (TSELEM_OPEN(tselem, space_outliner)) { outliner_do_libdata_operation( C, reports, scene, space_outliner, &te->subtree, operation_fn, user_data); } } } /** \} */ /* -------------------------------------------------------------------- */ /** \name Scene Menu Operator * \{ */ typedef enum eOutliner_PropSceneOps { OL_SCENE_OP_DELETE = 1, } eOutliner_PropSceneOps; static const EnumPropertyItem prop_scene_op_types[] = { {OL_SCENE_OP_DELETE, "DELETE", ICON_X, "Delete", ""}, {0, NULL, 0, NULL, NULL}, }; static bool outliner_do_scene_operation( bContext *C, eOutliner_PropSceneOps event, ListBase *lb, bool (*operation_fn)(bContext *, eOutliner_PropSceneOps, TreeElement *, TreeStoreElem *)) { bool success = false; LISTBASE_FOREACH (TreeElement *, te, lb) { TreeStoreElem *tselem = TREESTORE(te); if (tselem->flag & TSE_SELECTED) { if (operation_fn(C, event, te, tselem)) { success = true; } } } return success; } static bool scene_fn(bContext *C, eOutliner_PropSceneOps event, TreeElement *UNUSED(te), TreeStoreElem *tselem) { Scene *scene = (Scene *)tselem->id; if (event == OL_SCENE_OP_DELETE) { if (ED_scene_delete(C, CTX_data_main(C), scene)) { WM_event_add_notifier(C, NC_SCENE | NA_REMOVED, scene); } else { return false; } } return true; } static int outliner_scene_operation_exec(bContext *C, wmOperator *op) { SpaceOutliner *space_outliner = CTX_wm_space_outliner(C); const eOutliner_PropSceneOps event = RNA_enum_get(op->ptr, "type"); if (outliner_do_scene_operation(C, event, &space_outliner->tree, scene_fn) == false) { return OPERATOR_CANCELLED; } if (event == OL_SCENE_OP_DELETE) { outliner_cleanup_tree(space_outliner); ED_undo_push(C, "Delete Scene(s)"); } else { BLI_assert(0); return OPERATOR_CANCELLED; } return OPERATOR_FINISHED; } void OUTLINER_OT_scene_operation(wmOperatorType *ot) { /* identifiers */ ot->name = "Outliner Scene Operation"; ot->idname = "OUTLINER_OT_scene_operation"; ot->description = "Context menu for scene operations"; /* callbacks */ ot->invoke = WM_menu_invoke; ot->exec = outliner_scene_operation_exec; ot->poll = ED_operator_outliner_active; ot->flag = 0; ot->prop = RNA_def_enum(ot->srna, "type", prop_scene_op_types, 0, "Scene Operation", ""); } /** \} */ /* -------------------------------------------------------------------- */ /** \name Search Utilities * \{ */ /** * Stores the parent and a child element of a merged icon-row icon for * the merged select popup menu. The sub-tree of the parent is searched and * the child is needed to only show elements of the same type in the popup. */ typedef struct MergedSearchData { TreeElement *parent_element; TreeElement *select_element; } MergedSearchData; static void merged_element_search_fn_recursive( const ListBase *tree, short tselem_type, short type, const char *str, uiSearchItems *items) { char name[64]; int iconid; LISTBASE_FOREACH (TreeElement *, te, tree) { TreeStoreElem *tselem = TREESTORE(te); if (tree_element_id_type_to_index(te) == type && tselem_type == tselem->type) { if (BLI_strcasestr(te->name, str)) { BLI_strncpy(name, te->name, 64); iconid = tree_element_get_icon(tselem, te).icon; /* Don't allow duplicate named items */ if (UI_search_items_find_index(items, name) == -1) { if (!UI_search_item_add(items, name, te, iconid, 0, 0)) { break; } } } } merged_element_search_fn_recursive(&te->subtree, tselem_type, type, str, items); } } /* Get a list of elements that match the search string */ static void merged_element_search_update_fn(const bContext *UNUSED(C), void *data, const char *str, uiSearchItems *items, const bool UNUSED(is_first)) { MergedSearchData *search_data = (MergedSearchData *)data; TreeElement *parent = search_data->parent_element; TreeElement *te = search_data->select_element; int type = tree_element_id_type_to_index(te); merged_element_search_fn_recursive(&parent->subtree, TREESTORE(te)->type, type, str, items); } /* Activate an element from the merged element search menu */ static void merged_element_search_exec_fn(struct bContext *C, void *UNUSED(arg1), void *element) { SpaceOutliner *space_outliner = CTX_wm_space_outliner(C); TreeElement *te = (TreeElement *)element; outliner_item_select(C, space_outliner, te, OL_ITEM_SELECT | OL_ITEM_ACTIVATE); ED_outliner_select_sync_from_outliner(C, space_outliner); } /** * Merged element search menu * Created on activation of a merged or aggregated icon-row icon. */ static uiBlock *merged_element_search_menu(bContext *C, ARegion *region, void *data) { static char search[64] = ""; uiBlock *block; uiBut *but; /* Clear search on each menu creation */ *search = '\0'; block = UI_block_begin(C, region, __func__, UI_EMBOSS); UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_MOVEMOUSE_QUIT | UI_BLOCK_SEARCH_MENU); UI_block_theme_style_set(block, UI_BLOCK_THEME_STYLE_POPUP); short menu_width = 10 * UI_UNIT_X; but = uiDefSearchBut( block, search, 0, ICON_VIEWZOOM, sizeof(search), 10, 10, menu_width, UI_UNIT_Y, 0, 0, ""); UI_but_func_search_set( but, NULL, merged_element_search_update_fn, data, NULL, merged_element_search_exec_fn, NULL); UI_but_flag_enable(but, UI_BUT_ACTIVATE_ON_INIT); /* Fake button to hold space for search items */ uiDefBut(block, UI_BTYPE_LABEL, 0, "", 10, 10 - UI_searchbox_size_y(), menu_width, UI_searchbox_size_y(), NULL, 0, 0, 0, 0, NULL); /* Center the menu on the cursor */ UI_block_bounds_set_popup(block, 6, (const int[2]){-(menu_width / 2), 0}); return block; } void merged_element_search_menu_invoke(bContext *C, TreeElement *parent_te, TreeElement *activate_te) { MergedSearchData *select_data = MEM_callocN(sizeof(MergedSearchData), "merge_search_data"); select_data->parent_element = parent_te; select_data->select_element = activate_te; UI_popup_block_invoke(C, merged_element_search_menu, select_data, MEM_freeN); } static void object_select_fn(bContext *C, ReportList *UNUSED(reports), Scene *UNUSED(scene), TreeElement *UNUSED(te), TreeStoreElem *UNUSED(tsep), TreeStoreElem *tselem, void *UNUSED(user_data)) { ViewLayer *view_layer = CTX_data_view_layer(C); Object *ob = (Object *)tselem->id; Base *base = BKE_view_layer_base_find(view_layer, ob); if (base) { ED_object_base_select(base, BA_SELECT); } } /** \} */ /* -------------------------------------------------------------------- */ /** \name Callbacks (Selection, Users & Library) Utilities * \{ */ static void object_select_hierarchy_fn(bContext *C, ReportList *UNUSED(reports), Scene *UNUSED(scene), TreeElement *te, TreeStoreElem *UNUSED(tsep), TreeStoreElem *UNUSED(tselem), void *UNUSED(user_data)) { /* Don't extend because this toggles, which is nice for Ctrl-Click but not for a menu item. * it's especially confusing when multiple items are selected since some toggle on/off. */ SpaceOutliner *space_outliner = CTX_wm_space_outliner(C); outliner_item_select( C, space_outliner, te, OL_ITEM_SELECT | OL_ITEM_ACTIVATE | OL_ITEM_RECURSIVE); } static void object_deselect_fn(bContext *C, ReportList *UNUSED(reports), Scene *UNUSED(scene), TreeElement *UNUSED(te), TreeStoreElem *UNUSED(tsep), TreeStoreElem *tselem, void *UNUSED(user_data)) { ViewLayer *view_layer = CTX_data_view_layer(C); Object *ob = (Object *)tselem->id; Base *base = BKE_view_layer_base_find(view_layer, ob); if (base) { base->flag &= ~BASE_SELECTED; } } static void outliner_object_delete_fn(bContext *C, ReportList *reports, Scene *scene, Object *ob) { if (ob) { Main *bmain = CTX_data_main(C); if (ob->id.tag & LIB_TAG_INDIRECT) { BKE_reportf( reports, RPT_WARNING, "Cannot delete indirectly linked object '%s'", ob->id.name + 2); return; } if (BKE_library_ID_is_indirectly_used(bmain, ob) && ID_REAL_USERS(ob) <= 1 && ID_EXTRA_USERS(ob) == 0) { BKE_reportf(reports, RPT_WARNING, "Cannot delete object '%s' from scene '%s', indirectly used objects need at " "least one user", ob->id.name + 2, scene->id.name + 2); return; } /* Check also library later. */ if ((ob->mode & OB_MODE_EDIT) && BKE_object_is_in_editmode(ob)) { ED_object_editmode_exit_ex(bmain, scene, ob, EM_FREEDATA); } BKE_id_delete(bmain, ob); } } static void id_local_fn(bContext *C, ReportList *UNUSED(reports), Scene *UNUSED(scene), TreeElement *UNUSED(te), TreeStoreElem *UNUSED(tsep), TreeStoreElem *tselem, void *UNUSED(user_data)) { if (ID_IS_LINKED(tselem->id) && (tselem->id->tag & LIB_TAG_EXTERN)) { Main *bmain = CTX_data_main(C); /* if the ID type has no special local function, * just clear the lib */ if (BKE_lib_id_make_local(bmain, tselem->id, false, 0) == false) { BKE_lib_id_clear_library_data(bmain, tselem->id); } else { BKE_main_id_clear_newpoins(bmain); } } else if (ID_IS_OVERRIDE_LIBRARY_REAL(tselem->id)) { BKE_lib_override_library_free(&tselem->id->override_library, true); } } static void object_proxy_to_override_convert_fn(bContext *C, ReportList *reports, Scene *UNUSED(scene), TreeElement *UNUSED(te), TreeStoreElem *UNUSED(tsep), TreeStoreElem *tselem, void *UNUSED(user_data)) { BLI_assert(TSE_IS_REAL_ID(tselem)); ID *id_proxy = tselem->id; BLI_assert(GS(id_proxy->name) == ID_OB); Object *ob_proxy = (Object *)id_proxy; Scene *scene = CTX_data_scene(C); if (ob_proxy->proxy == NULL) { return; } if (!BKE_lib_override_library_proxy_convert( CTX_data_main(C), scene, CTX_data_view_layer(C), ob_proxy)) { BKE_reportf( reports, RPT_ERROR_INVALID_INPUT, "Could not create a library override from proxy '%s' (might use already local data?)", ob_proxy->id.name + 2); return; } DEG_id_tag_update(&scene->id, ID_RECALC_BASE_FLAGS | ID_RECALC_COPY_ON_WRITE); WM_event_add_notifier(C, NC_WINDOW, NULL); } typedef struct OutlinerLibOverrideData { bool do_hierarchy; } OutlinerLibOverrideData; static void id_override_library_create_fn(bContext *C, ReportList *UNUSED(reports), Scene *UNUSED(scene), TreeElement *te, TreeStoreElem *UNUSED(tsep), TreeStoreElem *tselem, void *user_data) { BLI_assert(TSE_IS_REAL_ID(tselem)); ID *id_root = tselem->id; OutlinerLibOverrideData *data = user_data; const bool do_hierarchy = data->do_hierarchy; if (ID_IS_OVERRIDABLE_LIBRARY(id_root) || (ID_IS_LINKED(id_root) && do_hierarchy)) { Main *bmain = CTX_data_main(C); id_root->tag |= LIB_TAG_DOIT; /* For now, remap all local usages of linked ID to local override one here. */ ID *id_iter; FOREACH_MAIN_ID_BEGIN (bmain, id_iter) { if (ID_IS_LINKED(id_iter)) { id_iter->tag &= ~LIB_TAG_DOIT; } else { id_iter->tag |= LIB_TAG_DOIT; } } FOREACH_MAIN_ID_END; if (do_hierarchy) { /* Tag all linked parents in tree hierarchy to be also overridden. */ while ((te = te->parent) != NULL) { if (!TSE_IS_REAL_ID(te->store_elem)) { continue; } if (!ID_IS_LINKED(te->store_elem->id)) { break; } te->store_elem->id->tag |= LIB_TAG_DOIT; } BKE_lib_override_library_create( bmain, CTX_data_scene(C), CTX_data_view_layer(C), id_root, NULL); } else if (ID_IS_OVERRIDABLE_LIBRARY(id_root)) { BKE_lib_override_library_create_from_id(bmain, id_root, true); /* Cleanup. */ BKE_main_id_clear_newpoins(bmain); BKE_main_id_tag_all(bmain, LIB_TAG_DOIT, false); } } else { CLOG_WARN(&LOG, "Could not create library override for data block '%s'", id_root->name); } } static void id_override_library_reset_fn(bContext *C, ReportList *UNUSED(reports), Scene *UNUSED(scene), TreeElement *UNUSED(te), TreeStoreElem *UNUSED(tsep), TreeStoreElem *tselem, void *user_data) { BLI_assert(TSE_IS_REAL_ID(tselem)); ID *id_root = tselem->id; OutlinerLibOverrideData *data = user_data; const bool do_hierarchy = data->do_hierarchy; if (ID_IS_OVERRIDE_LIBRARY_REAL(id_root)) { Main *bmain = CTX_data_main(C); if (do_hierarchy) { BKE_lib_override_library_id_hierarchy_reset(bmain, id_root); } else { BKE_lib_override_library_id_reset(bmain, id_root); } WM_event_add_notifier(C, NC_WM | ND_DATACHANGED, NULL); WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, NULL); } else { CLOG_WARN(&LOG, "Could not reset library override of data block '%s'", id_root->name); } } static void id_override_library_resync_fn(bContext *C, ReportList *UNUSED(reports), Scene *scene, TreeElement *te, TreeStoreElem *UNUSED(tsep), TreeStoreElem *tselem, void *UNUSED(user_data)) { BLI_assert(TSE_IS_REAL_ID(tselem)); ID *id_root = tselem->id; if (ID_IS_OVERRIDE_LIBRARY_REAL(id_root)) { Main *bmain = CTX_data_main(C); id_root->tag |= LIB_TAG_DOIT; /* Tag all linked parents in tree hierarchy to be also overridden. */ while ((te = te->parent) != NULL) { if (!TSE_IS_REAL_ID(te->store_elem)) { continue; } if (!ID_IS_OVERRIDE_LIBRARY_REAL(te->store_elem->id)) { break; } te->store_elem->id->tag |= LIB_TAG_DOIT; } BKE_lib_override_library_resync(bmain, scene, CTX_data_view_layer(C), id_root); WM_event_add_notifier(C, NC_WINDOW, NULL); } else { CLOG_WARN(&LOG, "Could not resync library override of data block '%s'", id_root->name); } } static void id_override_library_delete_fn(bContext *C, ReportList *UNUSED(reports), Scene *UNUSED(scene), TreeElement *te, TreeStoreElem *UNUSED(tsep), TreeStoreElem *tselem, void *UNUSED(user_data)) { BLI_assert(TSE_IS_REAL_ID(tselem)); ID *id_root = tselem->id; if (ID_IS_OVERRIDE_LIBRARY_REAL(id_root)) { Main *bmain = CTX_data_main(C); id_root->tag |= LIB_TAG_DOIT; /* Tag all linked parents in tree hierarchy to be also overridden. */ while ((te = te->parent) != NULL) { if (!TSE_IS_REAL_ID(te->store_elem)) { continue; } if (!ID_IS_OVERRIDE_LIBRARY_REAL(te->store_elem->id)) { break; } te->store_elem->id->tag |= LIB_TAG_DOIT; } BKE_lib_override_library_delete(bmain, id_root); WM_event_add_notifier(C, NC_WINDOW, NULL); } else { CLOG_WARN(&LOG, "Could not delete library override of data block '%s'", id_root->name); } } static void id_fake_user_set_fn(bContext *UNUSED(C), ReportList *UNUSED(reports), Scene *UNUSED(scene), TreeElement *UNUSED(te), TreeStoreElem *UNUSED(tsep), TreeStoreElem *tselem, void *UNUSED(user_data)) { ID *id = tselem->id; id_fake_user_set(id); } static void id_fake_user_clear_fn(bContext *UNUSED(C), ReportList *UNUSED(reports), Scene *UNUSED(scene), TreeElement *UNUSED(te), TreeStoreElem *UNUSED(tsep), TreeStoreElem *tselem, void *UNUSED(user_data)) { ID *id = tselem->id; id_fake_user_clear(id); } static void id_select_linked_fn(bContext *C, ReportList *UNUSED(reports), Scene *UNUSED(scene), TreeElement *UNUSED(te), TreeStoreElem *UNUSED(tsep), TreeStoreElem *tselem, void *UNUSED(user_data)) { ID *id = tselem->id; ED_object_select_linked_by_id(C, id); } static void singleuser_action_fn(bContext *C, ReportList *UNUSED(reports), Scene *UNUSED(scene), TreeElement *te, TreeStoreElem *tsep, TreeStoreElem *tselem, void *UNUSED(user_data)) { /* This callback runs for all selected elements, some of which may not be actions which results * in a crash. */ if (te->idcode != ID_AC) { return; } ID *id = tselem->id; if (id) { IdAdtTemplate *iat = (IdAdtTemplate *)tsep->id; PointerRNA ptr = {NULL}; PropertyRNA *prop; RNA_pointer_create(&iat->id, &RNA_AnimData, iat->adt, &ptr); prop = RNA_struct_find_property(&ptr, "action"); id_single_user(C, id, &ptr, prop); } } static void singleuser_world_fn(bContext *C, ReportList *UNUSED(reports), Scene *UNUSED(scene), TreeElement *UNUSED(te), TreeStoreElem *tsep, TreeStoreElem *tselem, void *UNUSED(user_data)) { ID *id = tselem->id; /* need to use parent scene not just scene, otherwise may end up getting wrong one */ if (id) { Scene *parscene = (Scene *)tsep->id; PointerRNA ptr = {NULL}; PropertyRNA *prop; RNA_id_pointer_create(&parscene->id, &ptr); prop = RNA_struct_find_property(&ptr, "world"); id_single_user(C, id, &ptr, prop); } } /** * \param recurse_selected: Set to false for operations which are already * recursively operating on their children. */ void outliner_do_object_operation_ex(bContext *C, ReportList *reports, Scene *scene_act, SpaceOutliner *space_outliner, ListBase *lb, outliner_operation_fn operation_fn, void *user_data, bool recurse_selected) { LISTBASE_FOREACH (TreeElement *, te, lb) { TreeStoreElem *tselem = TREESTORE(te); bool select_handled = false; if (tselem->flag & TSE_SELECTED) { if ((tselem->type == TSE_SOME_ID) && (te->idcode == ID_OB)) { /* When objects selected in other scenes... dunno if that should be allowed. */ Scene *scene_owner = (Scene *)outliner_search_back(te, ID_SCE); if (scene_owner && scene_act != scene_owner) { WM_window_set_active_scene(CTX_data_main(C), C, CTX_wm_window(C), scene_owner); } /* Important to use 'scene_owner' not scene_act else deleting objects can crash. * only use 'scene_act' when 'scene_owner' is NULL, which can happen when the * outliner isn't showing scenes: Visible Layer draw mode for eg. */ operation_fn( C, reports, scene_owner ? scene_owner : scene_act, te, NULL, tselem, user_data); select_handled = true; } } if (TSELEM_OPEN(tselem, space_outliner)) { if ((select_handled == false) || recurse_selected) { outliner_do_object_operation_ex(C, reports, scene_act, space_outliner, &te->subtree, operation_fn, NULL, recurse_selected); } } } } void outliner_do_object_operation(bContext *C, ReportList *reports, Scene *scene_act, SpaceOutliner *space_outliner, ListBase *lb, outliner_operation_fn operation_fn) { outliner_do_object_operation_ex( C, reports, scene_act, space_outliner, lb, operation_fn, NULL, true); } /** \} */ /* -------------------------------------------------------------------- */ /** \name Internal Tagging Utilities * \{ */ static void clear_animdata_fn(int UNUSED(event), TreeElement *UNUSED(te), TreeStoreElem *tselem, void *UNUSED(arg)) { BKE_animdata_free(tselem->id, true); DEG_id_tag_update(tselem->id, ID_RECALC_ANIMATION); } static void unlinkact_animdata_fn(int UNUSED(event), TreeElement *UNUSED(te), TreeStoreElem *tselem, void *UNUSED(arg)) { /* just set action to NULL */ BKE_animdata_set_action(NULL, tselem->id, NULL); DEG_id_tag_update(tselem->id, ID_RECALC_ANIMATION); } static void cleardrivers_animdata_fn(int UNUSED(event), TreeElement *UNUSED(te), TreeStoreElem *tselem, void *UNUSED(arg)) { IdAdtTemplate *iat = (IdAdtTemplate *)tselem->id; /* just free drivers - stored as a list of F-Curves */ BKE_fcurves_free(&iat->adt->drivers); DEG_id_tag_update(tselem->id, ID_RECALC_ANIMATION); } static void refreshdrivers_animdata_fn(int UNUSED(event), TreeElement *UNUSED(te), TreeStoreElem *tselem, void *UNUSED(arg)) { IdAdtTemplate *iat = (IdAdtTemplate *)tselem->id; /* Loop over drivers, performing refresh * (i.e. check graph_buttons.c and rna_fcurve.c for details). */ LISTBASE_FOREACH (FCurve *, fcu, &iat->adt->drivers) { fcu->flag &= ~FCURVE_DISABLED; if (fcu->driver) { fcu->driver->flag &= ~DRIVER_FLAG_INVALID; } } } /** \} */ /* -------------------------------------------------------------------- */ /** \name Object Operation Utilities * \{ */ typedef enum eOutliner_PropDataOps { OL_DOP_SELECT = 1, OL_DOP_DESELECT, OL_DOP_HIDE, OL_DOP_UNHIDE, OL_DOP_SELECT_LINKED, } eOutliner_PropDataOps; typedef enum eOutliner_PropConstraintOps { OL_CONSTRAINTOP_ENABLE = 1, OL_CONSTRAINTOP_DISABLE, OL_CONSTRAINTOP_DELETE, } eOutliner_PropConstraintOps; typedef enum eOutliner_PropModifierOps { OL_MODIFIER_OP_TOGVIS = 1, OL_MODIFIER_OP_TOGREN, OL_MODIFIER_OP_DELETE, } eOutliner_PropModifierOps; static void pchan_fn(int event, TreeElement *te, TreeStoreElem *UNUSED(tselem), void *UNUSED(arg)) { bPoseChannel *pchan = (bPoseChannel *)te->directdata; if (event == OL_DOP_SELECT) { pchan->bone->flag |= BONE_SELECTED; } else if (event == OL_DOP_DESELECT) { pchan->bone->flag &= ~BONE_SELECTED; } else if (event == OL_DOP_HIDE) { pchan->bone->flag |= BONE_HIDDEN_P; pchan->bone->flag &= ~BONE_SELECTED; } else if (event == OL_DOP_UNHIDE) { pchan->bone->flag &= ~BONE_HIDDEN_P; } } static void bone_fn(int event, TreeElement *te, TreeStoreElem *UNUSED(tselem), void *UNUSED(arg)) { Bone *bone = (Bone *)te->directdata; if (event == OL_DOP_SELECT) { bone->flag |= BONE_SELECTED; } else if (event == OL_DOP_DESELECT) { bone->flag &= ~BONE_SELECTED; } else if (event == OL_DOP_HIDE) { bone->flag |= BONE_HIDDEN_P; bone->flag &= ~BONE_SELECTED; } else if (event == OL_DOP_UNHIDE) { bone->flag &= ~BONE_HIDDEN_P; } } static void ebone_fn(int event, TreeElement *te, TreeStoreElem *UNUSED(tselem), void *UNUSED(arg)) { EditBone *ebone = (EditBone *)te->directdata; if (event == OL_DOP_SELECT) { ebone->flag |= BONE_SELECTED; } else if (event == OL_DOP_DESELECT) { ebone->flag &= ~BONE_SELECTED; } else if (event == OL_DOP_HIDE) { ebone->flag |= BONE_HIDDEN_A; ebone->flag &= ~BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL; } else if (event == OL_DOP_UNHIDE) { ebone->flag &= ~BONE_HIDDEN_A; } } static void sequence_fn(int event, TreeElement *te, TreeStoreElem *tselem, void *scene_ptr) { Sequence *seq = (Sequence *)te->directdata; if (event == OL_DOP_SELECT) { Scene *scene = (Scene *)scene_ptr; Editing *ed = SEQ_editing_get(scene, false); if (BLI_findindex(ed->seqbasep, seq) != -1) { ED_sequencer_select_sequence_single(scene, seq, true); } } (void)tselem; } static void gpencil_layer_fn(int event, TreeElement *te, TreeStoreElem *UNUSED(tselem), void *UNUSED(arg)) { bGPDlayer *gpl = (bGPDlayer *)te->directdata; if (event == OL_DOP_SELECT) { gpl->flag |= GP_LAYER_SELECT; } else if (event == OL_DOP_DESELECT) { gpl->flag &= ~GP_LAYER_SELECT; } else if (event == OL_DOP_HIDE) { gpl->flag |= GP_LAYER_HIDE; } else if (event == OL_DOP_UNHIDE) { gpl->flag &= ~GP_LAYER_HIDE; } } static void data_select_linked_fn(int event, TreeElement *te, TreeStoreElem *UNUSED(tselem), void *C_v) { if (event == OL_DOP_SELECT_LINKED) { if (RNA_struct_is_ID(te->rnaptr.type)) { bContext *C = (bContext *)C_v; ID *id = te->rnaptr.data; ED_object_select_linked_by_id(C, id); } } } static void constraint_fn(int event, TreeElement *te, TreeStoreElem *UNUSED(tselem), void *C_v) { bContext *C = C_v; Main *bmain = CTX_data_main(C); bConstraint *constraint = (bConstraint *)te->directdata; Object *ob = (Object *)outliner_search_back(te, ID_OB); if (event == OL_CONSTRAINTOP_ENABLE) { constraint->flag &= ~CONSTRAINT_OFF; ED_object_constraint_update(bmain, ob); WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob); } else if (event == OL_CONSTRAINTOP_DISABLE) { constraint->flag = CONSTRAINT_OFF; ED_object_constraint_update(bmain, ob); WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob); } else if (event == OL_CONSTRAINTOP_DELETE) { ListBase *lb = NULL; if (TREESTORE(te->parent->parent)->type == TSE_POSE_CHANNEL) { lb = &((bPoseChannel *)te->parent->parent->directdata)->constraints; } else { lb = &ob->constraints; } if (BKE_constraint_remove_ex(lb, ob, constraint, true)) { /* there's no active constraint now, so make sure this is the case */ BKE_constraints_active_set(&ob->constraints, NULL); /* needed to set the flags on posebones correctly */ ED_object_constraint_update(bmain, ob); WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_REMOVED, ob); te->store_elem->flag &= ~TSE_SELECTED; } } } static void modifier_fn(int event, TreeElement *te, TreeStoreElem *UNUSED(tselem), void *Carg) { bContext *C = (bContext *)Carg; Main *bmain = CTX_data_main(C); Scene *scene = CTX_data_scene(C); ModifierData *md = (ModifierData *)te->directdata; Object *ob = (Object *)outliner_search_back(te, ID_OB); if (event == OL_MODIFIER_OP_TOGVIS) { md->mode ^= eModifierMode_Realtime; DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, ob); } else if (event == OL_MODIFIER_OP_TOGREN) { md->mode ^= eModifierMode_Render; DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, ob); } else if (event == OL_MODIFIER_OP_DELETE) { ED_object_modifier_remove(NULL, bmain, scene, ob, md); WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER | NA_REMOVED, ob); te->store_elem->flag &= ~TSE_SELECTED; } } static void outliner_do_data_operation( SpaceOutliner *space_outliner, int type, int event, ListBase *lb, void (*operation_fn)(int, TreeElement *, TreeStoreElem *, void *), void *arg) { LISTBASE_FOREACH (TreeElement *, te, lb) { TreeStoreElem *tselem = TREESTORE(te); if (tselem->flag & TSE_SELECTED) { if (tselem->type == type) { operation_fn(event, te, tselem, arg); } } if (TSELEM_OPEN(tselem, space_outliner)) { outliner_do_data_operation(space_outliner, type, event, &te->subtree, operation_fn, arg); } } } static Base *outline_batch_delete_hierarchy( ReportList *reports, Main *bmain, ViewLayer *view_layer, Scene *scene, Base *base) { Base *child_base, *base_next; Object *object, *parent; if (!base) { return NULL; } object = base->object; for (child_base = view_layer->object_bases.first; child_base; child_base = base_next) { base_next = child_base->next; for (parent = child_base->object->parent; parent && (parent != object); parent = parent->parent) { /* pass */ } if (parent) { base_next = outline_batch_delete_hierarchy(reports, bmain, view_layer, scene, child_base); } } base_next = base->next; if (object->id.tag & LIB_TAG_INDIRECT) { BKE_reportf(reports, RPT_WARNING, "Cannot delete indirectly linked object '%s'", base->object->id.name + 2); return base_next; } if (BKE_library_ID_is_indirectly_used(bmain, object) && ID_REAL_USERS(object) <= 1 && ID_EXTRA_USERS(object) == 0) { BKE_reportf(reports, RPT_WARNING, "Cannot delete object '%s' from scene '%s', indirectly used objects need at least " "one user", object->id.name + 2, scene->id.name + 2); return base_next; } DEG_id_tag_update_ex(bmain, &object->id, ID_RECALC_BASE_FLAGS); BKE_scene_collections_object_remove(bmain, scene, object, false); if (object->id.us == 0) { object->id.tag |= LIB_TAG_DOIT; } return base_next; } static void object_batch_delete_hierarchy_fn(bContext *C, ReportList *reports, Scene *scene, Object *ob) { ViewLayer *view_layer = CTX_data_view_layer(C); Object *obedit = CTX_data_edit_object(C); Base *base = BKE_view_layer_base_find(view_layer, ob); if (base) { /* Check also library later. */ for (; obedit && (obedit != base->object); obedit = obedit->parent) { /* pass */ } if (obedit == base->object) { ED_object_editmode_exit(C, EM_FREEDATA); } outline_batch_delete_hierarchy(reports, CTX_data_main(C), view_layer, scene, base); } } /** \} */ /* -------------------------------------------------------------------- */ /** \name Object Menu Operator * \{ */ enum { OL_OP_SELECT = 1, OL_OP_DESELECT, OL_OP_SELECT_HIERARCHY, OL_OP_REMAP, OL_OP_RENAME, OL_OP_PROXY_TO_OVERRIDE_CONVERT, }; static const EnumPropertyItem prop_object_op_types[] = { {OL_OP_SELECT, "SELECT", ICON_RESTRICT_SELECT_OFF, "Select", ""}, {OL_OP_DESELECT, "DESELECT", 0, "Deselect", ""}, {OL_OP_SELECT_HIERARCHY, "SELECT_HIERARCHY", 0, "Select Hierarchy", ""}, {OL_OP_REMAP, "REMAP", 0, "Remap Users", "Make all users of selected data-blocks to use instead a new chosen one"}, {OL_OP_RENAME, "RENAME", 0, "Rename", ""}, {OL_OP_PROXY_TO_OVERRIDE_CONVERT, "OBJECT_PROXY_TO_OVERRIDE", 0, "Convert Proxy to Override", "Convert a Proxy object to a full library override, including all its dependencies"}, {0, NULL, 0, NULL, NULL}, }; static int outliner_object_operation_exec(bContext *C, wmOperator *op) { Main *bmain = CTX_data_main(C); Scene *scene = CTX_data_scene(C); wmWindow *win = CTX_wm_window(C); SpaceOutliner *space_outliner = CTX_wm_space_outliner(C); int event; const char *str = NULL; bool selection_changed = false; /* check for invalid states */ if (space_outliner == NULL) { return OPERATOR_CANCELLED; } event = RNA_enum_get(op->ptr, "type"); if (event == OL_OP_SELECT) { Scene *sce = scene; /* To be able to delete, scenes are set... */ outliner_do_object_operation( C, op->reports, scene, space_outliner, &space_outliner->tree, object_select_fn); if (scene != sce) { WM_window_set_active_scene(bmain, C, win, sce); } str = "Select Objects"; selection_changed = true; } else if (event == OL_OP_SELECT_HIERARCHY) { Scene *sce = scene; /* To be able to delete, scenes are set... */ outliner_do_object_operation_ex(C, op->reports, scene, space_outliner, &space_outliner->tree, object_select_hierarchy_fn, NULL, false); if (scene != sce) { WM_window_set_active_scene(bmain, C, win, sce); } str = "Select Object Hierarchy"; selection_changed = true; } else if (event == OL_OP_DESELECT) { outliner_do_object_operation( C, op->reports, scene, space_outliner, &space_outliner->tree, object_deselect_fn); str = "Deselect Objects"; selection_changed = true; } else if (event == OL_OP_REMAP) { outliner_do_libdata_operation( C, op->reports, scene, space_outliner, &space_outliner->tree, id_remap_fn, NULL); /* No undo push here, operator does it itself (since it's a modal one, the op_undo_depth * trick does not work here). */ } else if (event == OL_OP_RENAME) { outliner_do_object_operation( C, op->reports, scene, space_outliner, &space_outliner->tree, item_rename_fn); str = "Rename Object"; } else if (event == OL_OP_PROXY_TO_OVERRIDE_CONVERT) { outliner_do_object_operation(C, op->reports, scene, space_outliner, &space_outliner->tree, object_proxy_to_override_convert_fn); str = "Convert Proxy to Override"; } else { BLI_assert(0); return OPERATOR_CANCELLED; } if (selection_changed) { DEG_id_tag_update(&scene->id, ID_RECALC_SELECT); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); ED_outliner_select_sync_from_object_tag(C); } if (str != NULL) { ED_undo_push(C, str); } return OPERATOR_FINISHED; } void OUTLINER_OT_object_operation(wmOperatorType *ot) { /* identifiers */ ot->name = "Outliner Object Operation"; ot->idname = "OUTLINER_OT_object_operation"; /* callbacks */ ot->invoke = WM_menu_invoke; ot->exec = outliner_object_operation_exec; ot->poll = ED_operator_outliner_active; ot->flag = 0; ot->prop = RNA_def_enum(ot->srna, "type", prop_object_op_types, 0, "Object Operation", ""); } /** \} */ /* -------------------------------------------------------------------- */ /** \name Delete Object/Collection Operator * \{ */ typedef void (*OutlinerDeleteFunc)(bContext *C, ReportList *reports, Scene *scene, Object *ob); static void outliner_do_object_delete(bContext *C, ReportList *reports, Scene *scene, GSet *objects_to_delete, OutlinerDeleteFunc delete_fn) { GSetIterator objects_to_delete_iter; GSET_ITER (objects_to_delete_iter, objects_to_delete) { Object *ob = (Object *)BLI_gsetIterator_getKey(&objects_to_delete_iter); delete_fn(C, reports, scene, ob); } } static TreeTraversalAction outliner_find_objects_to_delete(TreeElement *te, void *customdata) { GSet *objects_to_delete = (GSet *)customdata; TreeStoreElem *tselem = TREESTORE(te); if (outliner_is_collection_tree_element(te)) { return TRAVERSE_CONTINUE; } if ((tselem->type != TSE_SOME_ID) || (tselem->id == NULL) || (GS(tselem->id->name) != ID_OB)) { return TRAVERSE_SKIP_CHILDS; } BLI_gset_add(objects_to_delete, tselem->id); return TRAVERSE_CONTINUE; } static int outliner_delete_exec(bContext *C, wmOperator *op) { Main *bmain = CTX_data_main(C); Scene *scene = CTX_data_scene(C); SpaceOutliner *space_outliner = CTX_wm_space_outliner(C); struct wmMsgBus *mbus = CTX_wm_message_bus(C); ViewLayer *view_layer = CTX_data_view_layer(C); const Base *basact_prev = BASACT(view_layer); const bool delete_hierarchy = RNA_boolean_get(op->ptr, "hierarchy"); /* Get selected objects skipping duplicates to prevent deleting objects linked to multiple * collections twice */ GSet *objects_to_delete = BLI_gset_ptr_new(__func__); outliner_tree_traverse(space_outliner, &space_outliner->tree, 0, TSE_SELECTED, outliner_find_objects_to_delete, objects_to_delete); if (delete_hierarchy) { BKE_main_id_tag_all(bmain, LIB_TAG_DOIT, false); outliner_do_object_delete( C, op->reports, scene, objects_to_delete, object_batch_delete_hierarchy_fn); BKE_id_multi_tagged_delete(bmain); } else { outliner_do_object_delete(C, op->reports, scene, objects_to_delete, outliner_object_delete_fn); } BLI_gset_free(objects_to_delete, NULL); outliner_collection_delete(C, bmain, scene, op->reports, delete_hierarchy); /* Tree management normally happens from draw_outliner(), but when * you're clicking too fast on Delete object from context menu in * outliner several mouse events can be handled in one cycle without * handling notifiers/redraw which leads to deleting the same object twice. * cleanup tree here to prevent such cases. */ outliner_cleanup_tree(space_outliner); DEG_id_tag_update(&scene->id, ID_RECALC_COPY_ON_WRITE); DEG_relations_tag_update(bmain); if (basact_prev != BASACT(view_layer)) { WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene); WM_msg_publish_rna_prop(mbus, &scene->id, view_layer, LayerObjects, active); } DEG_id_tag_update(&scene->id, ID_RECALC_SELECT); WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene); WM_event_add_notifier(C, NC_SCENE | ND_LAYER_CONTENT, scene); ED_outliner_select_sync_from_object_tag(C); return OPERATOR_FINISHED; } void OUTLINER_OT_delete(wmOperatorType *ot) { /* identifiers */ ot->name = "Delete"; ot->idname = "OUTLINER_OT_delete"; ot->description = "Delete selected objects and collections"; /* callbacks */ ot->exec = outliner_delete_exec; ot->poll = ED_operator_outliner_active; /* flags */ ot->flag |= OPTYPE_REGISTER | OPTYPE_UNDO; /* properties */ PropertyRNA *prop = RNA_def_boolean( ot->srna, "hierarchy", false, "Hierarchy", "Delete child objects and collections"); RNA_def_property_flag(prop, PROP_SKIP_SAVE); } /** \} */ /* -------------------------------------------------------------------- */ /** \name ID-Data Menu Operator * \{ */ typedef enum eOutlinerIdOpTypes { OUTLINER_IDOP_INVALID = 0, OUTLINER_IDOP_UNLINK, OUTLINER_IDOP_MARK_ASSET, OUTLINER_IDOP_CLEAR_ASSET, OUTLINER_IDOP_LOCAL, OUTLINER_IDOP_OVERRIDE_LIBRARY_CREATE, OUTLINER_IDOP_OVERRIDE_LIBRARY_CREATE_HIERARCHY, OUTLINER_IDOP_OVERRIDE_LIBRARY_PROXY_CONVERT, OUTLINER_IDOP_OVERRIDE_LIBRARY_RESET, OUTLINER_IDOP_OVERRIDE_LIBRARY_RESET_HIERARCHY, OUTLINER_IDOP_OVERRIDE_LIBRARY_RESYNC_HIERARCHY, OUTLINER_IDOP_OVERRIDE_LIBRARY_DELETE_HIERARCHY, OUTLINER_IDOP_SINGLE, OUTLINER_IDOP_DELETE, OUTLINER_IDOP_REMAP, OUTLINER_IDOP_COPY, OUTLINER_IDOP_PASTE, OUTLINER_IDOP_FAKE_ADD, OUTLINER_IDOP_FAKE_CLEAR, OUTLINER_IDOP_RENAME, OUTLINER_IDOP_SELECT_LINKED, } eOutlinerIdOpTypes; /* TODO: implement support for changing the ID-block used. */ static const EnumPropertyItem prop_id_op_types[] = { {OUTLINER_IDOP_UNLINK, "UNLINK", 0, "Unlink", ""}, {OUTLINER_IDOP_MARK_ASSET, "MARK_ASSET", 0, "Mark Asset", ""}, {OUTLINER_IDOP_CLEAR_ASSET, "CLEAR_ASSET", 0, "Clear Asset", ""}, {OUTLINER_IDOP_LOCAL, "LOCAL", 0, "Make Local", ""}, {OUTLINER_IDOP_SINGLE, "SINGLE", 0, "Make Single User", ""}, {OUTLINER_IDOP_DELETE, "DELETE", ICON_X, "Delete", ""}, {OUTLINER_IDOP_REMAP, "REMAP", 0, "Remap Users", "Make all users of selected data-blocks to use instead current (clicked) one"}, {0, "", 0, NULL, NULL}, {OUTLINER_IDOP_OVERRIDE_LIBRARY_CREATE, "OVERRIDE_LIBRARY_CREATE", 0, "Add Library Override", "Add a local override of this linked data-block"}, {OUTLINER_IDOP_OVERRIDE_LIBRARY_CREATE_HIERARCHY, "OVERRIDE_LIBRARY_CREATE_HIERARCHY", 0, "Add Library Override Hierarchy", "Add a local override of this linked data-block, and its hierarchy of dependencies"}, {OUTLINER_IDOP_OVERRIDE_LIBRARY_PROXY_CONVERT, "OVERRIDE_LIBRARY_PROXY_CONVERT", 0, "Convert Proxy to Override", "Convert a Proxy object to a full library override, including all its dependencies"}, {OUTLINER_IDOP_OVERRIDE_LIBRARY_RESET, "OVERRIDE_LIBRARY_RESET", 0, "Reset Library Override", "Reset this local override to its linked values"}, {OUTLINER_IDOP_OVERRIDE_LIBRARY_RESET_HIERARCHY, "OVERRIDE_LIBRARY_RESET_HIERARCHY", 0, "Reset Library Override Hierarchy", "Reset this local override to its linked values, as well as its hierarchy of dependencies"}, {OUTLINER_IDOP_OVERRIDE_LIBRARY_RESYNC_HIERARCHY, "OVERRIDE_LIBRARY_RESYNC_HIERARCHY", 0, "Resync Library Override Hierarchy", "Rebuild this local override from its linked reference, as well as its hierarchy of " "dependencies"}, {OUTLINER_IDOP_OVERRIDE_LIBRARY_DELETE_HIERARCHY, "OVERRIDE_LIBRARY_DELETE_HIERARCHY", 0, "Delete Library Override Hierarchy", "Delete this local override (including its hierarchy of override dependencies) and relink " "its usages to the linked data-blocks"}, {0, "", 0, NULL, NULL}, {OUTLINER_IDOP_COPY, "COPY", ICON_COPYDOWN, "Copy", ""}, {OUTLINER_IDOP_PASTE, "PASTE", ICON_PASTEDOWN, "Paste", ""}, {0, "", 0, NULL, NULL}, {OUTLINER_IDOP_FAKE_ADD, "ADD_FAKE", 0, "Add Fake User", "Ensure data-block gets saved even if it isn't in use (e.g. for motion and material " "libraries)"}, {OUTLINER_IDOP_FAKE_CLEAR, "CLEAR_FAKE", 0, "Clear Fake User", ""}, {OUTLINER_IDOP_RENAME, "RENAME", 0, "Rename", ""}, {OUTLINER_IDOP_SELECT_LINKED, "SELECT_LINKED", 0, "Select Linked", ""}, {0, NULL, 0, NULL, NULL}, }; static bool outliner_id_operation_item_poll(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), const int enum_value) { SpaceOutliner *space_outliner = CTX_wm_space_outliner(C); TreeElement *te = get_target_element(space_outliner); TreeStoreElem *tselem = TREESTORE(te); if (!TSE_IS_REAL_ID(tselem)) { return false; } Object *ob = NULL; if (GS(tselem->id->name) == ID_OB) { ob = (Object *)tselem->id; } switch (enum_value) { case OUTLINER_IDOP_MARK_ASSET: case OUTLINER_IDOP_CLEAR_ASSET: return U.experimental.use_asset_browser; case OUTLINER_IDOP_OVERRIDE_LIBRARY_CREATE: if (ID_IS_OVERRIDABLE_LIBRARY(tselem->id)) { return true; } return false; case OUTLINER_IDOP_OVERRIDE_LIBRARY_CREATE_HIERARCHY: if (ID_IS_OVERRIDABLE_LIBRARY(tselem->id) || (ID_IS_LINKED(tselem->id))) { return true; } return false; case OUTLINER_IDOP_OVERRIDE_LIBRARY_PROXY_CONVERT: if (ob != NULL && ob->proxy != NULL) { return true; } return false; case OUTLINER_IDOP_OVERRIDE_LIBRARY_RESET: case OUTLINER_IDOP_OVERRIDE_LIBRARY_RESET_HIERARCHY: case OUTLINER_IDOP_OVERRIDE_LIBRARY_RESYNC_HIERARCHY: case OUTLINER_IDOP_OVERRIDE_LIBRARY_DELETE_HIERARCHY: if (ID_IS_OVERRIDE_LIBRARY_REAL(tselem->id)) { return true; } return false; case OUTLINER_IDOP_SINGLE: if (!space_outliner || ELEM(space_outliner->outlinevis, SO_SCENES, SO_VIEW_LAYER)) { return true; } /* TODO(dalai): enable in the few cases where this can be supported * (i.e., when we have a valid parent for the tselem). */ return false; } return true; } static const EnumPropertyItem *outliner_id_operation_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *prop, bool *r_free) { EnumPropertyItem *items = NULL; int totitem = 0; if (C == NULL) { return prop_id_op_types; } for (const EnumPropertyItem *it = prop_id_op_types; it->identifier != NULL; it++) { if (!outliner_id_operation_item_poll(C, ptr, prop, it->value)) { continue; } RNA_enum_item_add(&items, &totitem, it); } RNA_enum_item_end(&items, &totitem); *r_free = true; return items; } static int outliner_id_operation_exec(bContext *C, wmOperator *op) { wmWindowManager *wm = CTX_wm_manager(C); Scene *scene = CTX_data_scene(C); SpaceOutliner *space_outliner = CTX_wm_space_outliner(C); int scenelevel = 0, objectlevel = 0, idlevel = 0, datalevel = 0; /* check for invalid states */ if (space_outliner == NULL) { return OPERATOR_CANCELLED; } TreeElement *te = get_target_element(space_outliner); get_element_operation_type(te, &scenelevel, &objectlevel, &idlevel, &datalevel); eOutlinerIdOpTypes event = RNA_enum_get(op->ptr, "type"); switch (event) { case OUTLINER_IDOP_UNLINK: { /* unlink datablock from its parent */ if (objectlevel) { outliner_do_libdata_operation( C, op->reports, scene, space_outliner, &space_outliner->tree, unlink_object_fn, NULL); WM_event_add_notifier(C, NC_SCENE | ND_LAYER, NULL); ED_undo_push(C, "Unlink Object"); break; } switch (idlevel) { case ID_AC: outliner_do_libdata_operation(C, op->reports, scene, space_outliner, &space_outliner->tree, unlink_action_fn, NULL); WM_event_add_notifier(C, NC_ANIMATION | ND_NLA_ACTCHANGE, NULL); ED_undo_push(C, "Unlink action"); break; case ID_MA: outliner_do_libdata_operation(C, op->reports, scene, space_outliner, &space_outliner->tree, unlink_material_fn, NULL); WM_event_add_notifier(C, NC_OBJECT | ND_OB_SHADING, NULL); ED_undo_push(C, "Unlink material"); break; case ID_TE: outliner_do_libdata_operation(C, op->reports, scene, space_outliner, &space_outliner->tree, unlink_texture_fn, NULL); WM_event_add_notifier(C, NC_OBJECT | ND_OB_SHADING, NULL); ED_undo_push(C, "Unlink texture"); break; case ID_WO: outliner_do_libdata_operation( C, op->reports, scene, space_outliner, &space_outliner->tree, unlink_world_fn, NULL); WM_event_add_notifier(C, NC_SCENE | ND_WORLD, NULL); ED_undo_push(C, "Unlink world"); break; case ID_GR: outliner_do_libdata_operation(C, op->reports, scene, space_outliner, &space_outliner->tree, unlink_collection_fn, NULL); WM_event_add_notifier(C, NC_SCENE | ND_LAYER, NULL); ED_undo_push(C, "Unlink Collection"); break; default: BKE_report(op->reports, RPT_WARNING, "Not yet implemented"); break; } break; } case OUTLINER_IDOP_MARK_ASSET: { WM_operator_name_call(C, "ASSET_OT_mark", WM_OP_EXEC_DEFAULT, NULL); break; } case OUTLINER_IDOP_CLEAR_ASSET: { WM_operator_name_call(C, "ASSET_OT_clear", WM_OP_EXEC_DEFAULT, NULL); break; } case OUTLINER_IDOP_LOCAL: { /* make local */ outliner_do_libdata_operation( C, op->reports, scene, space_outliner, &space_outliner->tree, id_local_fn, NULL); ED_undo_push(C, "Localized Data"); break; } case OUTLINER_IDOP_OVERRIDE_LIBRARY_CREATE: { outliner_do_libdata_operation(C, op->reports, scene, space_outliner, &space_outliner->tree, id_override_library_create_fn, &(OutlinerLibOverrideData){.do_hierarchy = false}); ED_undo_push(C, "Overridden Data"); break; } case OUTLINER_IDOP_OVERRIDE_LIBRARY_CREATE_HIERARCHY: { outliner_do_libdata_operation(C, op->reports, scene, space_outliner, &space_outliner->tree, id_override_library_create_fn, &(OutlinerLibOverrideData){.do_hierarchy = true}); ED_undo_push(C, "Overridden Data Hierarchy"); break; } case OUTLINER_IDOP_OVERRIDE_LIBRARY_PROXY_CONVERT: { outliner_do_object_operation(C, op->reports, scene, space_outliner, &space_outliner->tree, object_proxy_to_override_convert_fn); ED_undo_push(C, "Convert Proxy to Override"); break; } case OUTLINER_IDOP_OVERRIDE_LIBRARY_RESET: { outliner_do_libdata_operation(C, op->reports, scene, space_outliner, &space_outliner->tree, id_override_library_reset_fn, &(OutlinerLibOverrideData){.do_hierarchy = false}); ED_undo_push(C, "Reset Overridden Data"); break; } case OUTLINER_IDOP_OVERRIDE_LIBRARY_RESET_HIERARCHY: { outliner_do_libdata_operation(C, op->reports, scene, space_outliner, &space_outliner->tree, id_override_library_reset_fn, &(OutlinerLibOverrideData){.do_hierarchy = true}); ED_undo_push(C, "Reset Overridden Data Hierarchy"); break; } case OUTLINER_IDOP_OVERRIDE_LIBRARY_RESYNC_HIERARCHY: { outliner_do_libdata_operation(C, op->reports, scene, space_outliner, &space_outliner->tree, id_override_library_resync_fn, &(OutlinerLibOverrideData){.do_hierarchy = true}); ED_undo_push(C, "Resync Overridden Data Hierarchy"); break; } case OUTLINER_IDOP_OVERRIDE_LIBRARY_DELETE_HIERARCHY: { outliner_do_libdata_operation(C, op->reports, scene, space_outliner, &space_outliner->tree, id_override_library_delete_fn, &(OutlinerLibOverrideData){.do_hierarchy = true}); ED_undo_push(C, "Delete Overridden Data Hierarchy"); break; } case OUTLINER_IDOP_SINGLE: { /* make single user */ switch (idlevel) { case ID_AC: outliner_do_libdata_operation(C, op->reports, scene, space_outliner, &space_outliner->tree, singleuser_action_fn, NULL); WM_event_add_notifier(C, NC_ANIMATION | ND_NLA_ACTCHANGE, NULL); ED_undo_push(C, "Single-User Action"); break; case ID_WO: outliner_do_libdata_operation(C, op->reports, scene, space_outliner, &space_outliner->tree, singleuser_world_fn, NULL); WM_event_add_notifier(C, NC_SCENE | ND_WORLD, NULL); ED_undo_push(C, "Single-User World"); break; default: BKE_report(op->reports, RPT_WARNING, "Not yet implemented"); break; } break; } case OUTLINER_IDOP_DELETE: { if (idlevel > 0) { outliner_do_libdata_operation( C, op->reports, scene, space_outliner, &space_outliner->tree, id_delete_fn, NULL); ED_undo_push(C, "Delete"); } break; } case OUTLINER_IDOP_REMAP: { if (idlevel > 0) { outliner_do_libdata_operation( C, op->reports, scene, space_outliner, &space_outliner->tree, id_remap_fn, NULL); /* No undo push here, operator does it itself (since it's a modal one, the op_undo_depth * trick does not work here). */ } break; } case OUTLINER_IDOP_COPY: { wm->op_undo_depth++; WM_operator_name_call(C, "OUTLINER_OT_id_copy", WM_OP_INVOKE_DEFAULT, NULL); wm->op_undo_depth--; /* No need for undo, this operation does not change anything... */ break; } case OUTLINER_IDOP_PASTE: { wm->op_undo_depth++; WM_operator_name_call(C, "OUTLINER_OT_id_paste", WM_OP_INVOKE_DEFAULT, NULL); wm->op_undo_depth--; ED_outliner_select_sync_from_all_tag(C); ED_undo_push(C, "Paste"); break; } case OUTLINER_IDOP_FAKE_ADD: { /* set fake user */ outliner_do_libdata_operation( C, op->reports, scene, space_outliner, &space_outliner->tree, id_fake_user_set_fn, NULL); WM_event_add_notifier(C, NC_ID | NA_EDITED, NULL); ED_undo_push(C, "Add Fake User"); break; } case OUTLINER_IDOP_FAKE_CLEAR: { /* clear fake user */ outliner_do_libdata_operation(C, op->reports, scene, space_outliner, &space_outliner->tree, id_fake_user_clear_fn, NULL); WM_event_add_notifier(C, NC_ID | NA_EDITED, NULL); ED_undo_push(C, "Clear Fake User"); break; } case OUTLINER_IDOP_RENAME: { /* rename */ outliner_do_libdata_operation( C, op->reports, scene, space_outliner, &space_outliner->tree, item_rename_fn, NULL); WM_event_add_notifier(C, NC_ID | NA_EDITED, NULL); ED_undo_push(C, "Rename"); break; } case OUTLINER_IDOP_SELECT_LINKED: outliner_do_libdata_operation( C, op->reports, scene, space_outliner, &space_outliner->tree, id_select_linked_fn, NULL); ED_outliner_select_sync_from_all_tag(C); ED_undo_push(C, "Select"); break; default: /* Invalid - unhandled. */ break; } /* wrong notifier still... */ WM_event_add_notifier(C, NC_ID | NA_EDITED, NULL); /* XXX: this is just so that outliner is always up to date. */ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_OUTLINER, NULL); return OPERATOR_FINISHED; } void OUTLINER_OT_id_operation(wmOperatorType *ot) { /* identifiers */ ot->name = "Outliner ID Data Operation"; ot->idname = "OUTLINER_OT_id_operation"; /* callbacks */ ot->invoke = WM_menu_invoke; ot->exec = outliner_id_operation_exec; ot->poll = ED_operator_outliner_active; ot->flag = 0; ot->prop = RNA_def_enum(ot->srna, "type", prop_id_op_types, 0, "ID Data Operation", ""); RNA_def_enum_funcs(ot->prop, outliner_id_operation_itemf); } /** \} */ /* -------------------------------------------------------------------- */ /** \name Library Menu Operator * \{ */ typedef enum eOutlinerLibOpTypes { OL_LIB_INVALID = 0, OL_LIB_RENAME, OL_LIB_DELETE, OL_LIB_RELOCATE, OL_LIB_RELOAD, } eOutlinerLibOpTypes; static const EnumPropertyItem outliner_lib_op_type_items[] = { {OL_LIB_RENAME, "RENAME", 0, "Rename", ""}, {OL_LIB_DELETE, "DELETE", ICON_X, "Delete", "Delete this library and all its item from Blender - WARNING: no undo"}, {OL_LIB_RELOCATE, "RELOCATE", 0, "Relocate", "Select a new path for this library, and reload all its data"}, {OL_LIB_RELOAD, "RELOAD", ICON_FILE_REFRESH, "Reload", "Reload all data from this library"}, {0, NULL, 0, NULL, NULL}, }; static int outliner_lib_operation_exec(bContext *C, wmOperator *op) { Scene *scene = CTX_data_scene(C); SpaceOutliner *space_outliner = CTX_wm_space_outliner(C); int scenelevel = 0, objectlevel = 0, idlevel = 0, datalevel = 0; /* check for invalid states */ if (space_outliner == NULL) { return OPERATOR_CANCELLED; } TreeElement *te = get_target_element(space_outliner); get_element_operation_type(te, &scenelevel, &objectlevel, &idlevel, &datalevel); eOutlinerLibOpTypes event = RNA_enum_get(op->ptr, "type"); switch (event) { case OL_LIB_RENAME: { outliner_do_libdata_operation( C, op->reports, scene, space_outliner, &space_outliner->tree, item_rename_fn, NULL); WM_event_add_notifier(C, NC_ID | NA_EDITED, NULL); ED_undo_push(C, "Rename Library"); break; } case OL_LIB_DELETE: { outliner_do_libdata_operation( C, op->reports, scene, space_outliner, &space_outliner->tree, id_delete_fn, NULL); ED_undo_push(C, "Delete Library"); break; } case OL_LIB_RELOCATE: { outliner_do_libdata_operation( C, op->reports, scene, space_outliner, &space_outliner->tree, lib_relocate_fn, NULL); /* No undo push here, operator does it itself (since it's a modal one, the op_undo_depth * trick does not work here). */ break; } case OL_LIB_RELOAD: { outliner_do_libdata_operation( C, op->reports, scene, space_outliner, &space_outliner->tree, lib_reload_fn, NULL); /* No undo push here, operator does it itself (since it's a modal one, the op_undo_depth * trick does not work here). */ break; } default: /* invalid - unhandled */ break; } /* wrong notifier still... */ WM_event_add_notifier(C, NC_ID | NA_EDITED, NULL); /* XXX: this is just so that outliner is always up to date */ WM_event_add_notifier(C, NC_SPACE | ND_SPACE_OUTLINER, NULL); return OPERATOR_FINISHED; } void OUTLINER_OT_lib_operation(wmOperatorType *ot) { /* identifiers */ ot->name = "Outliner Library Operation"; ot->idname = "OUTLINER_OT_lib_operation"; /* callbacks */ ot->invoke = WM_menu_invoke; ot->exec = outliner_lib_operation_exec; ot->poll = ED_operator_outliner_active; ot->prop = RNA_def_enum( ot->srna, "type", outliner_lib_op_type_items, 0, "Library Operation", ""); } /** \} */ /* -------------------------------------------------------------------- */ /** \name Outliner Set Active Action Operator * \{ */ static void outliner_do_id_set_operation( SpaceOutliner *space_outliner, int type, ListBase *lb, ID *newid, void (*operation_fn)(TreeElement *, TreeStoreElem *, TreeStoreElem *, ID *)) { LISTBASE_FOREACH (TreeElement *, te, lb) { TreeStoreElem *tselem = TREESTORE(te); if (tselem->flag & TSE_SELECTED) { if (tselem->type == type) { TreeStoreElem *tsep = te->parent ? TREESTORE(te->parent) : NULL; operation_fn(te, tselem, tsep, newid); } } if (TSELEM_OPEN(tselem, space_outliner)) { outliner_do_id_set_operation(space_outliner, type, &te->subtree, newid, operation_fn); } } } static void actionset_id_fn(TreeElement *UNUSED(te), TreeStoreElem *tselem, TreeStoreElem *tsep, ID *actId) { bAction *act = (bAction *)actId; if (tselem->type == TSE_ANIM_DATA) { /* "animation" entries - action is child of this */ BKE_animdata_set_action(NULL, tselem->id, act); } /* TODO: if any other "expander" channels which own actions need to support this menu, * add: tselem->type = ... */ else if (tsep && (tsep->type == TSE_ANIM_DATA)) { /* "animation" entries case again */ BKE_animdata_set_action(NULL, tsep->id, act); } /* TODO: other cases not supported yet. */ } static int outliner_action_set_exec(bContext *C, wmOperator *op) { Main *bmain = CTX_data_main(C); SpaceOutliner *space_outliner = CTX_wm_space_outliner(C); int scenelevel = 0, objectlevel = 0, idlevel = 0, datalevel = 0; bAction *act; /* check for invalid states */ if (space_outliner == NULL) { return OPERATOR_CANCELLED; } TreeElement *te = get_target_element(space_outliner); get_element_operation_type(te, &scenelevel, &objectlevel, &idlevel, &datalevel); /* get action to use */ act = BLI_findlink(&bmain->actions, RNA_enum_get(op->ptr, "action")); if (act == NULL) { BKE_report(op->reports, RPT_ERROR, "No valid action to add"); return OPERATOR_CANCELLED; } if (act->idroot == 0) { /* Hopefully in this case (i.e. library of userless actions), * the user knows what they're doing. */ BKE_reportf(op->reports, RPT_WARNING, "Action '%s' does not specify what data-blocks it can be used on " "(try setting the 'ID Root Type' setting from the data-blocks editor " "for this action to avoid future problems)", act->id.name + 2); } /* perform action if valid channel */ if (datalevel == TSE_ANIM_DATA) { outliner_do_id_set_operation( space_outliner, datalevel, &space_outliner->tree, (ID *)act, actionset_id_fn); } else if (idlevel == ID_AC) { outliner_do_id_set_operation( space_outliner, idlevel, &space_outliner->tree, (ID *)act, actionset_id_fn); } else { return OPERATOR_CANCELLED; } /* set notifier that things have changed */ WM_event_add_notifier(C, NC_ANIMATION | ND_NLA_ACTCHANGE, NULL); ED_undo_push(C, "Set action"); /* done */ return OPERATOR_FINISHED; } void OUTLINER_OT_action_set(wmOperatorType *ot) { PropertyRNA *prop; /* identifiers */ ot->name = "Outliner Set Action"; ot->idname = "OUTLINER_OT_action_set"; ot->description = "Change the active action used"; /* api callbacks */ ot->invoke = WM_enum_search_invoke; ot->exec = outliner_action_set_exec; ot->poll = ED_operator_outliner_active; /* flags */ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; /* props */ /* TODO: this would be nicer as an ID-pointer... */ prop = RNA_def_enum(ot->srna, "action", DummyRNA_NULL_items, 0, "Action", ""); RNA_def_enum_funcs(prop, RNA_action_itemf); RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE); ot->prop = prop; } /** \} */ /* -------------------------------------------------------------------- */ /** \name Animation Menu Operator * \{ */ typedef enum eOutliner_AnimDataOps { OUTLINER_ANIMOP_INVALID = 0, OUTLINER_ANIMOP_CLEAR_ADT, OUTLINER_ANIMOP_SET_ACT, OUTLINER_ANIMOP_CLEAR_ACT, OUTLINER_ANIMOP_REFRESH_DRV, OUTLINER_ANIMOP_CLEAR_DRV } eOutliner_AnimDataOps; static const EnumPropertyItem prop_animdata_op_types[] = { {OUTLINER_ANIMOP_CLEAR_ADT, "CLEAR_ANIMDATA", 0, "Clear Animation Data", "Remove this animation data container"}, {OUTLINER_ANIMOP_SET_ACT, "SET_ACT", 0, "Set Action", ""}, {OUTLINER_ANIMOP_CLEAR_ACT, "CLEAR_ACT", 0, "Unlink Action", ""}, {OUTLINER_ANIMOP_REFRESH_DRV, "REFRESH_DRIVERS", 0, "Refresh Drivers", ""}, {OUTLINER_ANIMOP_CLEAR_DRV, "CLEAR_DRIVERS", 0, "Clear Drivers", ""}, {0, NULL, 0, NULL, NULL}, }; static int outliner_animdata_operation_exec(bContext *C, wmOperator *op) { wmWindowManager *wm = CTX_wm_manager(C); SpaceOutliner *space_outliner = CTX_wm_space_outliner(C); int scenelevel = 0, objectlevel = 0, idlevel = 0, datalevel = 0; /* check for invalid states */ if (space_outliner == NULL) { return OPERATOR_CANCELLED; } TreeElement *te = get_target_element(space_outliner); get_element_operation_type(te, &scenelevel, &objectlevel, &idlevel, &datalevel); if (datalevel != TSE_ANIM_DATA) { return OPERATOR_CANCELLED; } /* perform the core operation */ eOutliner_AnimDataOps event = RNA_enum_get(op->ptr, "type"); switch (event) { case OUTLINER_ANIMOP_CLEAR_ADT: /* Remove Animation Data - this may remove the active action, in some cases... */ outliner_do_data_operation( space_outliner, datalevel, event, &space_outliner->tree, clear_animdata_fn, NULL); WM_event_add_notifier(C, NC_ANIMATION | ND_NLA_ACTCHANGE, NULL); ED_undo_push(C, "Clear Animation Data"); break; case OUTLINER_ANIMOP_SET_ACT: /* delegate once again... */ wm->op_undo_depth++; WM_operator_name_call(C, "OUTLINER_OT_action_set", WM_OP_INVOKE_REGION_WIN, NULL); wm->op_undo_depth--; ED_undo_push(C, "Set active action"); break; case OUTLINER_ANIMOP_CLEAR_ACT: /* clear active action - using standard rules */ outliner_do_data_operation( space_outliner, datalevel, event, &space_outliner->tree, unlinkact_animdata_fn, NULL); WM_event_add_notifier(C, NC_ANIMATION | ND_NLA_ACTCHANGE, NULL); ED_undo_push(C, "Unlink action"); break; case OUTLINER_ANIMOP_REFRESH_DRV: outliner_do_data_operation(space_outliner, datalevel, event, &space_outliner->tree, refreshdrivers_animdata_fn, NULL); WM_event_add_notifier(C, NC_ANIMATION | ND_ANIMCHAN, NULL); /* ED_undo_push(C, "Refresh Drivers"); No undo needed - shouldn't have any impact? */ break; case OUTLINER_ANIMOP_CLEAR_DRV: outliner_do_data_operation( space_outliner, datalevel, event, &space_outliner->tree, cleardrivers_animdata_fn, NULL); WM_event_add_notifier(C, NC_ANIMATION | ND_ANIMCHAN, NULL); ED_undo_push(C, "Clear Drivers"); break; default: /* Invalid. */ break; } /* update dependencies */ DEG_relations_tag_update(CTX_data_main(C)); return OPERATOR_FINISHED; } void OUTLINER_OT_animdata_operation(wmOperatorType *ot) { /* identifiers */ ot->name = "Outliner Animation Data Operation"; ot->idname = "OUTLINER_OT_animdata_operation"; /* callbacks */ ot->invoke = WM_menu_invoke; ot->exec = outliner_animdata_operation_exec; ot->poll = ED_operator_outliner_active; ot->flag = 0; ot->prop = RNA_def_enum(ot->srna, "type", prop_animdata_op_types, 0, "Animation Operation", ""); } /** \} */ /* -------------------------------------------------------------------- */ /** \name Constraint Menu Operator * \{ */ static const EnumPropertyItem prop_constraint_op_types[] = { {OL_CONSTRAINTOP_ENABLE, "ENABLE", ICON_HIDE_OFF, "Enable", ""}, {OL_CONSTRAINTOP_DISABLE, "DISABLE", ICON_HIDE_ON, "Disable", ""}, {OL_CONSTRAINTOP_DELETE, "DELETE", ICON_X, "Delete", ""}, {0, NULL, 0, NULL, NULL}, }; static int outliner_constraint_operation_exec(bContext *C, wmOperator *op) { SpaceOutliner *space_outliner = CTX_wm_space_outliner(C); eOutliner_PropConstraintOps event = RNA_enum_get(op->ptr, "type"); outliner_do_data_operation( space_outliner, TSE_CONSTRAINT, event, &space_outliner->tree, constraint_fn, C); if (event == OL_CONSTRAINTOP_DELETE) { outliner_cleanup_tree(space_outliner); } ED_undo_push(C, "Constraint operation"); return OPERATOR_FINISHED; } void OUTLINER_OT_constraint_operation(wmOperatorType *ot) { /* identifiers */ ot->name = "Outliner Constraint Operation"; ot->idname = "OUTLINER_OT_constraint_operation"; /* callbacks */ ot->invoke = WM_menu_invoke; ot->exec = outliner_constraint_operation_exec; ot->poll = ED_operator_outliner_active; ot->flag = 0; ot->prop = RNA_def_enum( ot->srna, "type", prop_constraint_op_types, 0, "Constraint Operation", ""); } /** \} */ /* -------------------------------------------------------------------- */ /** \name Modifier Menu Operator * \{ */ static const EnumPropertyItem prop_modifier_op_types[] = { {OL_MODIFIER_OP_TOGVIS, "TOGVIS", ICON_RESTRICT_VIEW_OFF, "Toggle Viewport Use", ""}, {OL_MODIFIER_OP_TOGREN, "TOGREN", ICON_RESTRICT_RENDER_OFF, "Toggle Render Use", ""}, {OL_MODIFIER_OP_DELETE, "DELETE", ICON_X, "Delete", ""}, {0, NULL, 0, NULL, NULL}, }; static int outliner_modifier_operation_exec(bContext *C, wmOperator *op) { SpaceOutliner *space_outliner = CTX_wm_space_outliner(C); eOutliner_PropModifierOps event = RNA_enum_get(op->ptr, "type"); outliner_do_data_operation( space_outliner, TSE_MODIFIER, event, &space_outliner->tree, modifier_fn, C); if (event == OL_MODIFIER_OP_DELETE) { outliner_cleanup_tree(space_outliner); } ED_undo_push(C, "Modifier operation"); return OPERATOR_FINISHED; } void OUTLINER_OT_modifier_operation(wmOperatorType *ot) { /* identifiers */ ot->name = "Outliner Modifier Operation"; ot->idname = "OUTLINER_OT_modifier_operation"; /* callbacks */ ot->invoke = WM_menu_invoke; ot->exec = outliner_modifier_operation_exec; ot->poll = ED_operator_outliner_active; ot->flag = 0; ot->prop = RNA_def_enum(ot->srna, "type", prop_modifier_op_types, 0, "Modifier Operation", ""); } /** \} */ /* -------------------------------------------------------------------- */ /** \name Data Menu Operator * \{ */ /* XXX: select linked is for RNA structs only. */ static const EnumPropertyItem prop_data_op_types[] = { {OL_DOP_SELECT, "SELECT", 0, "Select", ""}, {OL_DOP_DESELECT, "DESELECT", 0, "Deselect", ""}, {OL_DOP_HIDE, "HIDE", 0, "Hide", ""}, {OL_DOP_UNHIDE, "UNHIDE", 0, "Unhide", ""}, {OL_DOP_SELECT_LINKED, "SELECT_LINKED", 0, "Select Linked", ""}, {0, NULL, 0, NULL, NULL}, }; static int outliner_data_operation_exec(bContext *C, wmOperator *op) { SpaceOutliner *space_outliner = CTX_wm_space_outliner(C); int scenelevel = 0, objectlevel = 0, idlevel = 0, datalevel = 0; /* check for invalid states */ if (space_outliner == NULL) { return OPERATOR_CANCELLED; } TreeElement *te = get_target_element(space_outliner); get_element_operation_type(te, &scenelevel, &objectlevel, &idlevel, &datalevel); eOutliner_PropDataOps event = RNA_enum_get(op->ptr, "type"); switch (datalevel) { case TSE_POSE_CHANNEL: { outliner_do_data_operation( space_outliner, datalevel, event, &space_outliner->tree, pchan_fn, NULL); WM_event_add_notifier(C, NC_OBJECT | ND_POSE, NULL); ED_undo_push(C, "PoseChannel operation"); break; } case TSE_BONE: { outliner_do_data_operation( space_outliner, datalevel, event, &space_outliner->tree, bone_fn, NULL); WM_event_add_notifier(C, NC_OBJECT | ND_POSE, NULL); ED_undo_push(C, "Bone operation"); break; } case TSE_EBONE: { outliner_do_data_operation( space_outliner, datalevel, event, &space_outliner->tree, ebone_fn, NULL); WM_event_add_notifier(C, NC_OBJECT | ND_POSE, NULL); ED_undo_push(C, "EditBone operation"); break; } case TSE_SEQUENCE: { Scene *scene = CTX_data_scene(C); outliner_do_data_operation( space_outliner, datalevel, event, &space_outliner->tree, sequence_fn, scene); break; } case TSE_GP_LAYER: { outliner_do_data_operation( space_outliner, datalevel, event, &space_outliner->tree, gpencil_layer_fn, NULL); WM_event_add_notifier(C, NC_GPENCIL | ND_DATA, NULL); ED_undo_push(C, "Grease Pencil Layer operation"); break; } case TSE_RNA_STRUCT: if (event == OL_DOP_SELECT_LINKED) { outliner_do_data_operation( space_outliner, datalevel, event, &space_outliner->tree, data_select_linked_fn, C); } break; default: BKE_report(op->reports, RPT_WARNING, "Not yet implemented"); break; } return OPERATOR_FINISHED; } void OUTLINER_OT_data_operation(wmOperatorType *ot) { /* identifiers */ ot->name = "Outliner Data Operation"; ot->idname = "OUTLINER_OT_data_operation"; /* callbacks */ ot->invoke = WM_menu_invoke; ot->exec = outliner_data_operation_exec; ot->poll = ED_operator_outliner_active; ot->flag = 0; ot->prop = RNA_def_enum(ot->srna, "type", prop_data_op_types, 0, "Data Operation", ""); } /** \} */ /* -------------------------------------------------------------------- */ /** \name Context Menu Operator * \{ */ static int outliner_operator_menu(bContext *C, const char *opname) { wmOperatorType *ot = WM_operatortype_find(opname, false); uiPopupMenu *pup = UI_popup_menu_begin(C, WM_operatortype_name(ot, NULL), ICON_NONE); uiLayout *layout = UI_popup_menu_layout(pup); /* set this so the default execution context is the same as submenus */ uiLayoutSetOperatorContext(layout, WM_OP_INVOKE_REGION_WIN); uiItemsEnumO(layout, ot->idname, RNA_property_identifier(ot->prop)); uiItemS(layout); uiItemMContents(layout, "OUTLINER_MT_context_menu"); UI_popup_menu_end(C, pup); return OPERATOR_INTERFACE; } static int do_outliner_operation_event(bContext *C, ReportList *reports, ARegion *region, SpaceOutliner *space_outliner, TreeElement *te) { int scenelevel = 0, objectlevel = 0, idlevel = 0, datalevel = 0; TreeStoreElem *tselem = TREESTORE(te); int select_flag = OL_ITEM_ACTIVATE | OL_ITEM_SELECT; if (tselem->flag & TSE_SELECTED) { select_flag |= OL_ITEM_EXTEND; } outliner_item_select(C, space_outliner, te, select_flag); /* Only redraw, don't rebuild here because TreeElement pointers will * become invalid and operations will crash. */ ED_region_tag_redraw_no_rebuild(region); ED_outliner_select_sync_from_outliner(C, space_outliner); get_element_operation_type(te, &scenelevel, &objectlevel, &idlevel, &datalevel); if (scenelevel) { if (objectlevel || datalevel || idlevel) { BKE_report(reports, RPT_WARNING, "Mixed selection"); return OPERATOR_CANCELLED; } return outliner_operator_menu(C, "OUTLINER_OT_scene_operation"); } if (objectlevel) { WM_menu_name_call(C, "OUTLINER_MT_object", WM_OP_INVOKE_REGION_WIN); return OPERATOR_FINISHED; } if (idlevel) { if (idlevel == -1 || datalevel) { BKE_report(reports, RPT_WARNING, "Mixed selection"); return OPERATOR_CANCELLED; } switch (idlevel) { case ID_GR: WM_menu_name_call(C, "OUTLINER_MT_collection", WM_OP_INVOKE_REGION_WIN); return OPERATOR_FINISHED; break; case ID_LI: return outliner_operator_menu(C, "OUTLINER_OT_lib_operation"); break; default: return outliner_operator_menu(C, "OUTLINER_OT_id_operation"); break; } } else if (datalevel) { if (datalevel == -1) { BKE_report(reports, RPT_WARNING, "Mixed selection"); return OPERATOR_CANCELLED; } if (datalevel == TSE_ANIM_DATA) { return outliner_operator_menu(C, "OUTLINER_OT_animdata_operation"); } if (datalevel == TSE_DRIVER_BASE) { /* do nothing... no special ops needed yet */ return OPERATOR_CANCELLED; } if (datalevel == TSE_LAYER_COLLECTION) { WM_menu_name_call(C, "OUTLINER_MT_collection", WM_OP_INVOKE_REGION_WIN); return OPERATOR_FINISHED; } if (ELEM(datalevel, TSE_SCENE_COLLECTION_BASE, TSE_VIEW_COLLECTION_BASE)) { WM_menu_name_call(C, "OUTLINER_MT_collection_new", WM_OP_INVOKE_REGION_WIN); return OPERATOR_FINISHED; } if (datalevel == TSE_ID_BASE) { /* do nothing... there are no ops needed here yet */ return OPERATOR_CANCELLED; } if (datalevel == TSE_CONSTRAINT) { return outliner_operator_menu(C, "OUTLINER_OT_constraint_operation"); } if (datalevel == TSE_MODIFIER) { return outliner_operator_menu(C, "OUTLINER_OT_modifier_operation"); } return outliner_operator_menu(C, "OUTLINER_OT_data_operation"); } return OPERATOR_CANCELLED; } static int outliner_operation(bContext *C, wmOperator *op, const wmEvent *event) { ARegion *region = CTX_wm_region(C); SpaceOutliner *space_outliner = CTX_wm_space_outliner(C); uiBut *but = UI_context_active_but_get(C); float view_mval[2]; if (but) { UI_but_tooltip_timer_remove(C, but); } UI_view2d_region_to_view( &region->v2d, event->mval[0], event->mval[1], &view_mval[0], &view_mval[1]); TreeElement *hovered_te = outliner_find_item_at_y( space_outliner, &space_outliner->tree, view_mval[1]); if (!hovered_te) { /* Let this fall through to 'OUTLINER_MT_context_menu'. */ return OPERATOR_PASS_THROUGH; } return do_outliner_operation_event(C, op->reports, region, space_outliner, hovered_te); } /* Menu only! Calls other operators */ void OUTLINER_OT_operation(wmOperatorType *ot) { ot->name = "Context Menu"; ot->idname = "OUTLINER_OT_operation"; ot->description = "Context menu for item operations"; ot->invoke = outliner_operation; ot->poll = ED_operator_outliner_active; } /** \} */
32.456462
99
0.597398
[ "mesh", "render", "object" ]
9af424716fb2987a79eb3eac97775e365ebec5b5
5,111
h
C
searchlib/src/vespa/searchlib/query/tree/termnodes.h
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
1
2020-06-02T13:28:29.000Z
2020-06-02T13:28:29.000Z
searchlib/src/vespa/searchlib/query/tree/termnodes.h
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
1
2021-03-31T22:24:20.000Z
2021-03-31T22:24:20.000Z
searchlib/src/vespa/searchlib/query/tree/termnodes.h
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
1
2020-09-03T11:39:52.000Z
2020-09-03T11:39:52.000Z
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include "location.h" #include "predicate_query_term.h" #include "querynodemixin.h" #include "range.h" #include "term.h" namespace search::query { typedef TermBase<vespalib::string> StringBase; class NumberTerm : public QueryNodeMixin<NumberTerm, StringBase > { public: NumberTerm(Type term, vespalib::stringref view, int32_t id, Weight weight) : QueryNodeMixinType(term, view, id, weight) {} virtual ~NumberTerm() = 0; }; //----------------------------------------------------------------------------- class PrefixTerm : public QueryNodeMixin<PrefixTerm, StringBase > { public: PrefixTerm(const Type &term, vespalib::stringref view, int32_t id, Weight weight) : QueryNodeMixinType(term, view, id, weight) {} virtual ~PrefixTerm() = 0; }; //----------------------------------------------------------------------------- class RangeTerm : public QueryNodeMixin<RangeTerm, TermBase<Range> > { public: RangeTerm(const Type& term, vespalib::stringref view, int32_t id, Weight weight) : QueryNodeMixinType(term, view, id, weight) {} virtual ~RangeTerm() = 0; }; //----------------------------------------------------------------------------- class StringTerm : public QueryNodeMixin<StringTerm, StringBase > { public: StringTerm(const Type &term, vespalib::stringref view, int32_t id, Weight weight); virtual ~StringTerm() = 0; }; //----------------------------------------------------------------------------- class SubstringTerm : public QueryNodeMixin<SubstringTerm, StringBase > { public: SubstringTerm(const Type &term, vespalib::stringref view, int32_t id, Weight weight) : QueryNodeMixinType(term, view, id, weight) {} virtual ~SubstringTerm() = 0; }; //----------------------------------------------------------------------------- class SuffixTerm : public QueryNodeMixin<SuffixTerm, StringBase > { public: SuffixTerm(const Type &term, vespalib::stringref view, int32_t id, Weight weight) : QueryNodeMixinType(term, view, id, weight) {} virtual ~SuffixTerm() = 0; }; //----------------------------------------------------------------------------- class LocationTerm : public QueryNodeMixin<LocationTerm, TermBase<Location> > { public: LocationTerm(const Type &term, vespalib::stringref view, int32_t id, Weight weight) : QueryNodeMixinType(term, view, id, weight) {} virtual ~LocationTerm() = 0; }; //----------------------------------------------------------------------------- class PredicateQuery : public QueryNodeMixin<PredicateQuery, TermBase<PredicateQueryTerm::UP> > { public: PredicateQuery(PredicateQueryTerm::UP term, vespalib::stringref view, int32_t id, Weight weight) : QueryNodeMixinType(std::move(term), view, id, weight) {} }; //----------------------------------------------------------------------------- class RegExpTerm : public QueryNodeMixin<RegExpTerm, StringBase> { public: RegExpTerm(const Type &term, vespalib::stringref view, int32_t id, Weight weight) : QueryNodeMixinType(term, view, id, weight) {} virtual ~RegExpTerm() = 0; }; /** * Term matching the K nearest neighbors in a multi-dimensional vector space. * * The query point is specified as a dense tensor of order 1. * This is found in fef::IQueryEnvironment using the query tensor name as key. * The field name is the name of a dense document tensor of order 1. * Both tensors are validated to have the same tensor type before the query is sent to the backend. * * Target num hits (K) is a hint to how many neighbors to return. * The actual returned number might be higher (or lower if the query returns fewer hits). */ class NearestNeighborTerm : public QueryNodeMixin<NearestNeighborTerm, TermNode> { private: vespalib::string _query_tensor_name; uint32_t _target_num_hits; bool _allow_approximate; uint32_t _explore_additional_hits; public: NearestNeighborTerm(vespalib::stringref query_tensor_name, vespalib::stringref field_name, int32_t id, Weight weight, uint32_t target_num_hits, bool allow_approximate, uint32_t explore_additional_hits) : QueryNodeMixinType(field_name, id, weight), _query_tensor_name(query_tensor_name), _target_num_hits(target_num_hits), _allow_approximate(allow_approximate), _explore_additional_hits(explore_additional_hits) {} virtual ~NearestNeighborTerm() {} const vespalib::string& get_query_tensor_name() const { return _query_tensor_name; } uint32_t get_target_num_hits() const { return _target_num_hits; } bool get_allow_approximate() const { return _allow_approximate; } uint32_t get_explore_additional_hits() const { return _explore_additional_hits; } }; }
33.405229
118
0.608883
[ "vector" ]
9af9abf91a1676b368b0a0b0c252c0f53cd181b7
3,594
h
C
Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/EditorModeFeedback/EditorEditorModeFeedbackSystemComponent.h
Jackerty/o3de
f521a288cf020d166949c1dc243c4938539b5244
[ "Apache-2.0", "MIT" ]
1
2022-03-28T08:06:58.000Z
2022-03-28T08:06:58.000Z
Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/EditorModeFeedback/EditorEditorModeFeedbackSystemComponent.h
Jackerty/o3de
f521a288cf020d166949c1dc243c4938539b5244
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/AtomLyIntegration/CommonFeatures/Code/Source/PostProcess/EditorModeFeedback/EditorEditorModeFeedbackSystemComponent.h
Jackerty/o3de
f521a288cf020d166949c1dc243c4938539b5244
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once #include <AzCore/std/containers/unordered_map.h> #include <AzCore/std/containers/vector.h> #include <AzCore/std/functional.h> #include <AzCore/Component/Component.h> #include <AzCore/Component/TickBus.h> #include <AzToolsFramework/ToolsComponents/EditorComponentBase.h> #include <AzToolsFramework/API/ViewportEditorModeTrackerNotificationBus.h> #include <Atom/Feature/PostProcess/EditorModeFeedback/EditorModeFeedbackInterface.h> #include <Atom/RPI.Reflect/Model/ModelLodIndex.h> #include <AtomCore/Instance/Instance.h> namespace AZ { namespace RPI { class MeshDrawPacket; class Material; } namespace Render { //! Component for the editor mode feedback system. class EditorEditorModeFeedbackSystemComponent : public AzToolsFramework::Components::EditorComponentBase , public EditorModeFeedbackInterface , public AZ::TickBus::Handler , private AzToolsFramework::ViewportEditorModeNotificationsBus::Handler { public: AZ_EDITOR_COMPONENT(EditorEditorModeFeedbackSystemComponent, "{A88EE29D-4C72-4995-B3BD-41EEDE480487}"); static void Reflect(AZ::ReflectContext* context); ~EditorEditorModeFeedbackSystemComponent(); // EditorComponentBase overrides ... void Activate() override; void Deactivate() override; // EditorModeFeedbackInterface overrides ... bool IsEnabled() const override; void RegisterOrUpdateDrawableComponent( EntityComponentIdPair entityComponentId, const MeshFeatureProcessorInterface::MeshHandle& meshHandle) override; private: // ViewportEditorModeNotificationsBus overrides ... void OnEditorModeActivated( const AzToolsFramework::ViewportEditorModesInterface& editorModeState, AzToolsFramework::ViewportEditorMode mode) override; void OnEditorModeDeactivated( const AzToolsFramework::ViewportEditorModesInterface& editorModeState, AzToolsFramework::ViewportEditorMode mode) override; // TickBus overrides ... void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; int GetTickOrder() override; //! Flag to specify whether or not the editor feedback effects are active. bool m_enabled = false; //! Data to construct draw packets for meshes. struct MeshHandleDrawPackets { ~MeshHandleDrawPackets(); const MeshFeatureProcessorInterface::MeshHandle* m_meshHandle; RPI::ModelLodIndex m_modelLodIndex = RPI::ModelLodIndex::Null; AZStd::vector<RPI::MeshDrawPacket> m_meshDrawPackets; }; //! Map for entities and their drawable components. AZStd::unordered_map<EntityId, AZStd::unordered_map<ComponentId, MeshHandleDrawPackets>> m_entityComponentMeshHandleDrawPackets; //! Material for sending draw packets to the entity mask pass. Data::Instance<RPI::Material> m_maskMaterial = nullptr; //! Settings registery override for enabling/disabling editor mode feedback. bool m_registeryEnabled = false; }; } // namespace Render } // namespace AZ
39.933333
140
0.684196
[ "render", "vector", "model", "3d" ]
9afe68f9d2d24e3383cc82edec4369c622d13334
3,933
h
C
aws-cpp-sdk-storagegateway/include/aws/storagegateway/model/ListAutomaticTapeCreationPoliciesResult.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-storagegateway/include/aws/storagegateway/model/ListAutomaticTapeCreationPoliciesResult.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-storagegateway/include/aws/storagegateway/model/ListAutomaticTapeCreationPoliciesResult.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/storagegateway/StorageGateway_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/storagegateway/model/AutomaticTapeCreationPolicyInfo.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace StorageGateway { namespace Model { class AWS_STORAGEGATEWAY_API ListAutomaticTapeCreationPoliciesResult { public: ListAutomaticTapeCreationPoliciesResult(); ListAutomaticTapeCreationPoliciesResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); ListAutomaticTapeCreationPoliciesResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>Gets a listing of information about the gateway's automatic tape creation * policies, including the automatic tape creation rules and the gateway that is * using the policies.</p> */ inline const Aws::Vector<AutomaticTapeCreationPolicyInfo>& GetAutomaticTapeCreationPolicyInfos() const{ return m_automaticTapeCreationPolicyInfos; } /** * <p>Gets a listing of information about the gateway's automatic tape creation * policies, including the automatic tape creation rules and the gateway that is * using the policies.</p> */ inline void SetAutomaticTapeCreationPolicyInfos(const Aws::Vector<AutomaticTapeCreationPolicyInfo>& value) { m_automaticTapeCreationPolicyInfos = value; } /** * <p>Gets a listing of information about the gateway's automatic tape creation * policies, including the automatic tape creation rules and the gateway that is * using the policies.</p> */ inline void SetAutomaticTapeCreationPolicyInfos(Aws::Vector<AutomaticTapeCreationPolicyInfo>&& value) { m_automaticTapeCreationPolicyInfos = std::move(value); } /** * <p>Gets a listing of information about the gateway's automatic tape creation * policies, including the automatic tape creation rules and the gateway that is * using the policies.</p> */ inline ListAutomaticTapeCreationPoliciesResult& WithAutomaticTapeCreationPolicyInfos(const Aws::Vector<AutomaticTapeCreationPolicyInfo>& value) { SetAutomaticTapeCreationPolicyInfos(value); return *this;} /** * <p>Gets a listing of information about the gateway's automatic tape creation * policies, including the automatic tape creation rules and the gateway that is * using the policies.</p> */ inline ListAutomaticTapeCreationPoliciesResult& WithAutomaticTapeCreationPolicyInfos(Aws::Vector<AutomaticTapeCreationPolicyInfo>&& value) { SetAutomaticTapeCreationPolicyInfos(std::move(value)); return *this;} /** * <p>Gets a listing of information about the gateway's automatic tape creation * policies, including the automatic tape creation rules and the gateway that is * using the policies.</p> */ inline ListAutomaticTapeCreationPoliciesResult& AddAutomaticTapeCreationPolicyInfos(const AutomaticTapeCreationPolicyInfo& value) { m_automaticTapeCreationPolicyInfos.push_back(value); return *this; } /** * <p>Gets a listing of information about the gateway's automatic tape creation * policies, including the automatic tape creation rules and the gateway that is * using the policies.</p> */ inline ListAutomaticTapeCreationPoliciesResult& AddAutomaticTapeCreationPolicyInfos(AutomaticTapeCreationPolicyInfo&& value) { m_automaticTapeCreationPolicyInfos.push_back(std::move(value)); return *this; } private: Aws::Vector<AutomaticTapeCreationPolicyInfo> m_automaticTapeCreationPolicyInfos; }; } // namespace Model } // namespace StorageGateway } // namespace Aws
42.290323
214
0.763794
[ "vector", "model" ]
b100ac68fff68eb3625a5ece2bba7cf2ee983d51
861,102
c
C
src/xmlschemas.c
djp952/prebuilt-libxml2
8f067d2965c964bf4ba35ad1c0a3f5c313a2fa0f
[ "AML" ]
2
2020-07-24T11:11:36.000Z
2022-03-17T13:33:59.000Z
src/xmlschemas.c
djp952/prebuilt-libxml2
8f067d2965c964bf4ba35ad1c0a3f5c313a2fa0f
[ "AML" ]
null
null
null
src/xmlschemas.c
djp952/prebuilt-libxml2
8f067d2965c964bf4ba35ad1c0a3f5c313a2fa0f
[ "AML" ]
3
2020-02-20T12:24:55.000Z
2021-03-19T08:41:48.000Z
/* * schemas.c : implementation of the XML Schema handling and * schema validity checking * * See Copyright for the status of this software. * * Daniel Veillard <veillard@redhat.com> */ /* * TODO: * - when types are redefined in includes, check that all * types in the redef list are equal * -> need a type equality operation. * - if we don't intend to use the schema for schemas, we * need to validate all schema attributes (ref, type, name) * against their types. * - Eliminate item creation for: ?? * * URGENT TODO: * - For xsi-driven schema acquisition, augment the IDCs after every * acquisition episode (xmlSchemaAugmentIDC). * * NOTES: * - Eliminated item creation for: <restriction>, <extension>, * <simpleContent>, <complexContent>, <list>, <union> * * PROBLEMS: * - http://lists.w3.org/Archives/Public/www-xml-schema-comments/2005JulSep/0337.html * IDC XPath expression and chameleon includes: the targetNamespace is changed, so * XPath will have trouble to resolve to this namespace, since not known. * * * CONSTRAINTS: * * Schema Component Constraint: * All Group Limited (cos-all-limited) * Status: complete * (1.2) * In xmlSchemaGroupDefReferenceTermFixup() and * (2) * In xmlSchemaParseModelGroup() * TODO: Actually this should go to component-level checks, * but is done here due to performance. Move it to an other layer * is schema construction via an API is implemented. */ /* To avoid EBCDIC trouble when parsing on zOS */ #if defined(__MVS__) #pragma convert("ISO8859-1") #endif #define IN_LIBXML #include "libxml.h" #ifdef LIBXML_SCHEMAS_ENABLED #include <string.h> #include <libxml/xmlmemory.h> #include <libxml/parser.h> #include <libxml/parserInternals.h> #include <libxml/hash.h> #include <libxml/uri.h> #include <libxml/xmlschemas.h> #include <libxml/schemasInternals.h> #include <libxml/xmlschemastypes.h> #include <libxml/xmlautomata.h> #include <libxml/xmlregexp.h> #include <libxml/dict.h> #include <libxml/encoding.h> #include <libxml/xmlIO.h> #ifdef LIBXML_PATTERN_ENABLED #include <libxml/pattern.h> #endif #ifdef LIBXML_READER_ENABLED #include <libxml/xmlreader.h> #endif /* #define DEBUG 1 */ /* #define DEBUG_CONTENT 1 */ /* #define DEBUG_TYPE 1 */ /* #define DEBUG_CONTENT_REGEXP 1 */ /* #define DEBUG_AUTOMATA 1 */ /* #define DEBUG_IDC */ /* #define DEBUG_IDC_NODE_TABLE */ /* #define WXS_ELEM_DECL_CONS_ENABLED */ #ifdef DEBUG_IDC #ifndef DEBUG_IDC_NODE_TABLE #define DEBUG_IDC_NODE_TABLE #endif #endif /* #define ENABLE_PARTICLE_RESTRICTION 1 */ #define ENABLE_REDEFINE /* #define ENABLE_NAMED_LOCALS */ /* #define ENABLE_IDC_NODE_TABLES_TEST */ #define DUMP_CONTENT_MODEL #ifdef LIBXML_READER_ENABLED /* #define XML_SCHEMA_READER_ENABLED */ #endif #define UNBOUNDED (1 << 30) #define TODO \ xmlGenericError(xmlGenericErrorContext, \ "Unimplemented block at %s:%d\n", \ __FILE__, __LINE__); #define XML_SCHEMAS_NO_NAMESPACE (const xmlChar *) "##" /* * The XML Schemas namespaces */ static const xmlChar *xmlSchemaNs = (const xmlChar *) "http://www.w3.org/2001/XMLSchema"; static const xmlChar *xmlSchemaInstanceNs = (const xmlChar *) "http://www.w3.org/2001/XMLSchema-instance"; static const xmlChar *xmlNamespaceNs = (const xmlChar *) "http://www.w3.org/2000/xmlns/"; /* * Come casting macros. */ #define ACTXT_CAST (xmlSchemaAbstractCtxtPtr) #define PCTXT_CAST (xmlSchemaParserCtxtPtr) #define VCTXT_CAST (xmlSchemaValidCtxtPtr) #define WXS_BASIC_CAST (xmlSchemaBasicItemPtr) #define WXS_TREE_CAST (xmlSchemaTreeItemPtr) #define WXS_PTC_CAST (xmlSchemaParticlePtr) #define WXS_TYPE_CAST (xmlSchemaTypePtr) #define WXS_ELEM_CAST (xmlSchemaElementPtr) #define WXS_ATTR_GROUP_CAST (xmlSchemaAttributeGroupPtr) #define WXS_ATTR_CAST (xmlSchemaAttributePtr) #define WXS_ATTR_USE_CAST (xmlSchemaAttributeUsePtr) #define WXS_ATTR_PROHIB_CAST (xmlSchemaAttributeUseProhibPtr) #define WXS_MODEL_GROUPDEF_CAST (xmlSchemaModelGroupDefPtr) #define WXS_MODEL_GROUP_CAST (xmlSchemaModelGroupPtr) #define WXS_IDC_CAST (xmlSchemaIDCPtr) #define WXS_QNAME_CAST (xmlSchemaQNameRefPtr) #define WXS_LIST_CAST (xmlSchemaItemListPtr) /* * Macros to query common properties of components. */ #define WXS_ITEM_NODE(i) xmlSchemaGetComponentNode(WXS_BASIC_CAST (i)) #define WXS_ITEM_TYPE_NAME(i) xmlSchemaGetComponentTypeStr(WXS_BASIC_CAST (i)) /* * Macros for element declarations. */ #define WXS_ELEM_TYPEDEF(e) (e)->subtypes #define WXS_SUBST_HEAD(item) (item)->refDecl /* * Macros for attribute declarations. */ #define WXS_ATTR_TYPEDEF(a) (a)->subtypes /* * Macros for attribute uses. */ #define WXS_ATTRUSE_DECL(au) (WXS_ATTR_USE_CAST (au))->attrDecl #define WXS_ATTRUSE_TYPEDEF(au) WXS_ATTR_TYPEDEF(WXS_ATTRUSE_DECL( WXS_ATTR_USE_CAST au)) #define WXS_ATTRUSE_DECL_NAME(au) (WXS_ATTRUSE_DECL(au))->name #define WXS_ATTRUSE_DECL_TNS(au) (WXS_ATTRUSE_DECL(au))->targetNamespace /* * Macros for attribute groups. */ #define WXS_ATTR_GROUP_HAS_REFS(ag) ((WXS_ATTR_GROUP_CAST (ag))->flags & XML_SCHEMAS_ATTRGROUP_HAS_REFS) #define WXS_ATTR_GROUP_EXPANDED(ag) ((WXS_ATTR_GROUP_CAST (ag))->flags & XML_SCHEMAS_ATTRGROUP_WILDCARD_BUILDED) /* * Macros for particles. */ #define WXS_PARTICLE(p) WXS_PTC_CAST (p) #define WXS_PARTICLE_TERM(p) (WXS_PARTICLE(p))->children #define WXS_PARTICLE_TERM_AS_ELEM(p) (WXS_ELEM_CAST WXS_PARTICLE_TERM(p)) #define WXS_PARTICLE_MODEL(p) WXS_MODEL_GROUP_CAST WXS_PARTICLE(p)->children /* * Macros for model groups definitions. */ #define WXS_MODELGROUPDEF_MODEL(mgd) (WXS_MODEL_GROUP_CAST (mgd))->children /* * Macros for model groups. */ #define WXS_IS_MODEL_GROUP(i) \ (((i)->type == XML_SCHEMA_TYPE_SEQUENCE) || \ ((i)->type == XML_SCHEMA_TYPE_CHOICE) || \ ((i)->type == XML_SCHEMA_TYPE_ALL)) #define WXS_MODELGROUP_PARTICLE(mg) WXS_PTC_CAST (mg)->children /* * Macros for schema buckets. */ #define WXS_IS_BUCKET_INCREDEF(t) (((t) == XML_SCHEMA_SCHEMA_INCLUDE) || \ ((t) == XML_SCHEMA_SCHEMA_REDEFINE)) #define WXS_IS_BUCKET_IMPMAIN(t) (((t) == XML_SCHEMA_SCHEMA_MAIN) || \ ((t) == XML_SCHEMA_SCHEMA_IMPORT)) #define WXS_IMPBUCKET(b) ((xmlSchemaImportPtr) (b)) #define WXS_INCBUCKET(b) ((xmlSchemaIncludePtr) (b)) /* * Macros for complex/simple types. */ #define WXS_IS_ANYTYPE(i) \ (( (i)->type == XML_SCHEMA_TYPE_BASIC) && \ ( (WXS_TYPE_CAST (i))->builtInType == XML_SCHEMAS_ANYTYPE)) #define WXS_IS_COMPLEX(i) \ (((i)->type == XML_SCHEMA_TYPE_COMPLEX) || \ ((i)->builtInType == XML_SCHEMAS_ANYTYPE)) #define WXS_IS_SIMPLE(item) \ ((item->type == XML_SCHEMA_TYPE_SIMPLE) || \ ((item->type == XML_SCHEMA_TYPE_BASIC) && \ (item->builtInType != XML_SCHEMAS_ANYTYPE))) #define WXS_IS_ANY_SIMPLE_TYPE(i) \ (((i)->type == XML_SCHEMA_TYPE_BASIC) && \ ((i)->builtInType == XML_SCHEMAS_ANYSIMPLETYPE)) #define WXS_IS_RESTRICTION(t) \ ((t)->flags & XML_SCHEMAS_TYPE_DERIVATION_METHOD_RESTRICTION) #define WXS_IS_EXTENSION(t) \ ((t)->flags & XML_SCHEMAS_TYPE_DERIVATION_METHOD_EXTENSION) #define WXS_IS_TYPE_NOT_FIXED(i) \ (((i)->type != XML_SCHEMA_TYPE_BASIC) && \ (((i)->flags & XML_SCHEMAS_TYPE_INTERNAL_RESOLVED) == 0)) #define WXS_IS_TYPE_NOT_FIXED_1(item) \ (((item)->type != XML_SCHEMA_TYPE_BASIC) && \ (((item)->flags & XML_SCHEMAS_TYPE_FIXUP_1) == 0)) #define WXS_TYPE_IS_GLOBAL(t) ((t)->flags & XML_SCHEMAS_TYPE_GLOBAL) #define WXS_TYPE_IS_LOCAL(t) (((t)->flags & XML_SCHEMAS_TYPE_GLOBAL) == 0) /* * Macros for exclusively for complex types. */ #define WXS_HAS_COMPLEX_CONTENT(item) \ ((item->contentType == XML_SCHEMA_CONTENT_MIXED) || \ (item->contentType == XML_SCHEMA_CONTENT_EMPTY) || \ (item->contentType == XML_SCHEMA_CONTENT_ELEMENTS)) #define WXS_HAS_SIMPLE_CONTENT(item) \ ((item->contentType == XML_SCHEMA_CONTENT_SIMPLE) || \ (item->contentType == XML_SCHEMA_CONTENT_BASIC)) #define WXS_HAS_MIXED_CONTENT(item) \ (item->contentType == XML_SCHEMA_CONTENT_MIXED) #define WXS_EMPTIABLE(t) \ (xmlSchemaIsParticleEmptiable(WXS_PTC_CAST (t)->subtypes)) #define WXS_TYPE_CONTENTTYPE(t) (t)->subtypes #define WXS_TYPE_PARTICLE(t) WXS_PTC_CAST (t)->subtypes #define WXS_TYPE_PARTICLE_TERM(t) WXS_PARTICLE_TERM(WXS_TYPE_PARTICLE(t)) /* * Macros for exclusively for simple types. */ #define WXS_LIST_ITEMTYPE(t) (t)->subtypes #define WXS_IS_ATOMIC(t) (t->flags & XML_SCHEMAS_TYPE_VARIETY_ATOMIC) #define WXS_IS_LIST(t) (t->flags & XML_SCHEMAS_TYPE_VARIETY_LIST) #define WXS_IS_UNION(t) (t->flags & XML_SCHEMAS_TYPE_VARIETY_UNION) /* * Misc parser context macros. */ #define WXS_CONSTRUCTOR(ctx) (ctx)->constructor #define WXS_HAS_BUCKETS(ctx) \ ( (WXS_CONSTRUCTOR((ctx))->buckets != NULL) && \ (WXS_CONSTRUCTOR((ctx))->buckets->nbItems > 0) ) #define WXS_SUBST_GROUPS(ctx) WXS_CONSTRUCTOR((ctx))->substGroups #define WXS_BUCKET(ctx) WXS_CONSTRUCTOR((ctx))->bucket #define WXS_SCHEMA(ctx) (ctx)->schema #define WXS_ADD_LOCAL(ctx, item) \ xmlSchemaAddItemSize(&(WXS_BUCKET(ctx)->locals), 10, item) #define WXS_ADD_GLOBAL(ctx, item) \ xmlSchemaAddItemSize(&(WXS_BUCKET(ctx)->globals), 5, item) #define WXS_ADD_PENDING(ctx, item) \ xmlSchemaAddItemSize(&((ctx)->constructor->pending), 10, item) /* * xmlSchemaItemList macros. */ #define WXS_ILIST_IS_EMPTY(l) ((l == NULL) || ((l)->nbItems == 0)) /* * Misc macros. */ #define IS_SCHEMA(node, type) \ ((node != NULL) && (node->ns != NULL) && \ (xmlStrEqual(node->name, (const xmlChar *) type)) && \ (xmlStrEqual(node->ns->href, xmlSchemaNs))) #define FREE_AND_NULL(str) if ((str) != NULL) { xmlFree((xmlChar *) (str)); str = NULL; } /* * Since we put the default/fixed values into the dict, we can * use pointer comparison for those values. * REMOVED: (xmlStrEqual((v1), (v2))) */ #define WXS_ARE_DEFAULT_STR_EQUAL(v1, v2) ((v1) == (v2)) #define INODE_NILLED(item) (item->flags & XML_SCHEMA_ELEM_INFO_NILLED) #define CAN_PARSE_SCHEMA(b) (((b)->doc != NULL) && ((b)->parsed == 0)) #define HFAILURE if (res == -1) goto exit_failure; #define HERROR if (res != 0) goto exit_error; #define HSTOP(ctx) if ((ctx)->stop) goto exit; /* * Some flags used for various schema constraints. */ #define SUBSET_RESTRICTION 1<<0 #define SUBSET_EXTENSION 1<<1 #define SUBSET_SUBSTITUTION 1<<2 #define SUBSET_LIST 1<<3 #define SUBSET_UNION 1<<4 typedef struct _xmlSchemaNodeInfo xmlSchemaNodeInfo; typedef xmlSchemaNodeInfo *xmlSchemaNodeInfoPtr; typedef struct _xmlSchemaItemList xmlSchemaItemList; typedef xmlSchemaItemList *xmlSchemaItemListPtr; struct _xmlSchemaItemList { void **items; /* used for dynamic addition of schemata */ int nbItems; /* used for dynamic addition of schemata */ int sizeItems; /* used for dynamic addition of schemata */ }; #define XML_SCHEMA_CTXT_PARSER 1 #define XML_SCHEMA_CTXT_VALIDATOR 2 typedef struct _xmlSchemaAbstractCtxt xmlSchemaAbstractCtxt; typedef xmlSchemaAbstractCtxt *xmlSchemaAbstractCtxtPtr; struct _xmlSchemaAbstractCtxt { int type; /* E.g. XML_SCHEMA_CTXT_VALIDATOR */ void *dummy; /* Fix alignment issues */ }; typedef struct _xmlSchemaBucket xmlSchemaBucket; typedef xmlSchemaBucket *xmlSchemaBucketPtr; #define XML_SCHEMA_SCHEMA_MAIN 0 #define XML_SCHEMA_SCHEMA_IMPORT 1 #define XML_SCHEMA_SCHEMA_INCLUDE 2 #define XML_SCHEMA_SCHEMA_REDEFINE 3 /** * xmlSchemaSchemaRelation: * * Used to create a graph of schema relationships. */ typedef struct _xmlSchemaSchemaRelation xmlSchemaSchemaRelation; typedef xmlSchemaSchemaRelation *xmlSchemaSchemaRelationPtr; struct _xmlSchemaSchemaRelation { xmlSchemaSchemaRelationPtr next; int type; /* E.g. XML_SCHEMA_SCHEMA_IMPORT */ const xmlChar *importNamespace; xmlSchemaBucketPtr bucket; }; #define XML_SCHEMA_BUCKET_MARKED 1<<0 #define XML_SCHEMA_BUCKET_COMPS_ADDED 1<<1 struct _xmlSchemaBucket { int type; int flags; const xmlChar *schemaLocation; const xmlChar *origTargetNamespace; const xmlChar *targetNamespace; xmlDocPtr doc; xmlSchemaSchemaRelationPtr relations; int located; int parsed; int imported; int preserveDoc; xmlSchemaItemListPtr globals; /* Global components. */ xmlSchemaItemListPtr locals; /* Local components. */ }; /** * xmlSchemaImport: * (extends xmlSchemaBucket) * * Reflects a schema. Holds some information * about the schema and its toplevel components. Duplicate * toplevel components are not checked at this level. */ typedef struct _xmlSchemaImport xmlSchemaImport; typedef xmlSchemaImport *xmlSchemaImportPtr; struct _xmlSchemaImport { int type; /* Main OR import OR include. */ int flags; const xmlChar *schemaLocation; /* The URI of the schema document. */ /* For chameleon includes, @origTargetNamespace will be NULL */ const xmlChar *origTargetNamespace; /* * For chameleon includes, @targetNamespace will be the * targetNamespace of the including schema. */ const xmlChar *targetNamespace; xmlDocPtr doc; /* The schema node-tree. */ /* @relations will hold any included/imported/redefined schemas. */ xmlSchemaSchemaRelationPtr relations; int located; int parsed; int imported; int preserveDoc; xmlSchemaItemListPtr globals; xmlSchemaItemListPtr locals; /* The imported schema. */ xmlSchemaPtr schema; }; /* * (extends xmlSchemaBucket) */ typedef struct _xmlSchemaInclude xmlSchemaInclude; typedef xmlSchemaInclude *xmlSchemaIncludePtr; struct _xmlSchemaInclude { int type; int flags; const xmlChar *schemaLocation; const xmlChar *origTargetNamespace; const xmlChar *targetNamespace; xmlDocPtr doc; xmlSchemaSchemaRelationPtr relations; int located; int parsed; int imported; int preserveDoc; xmlSchemaItemListPtr globals; /* Global components. */ xmlSchemaItemListPtr locals; /* Local components. */ /* The owning main or import schema bucket. */ xmlSchemaImportPtr ownerImport; }; /** * xmlSchemaBasicItem: * * The abstract base type for schema components. */ typedef struct _xmlSchemaBasicItem xmlSchemaBasicItem; typedef xmlSchemaBasicItem *xmlSchemaBasicItemPtr; struct _xmlSchemaBasicItem { xmlSchemaTypeType type; void *dummy; /* Fix alignment issues */ }; /** * xmlSchemaAnnotItem: * * The abstract base type for annotated schema components. * (Extends xmlSchemaBasicItem) */ typedef struct _xmlSchemaAnnotItem xmlSchemaAnnotItem; typedef xmlSchemaAnnotItem *xmlSchemaAnnotItemPtr; struct _xmlSchemaAnnotItem { xmlSchemaTypeType type; xmlSchemaAnnotPtr annot; }; /** * xmlSchemaTreeItem: * * The abstract base type for tree-like structured schema components. * (Extends xmlSchemaAnnotItem) */ typedef struct _xmlSchemaTreeItem xmlSchemaTreeItem; typedef xmlSchemaTreeItem *xmlSchemaTreeItemPtr; struct _xmlSchemaTreeItem { xmlSchemaTypeType type; xmlSchemaAnnotPtr annot; xmlSchemaTreeItemPtr next; xmlSchemaTreeItemPtr children; }; #define XML_SCHEMA_ATTR_USE_FIXED 1<<0 /** * xmlSchemaAttributeUsePtr: * * The abstract base type for tree-like structured schema components. * (Extends xmlSchemaTreeItem) */ typedef struct _xmlSchemaAttributeUse xmlSchemaAttributeUse; typedef xmlSchemaAttributeUse *xmlSchemaAttributeUsePtr; struct _xmlSchemaAttributeUse { xmlSchemaTypeType type; xmlSchemaAnnotPtr annot; xmlSchemaAttributeUsePtr next; /* The next attr. use. */ /* * The attr. decl. OR a QName-ref. to an attr. decl. OR * a QName-ref. to an attribute group definition. */ xmlSchemaAttributePtr attrDecl; int flags; xmlNodePtr node; int occurs; /* required, optional */ const xmlChar * defValue; xmlSchemaValPtr defVal; }; /** * xmlSchemaAttributeUseProhibPtr: * * A helper component to reflect attribute prohibitions. * (Extends xmlSchemaBasicItem) */ typedef struct _xmlSchemaAttributeUseProhib xmlSchemaAttributeUseProhib; typedef xmlSchemaAttributeUseProhib *xmlSchemaAttributeUseProhibPtr; struct _xmlSchemaAttributeUseProhib { xmlSchemaTypeType type; /* == XML_SCHEMA_EXTRA_ATTR_USE_PROHIB */ xmlNodePtr node; const xmlChar *name; const xmlChar *targetNamespace; int isRef; }; /** * xmlSchemaRedef: */ typedef struct _xmlSchemaRedef xmlSchemaRedef; typedef xmlSchemaRedef *xmlSchemaRedefPtr; struct _xmlSchemaRedef { xmlSchemaRedefPtr next; xmlSchemaBasicItemPtr item; /* The redefining component. */ xmlSchemaBasicItemPtr reference; /* The referencing component. */ xmlSchemaBasicItemPtr target; /* The to-be-redefined component. */ const xmlChar *refName; /* The name of the to-be-redefined component. */ const xmlChar *refTargetNs; /* The target namespace of the to-be-redefined comp. */ xmlSchemaBucketPtr targetBucket; /* The redefined schema. */ }; /** * xmlSchemaConstructionCtxt: */ typedef struct _xmlSchemaConstructionCtxt xmlSchemaConstructionCtxt; typedef xmlSchemaConstructionCtxt *xmlSchemaConstructionCtxtPtr; struct _xmlSchemaConstructionCtxt { xmlSchemaPtr mainSchema; /* The main schema. */ xmlSchemaBucketPtr mainBucket; /* The main schema bucket */ xmlDictPtr dict; xmlSchemaItemListPtr buckets; /* List of schema buckets. */ /* xmlSchemaItemListPtr relations; */ /* List of schema relations. */ xmlSchemaBucketPtr bucket; /* The current schema bucket */ xmlSchemaItemListPtr pending; /* All Components of all schemas that need to be fixed. */ xmlHashTablePtr substGroups; xmlSchemaRedefPtr redefs; xmlSchemaRedefPtr lastRedef; }; #define XML_SCHEMAS_PARSE_ERROR 1 #define SCHEMAS_PARSE_OPTIONS XML_PARSE_NOENT struct _xmlSchemaParserCtxt { int type; void *errCtxt; /* user specific error context */ xmlSchemaValidityErrorFunc error; /* the callback in case of errors */ xmlSchemaValidityWarningFunc warning; /* the callback in case of warning */ int err; int nberrors; xmlStructuredErrorFunc serror; xmlSchemaConstructionCtxtPtr constructor; int ownsConstructor; /* TODO: Move this to parser *flags*. */ /* xmlSchemaPtr topschema; */ /* xmlHashTablePtr namespaces; */ xmlSchemaPtr schema; /* The main schema in use */ int counter; const xmlChar *URL; xmlDocPtr doc; int preserve; /* Whether the doc should be freed */ const char *buffer; int size; /* * Used to build complex element content models */ xmlAutomataPtr am; xmlAutomataStatePtr start; xmlAutomataStatePtr end; xmlAutomataStatePtr state; xmlDictPtr dict; /* dictionary for interned string names */ xmlSchemaTypePtr ctxtType; /* The current context simple/complex type */ int options; xmlSchemaValidCtxtPtr vctxt; int isS4S; int isRedefine; int xsiAssemble; int stop; /* If the parser should stop; i.e. a critical error. */ const xmlChar *targetNamespace; xmlSchemaBucketPtr redefined; /* The schema to be redefined. */ xmlSchemaRedefPtr redef; /* Used for redefinitions. */ int redefCounter; /* Used for redefinitions. */ xmlSchemaItemListPtr attrProhibs; }; /** * xmlSchemaQNameRef: * * A component reference item (not a schema component) * (Extends xmlSchemaBasicItem) */ typedef struct _xmlSchemaQNameRef xmlSchemaQNameRef; typedef xmlSchemaQNameRef *xmlSchemaQNameRefPtr; struct _xmlSchemaQNameRef { xmlSchemaTypeType type; xmlSchemaBasicItemPtr item; /* The resolved referenced item. */ xmlSchemaTypeType itemType; const xmlChar *name; const xmlChar *targetNamespace; xmlNodePtr node; }; /** * xmlSchemaParticle: * * A particle component. * (Extends xmlSchemaTreeItem) */ typedef struct _xmlSchemaParticle xmlSchemaParticle; typedef xmlSchemaParticle *xmlSchemaParticlePtr; struct _xmlSchemaParticle { xmlSchemaTypeType type; xmlSchemaAnnotPtr annot; xmlSchemaTreeItemPtr next; /* next particle */ xmlSchemaTreeItemPtr children; /* the "term" (e.g. a model group, a group definition, a XML_SCHEMA_EXTRA_QNAMEREF (if a reference), etc.) */ int minOccurs; int maxOccurs; xmlNodePtr node; }; /** * xmlSchemaModelGroup: * * A model group component. * (Extends xmlSchemaTreeItem) */ typedef struct _xmlSchemaModelGroup xmlSchemaModelGroup; typedef xmlSchemaModelGroup *xmlSchemaModelGroupPtr; struct _xmlSchemaModelGroup { xmlSchemaTypeType type; /* XML_SCHEMA_TYPE_SEQUENCE, XML_SCHEMA_TYPE_CHOICE, XML_SCHEMA_TYPE_ALL */ xmlSchemaAnnotPtr annot; xmlSchemaTreeItemPtr next; /* not used */ xmlSchemaTreeItemPtr children; /* first particle (OR "element decl" OR "wildcard") */ xmlNodePtr node; }; #define XML_SCHEMA_MODEL_GROUP_DEF_MARKED 1<<0 #define XML_SCHEMA_MODEL_GROUP_DEF_REDEFINED 1<<1 /** * xmlSchemaModelGroupDef: * * A model group definition component. * (Extends xmlSchemaTreeItem) */ typedef struct _xmlSchemaModelGroupDef xmlSchemaModelGroupDef; typedef xmlSchemaModelGroupDef *xmlSchemaModelGroupDefPtr; struct _xmlSchemaModelGroupDef { xmlSchemaTypeType type; /* XML_SCHEMA_TYPE_GROUP */ xmlSchemaAnnotPtr annot; xmlSchemaTreeItemPtr next; /* not used */ xmlSchemaTreeItemPtr children; /* the "model group" */ const xmlChar *name; const xmlChar *targetNamespace; xmlNodePtr node; int flags; }; typedef struct _xmlSchemaIDC xmlSchemaIDC; typedef xmlSchemaIDC *xmlSchemaIDCPtr; /** * xmlSchemaIDCSelect: * * The identity-constraint "field" and "selector" item, holding the * XPath expression. */ typedef struct _xmlSchemaIDCSelect xmlSchemaIDCSelect; typedef xmlSchemaIDCSelect *xmlSchemaIDCSelectPtr; struct _xmlSchemaIDCSelect { xmlSchemaIDCSelectPtr next; xmlSchemaIDCPtr idc; int index; /* an index position if significant for IDC key-sequences */ const xmlChar *xpath; /* the XPath expression */ void *xpathComp; /* the compiled XPath expression */ }; /** * xmlSchemaIDC: * * The identity-constraint definition component. * (Extends xmlSchemaAnnotItem) */ struct _xmlSchemaIDC { xmlSchemaTypeType type; xmlSchemaAnnotPtr annot; xmlSchemaIDCPtr next; xmlNodePtr node; const xmlChar *name; const xmlChar *targetNamespace; xmlSchemaIDCSelectPtr selector; xmlSchemaIDCSelectPtr fields; int nbFields; xmlSchemaQNameRefPtr ref; }; /** * xmlSchemaIDCAug: * * The augmented IDC information used for validation. */ typedef struct _xmlSchemaIDCAug xmlSchemaIDCAug; typedef xmlSchemaIDCAug *xmlSchemaIDCAugPtr; struct _xmlSchemaIDCAug { xmlSchemaIDCAugPtr next; /* next in a list */ xmlSchemaIDCPtr def; /* the IDC definition */ int keyrefDepth; /* the lowest tree level to which IDC tables need to be bubbled upwards */ }; /** * xmlSchemaPSVIIDCKeySequence: * * The key sequence of a node table item. */ typedef struct _xmlSchemaPSVIIDCKey xmlSchemaPSVIIDCKey; typedef xmlSchemaPSVIIDCKey *xmlSchemaPSVIIDCKeyPtr; struct _xmlSchemaPSVIIDCKey { xmlSchemaTypePtr type; xmlSchemaValPtr val; }; /** * xmlSchemaPSVIIDCNode: * * The node table item of a node table. */ typedef struct _xmlSchemaPSVIIDCNode xmlSchemaPSVIIDCNode; typedef xmlSchemaPSVIIDCNode *xmlSchemaPSVIIDCNodePtr; struct _xmlSchemaPSVIIDCNode { xmlNodePtr node; xmlSchemaPSVIIDCKeyPtr *keys; int nodeLine; int nodeQNameID; }; /** * xmlSchemaPSVIIDCBinding: * * The identity-constraint binding item of the [identity-constraint table]. */ typedef struct _xmlSchemaPSVIIDCBinding xmlSchemaPSVIIDCBinding; typedef xmlSchemaPSVIIDCBinding *xmlSchemaPSVIIDCBindingPtr; struct _xmlSchemaPSVIIDCBinding { xmlSchemaPSVIIDCBindingPtr next; /* next binding of a specific node */ xmlSchemaIDCPtr definition; /* the IDC definition */ xmlSchemaPSVIIDCNodePtr *nodeTable; /* array of key-sequences */ int nbNodes; /* number of entries in the node table */ int sizeNodes; /* size of the node table */ xmlSchemaItemListPtr dupls; }; #define XPATH_STATE_OBJ_TYPE_IDC_SELECTOR 1 #define XPATH_STATE_OBJ_TYPE_IDC_FIELD 2 #define XPATH_STATE_OBJ_MATCHES -2 #define XPATH_STATE_OBJ_BLOCKED -3 typedef struct _xmlSchemaIDCMatcher xmlSchemaIDCMatcher; typedef xmlSchemaIDCMatcher *xmlSchemaIDCMatcherPtr; /** * xmlSchemaIDCStateObj: * * The state object used to evaluate XPath expressions. */ typedef struct _xmlSchemaIDCStateObj xmlSchemaIDCStateObj; typedef xmlSchemaIDCStateObj *xmlSchemaIDCStateObjPtr; struct _xmlSchemaIDCStateObj { int type; xmlSchemaIDCStateObjPtr next; /* next if in a list */ int depth; /* depth of creation */ int *history; /* list of (depth, state-id) tuples */ int nbHistory; int sizeHistory; xmlSchemaIDCMatcherPtr matcher; /* the correspondent field/selector matcher */ xmlSchemaIDCSelectPtr sel; void *xpathCtxt; }; #define IDC_MATCHER 0 /** * xmlSchemaIDCMatcher: * * Used to evaluate IDC selectors (and fields). */ struct _xmlSchemaIDCMatcher { int type; int depth; /* the tree depth at creation time */ xmlSchemaIDCMatcherPtr next; /* next in the list */ xmlSchemaIDCMatcherPtr nextCached; /* next in the cache list */ xmlSchemaIDCAugPtr aidc; /* the augmented IDC item */ int idcType; xmlSchemaPSVIIDCKeyPtr **keySeqs; /* the key-sequences of the target elements */ int sizeKeySeqs; xmlSchemaItemListPtr targets; /* list of target-node (xmlSchemaPSVIIDCNodePtr) entries */ xmlHashTablePtr htab; }; /* * Element info flags. */ #define XML_SCHEMA_NODE_INFO_FLAG_OWNED_NAMES 1<<0 #define XML_SCHEMA_NODE_INFO_FLAG_OWNED_VALUES 1<<1 #define XML_SCHEMA_ELEM_INFO_NILLED 1<<2 #define XML_SCHEMA_ELEM_INFO_LOCAL_TYPE 1<<3 #define XML_SCHEMA_NODE_INFO_VALUE_NEEDED 1<<4 #define XML_SCHEMA_ELEM_INFO_EMPTY 1<<5 #define XML_SCHEMA_ELEM_INFO_HAS_CONTENT 1<<6 #define XML_SCHEMA_ELEM_INFO_HAS_ELEM_CONTENT 1<<7 #define XML_SCHEMA_ELEM_INFO_ERR_BAD_CONTENT 1<<8 #define XML_SCHEMA_NODE_INFO_ERR_NOT_EXPECTED 1<<9 #define XML_SCHEMA_NODE_INFO_ERR_BAD_TYPE 1<<10 /** * xmlSchemaNodeInfo: * * Holds information of an element node. */ struct _xmlSchemaNodeInfo { int nodeType; xmlNodePtr node; int nodeLine; const xmlChar *localName; const xmlChar *nsName; const xmlChar *value; xmlSchemaValPtr val; /* the pre-computed value if any */ xmlSchemaTypePtr typeDef; /* the complex/simple type definition if any */ int flags; /* combination of node info flags */ int valNeeded; int normVal; xmlSchemaElementPtr decl; /* the element/attribute declaration */ int depth; xmlSchemaPSVIIDCBindingPtr idcTable; /* the table of PSVI IDC bindings for the scope element*/ xmlSchemaIDCMatcherPtr idcMatchers; /* the IDC matchers for the scope element */ xmlRegExecCtxtPtr regexCtxt; const xmlChar **nsBindings; /* Namespace bindings on this element */ int nbNsBindings; int sizeNsBindings; int hasKeyrefs; int appliedXPath; /* Indicates that an XPath has been applied. */ }; #define XML_SCHEMAS_ATTR_UNKNOWN 1 #define XML_SCHEMAS_ATTR_ASSESSED 2 #define XML_SCHEMAS_ATTR_PROHIBITED 3 #define XML_SCHEMAS_ATTR_ERR_MISSING 4 #define XML_SCHEMAS_ATTR_INVALID_VALUE 5 #define XML_SCHEMAS_ATTR_ERR_NO_TYPE 6 #define XML_SCHEMAS_ATTR_ERR_FIXED_VALUE 7 #define XML_SCHEMAS_ATTR_DEFAULT 8 #define XML_SCHEMAS_ATTR_VALIDATE_VALUE 9 #define XML_SCHEMAS_ATTR_ERR_WILD_STRICT_NO_DECL 10 #define XML_SCHEMAS_ATTR_HAS_ATTR_USE 11 #define XML_SCHEMAS_ATTR_HAS_ATTR_DECL 12 #define XML_SCHEMAS_ATTR_WILD_SKIP 13 #define XML_SCHEMAS_ATTR_WILD_LAX_NO_DECL 14 #define XML_SCHEMAS_ATTR_ERR_WILD_DUPLICATE_ID 15 #define XML_SCHEMAS_ATTR_ERR_WILD_AND_USE_ID 16 #define XML_SCHEMAS_ATTR_META 17 /* * @metaType values of xmlSchemaAttrInfo. */ #define XML_SCHEMA_ATTR_INFO_META_XSI_TYPE 1 #define XML_SCHEMA_ATTR_INFO_META_XSI_NIL 2 #define XML_SCHEMA_ATTR_INFO_META_XSI_SCHEMA_LOC 3 #define XML_SCHEMA_ATTR_INFO_META_XSI_NO_NS_SCHEMA_LOC 4 #define XML_SCHEMA_ATTR_INFO_META_XMLNS 5 typedef struct _xmlSchemaAttrInfo xmlSchemaAttrInfo; typedef xmlSchemaAttrInfo *xmlSchemaAttrInfoPtr; struct _xmlSchemaAttrInfo { int nodeType; xmlNodePtr node; int nodeLine; const xmlChar *localName; const xmlChar *nsName; const xmlChar *value; xmlSchemaValPtr val; /* the pre-computed value if any */ xmlSchemaTypePtr typeDef; /* the complex/simple type definition if any */ int flags; /* combination of node info flags */ xmlSchemaAttributePtr decl; /* the attribute declaration */ xmlSchemaAttributeUsePtr use; /* the attribute use */ int state; int metaType; const xmlChar *vcValue; /* the value constraint value */ xmlSchemaNodeInfoPtr parent; }; #define XML_SCHEMA_VALID_CTXT_FLAG_STREAM 1 /** * xmlSchemaValidCtxt: * * A Schemas validation context */ struct _xmlSchemaValidCtxt { int type; void *errCtxt; /* user specific data block */ xmlSchemaValidityErrorFunc error; /* the callback in case of errors */ xmlSchemaValidityWarningFunc warning; /* the callback in case of warning */ xmlStructuredErrorFunc serror; xmlSchemaPtr schema; /* The schema in use */ xmlDocPtr doc; xmlParserInputBufferPtr input; xmlCharEncoding enc; xmlSAXHandlerPtr sax; xmlParserCtxtPtr parserCtxt; void *user_data; /* TODO: What is this for? */ char *filename; int err; int nberrors; xmlNodePtr node; xmlNodePtr cur; /* xmlSchemaTypePtr type; */ xmlRegExecCtxtPtr regexp; xmlSchemaValPtr value; int valueWS; int options; xmlNodePtr validationRoot; xmlSchemaParserCtxtPtr pctxt; int xsiAssemble; int depth; xmlSchemaNodeInfoPtr *elemInfos; /* array of element information */ int sizeElemInfos; xmlSchemaNodeInfoPtr inode; /* the current element information */ xmlSchemaIDCAugPtr aidcs; /* a list of augmented IDC information */ xmlSchemaIDCStateObjPtr xpathStates; /* first active state object. */ xmlSchemaIDCStateObjPtr xpathStatePool; /* first stored state object. */ xmlSchemaIDCMatcherPtr idcMatcherCache; /* Cache for IDC matcher objects. */ xmlSchemaPSVIIDCNodePtr *idcNodes; /* list of all IDC node-table entries*/ int nbIdcNodes; int sizeIdcNodes; xmlSchemaPSVIIDCKeyPtr *idcKeys; /* list of all IDC node-table entries */ int nbIdcKeys; int sizeIdcKeys; int flags; xmlDictPtr dict; #ifdef LIBXML_READER_ENABLED xmlTextReaderPtr reader; #endif xmlSchemaAttrInfoPtr *attrInfos; int nbAttrInfos; int sizeAttrInfos; int skipDepth; xmlSchemaItemListPtr nodeQNames; int hasKeyrefs; int createIDCNodeTables; int psviExposeIDCNodeTables; /* Locator for error reporting in streaming mode */ xmlSchemaValidityLocatorFunc locFunc; void *locCtxt; }; /** * xmlSchemaSubstGroup: * * */ typedef struct _xmlSchemaSubstGroup xmlSchemaSubstGroup; typedef xmlSchemaSubstGroup *xmlSchemaSubstGroupPtr; struct _xmlSchemaSubstGroup { xmlSchemaElementPtr head; xmlSchemaItemListPtr members; }; /** * xmlIDCHashEntry: * * an entry in hash tables to quickly look up keys/uniques */ typedef struct _xmlIDCHashEntry xmlIDCHashEntry; typedef xmlIDCHashEntry *xmlIDCHashEntryPtr; struct _xmlIDCHashEntry { xmlIDCHashEntryPtr next; /* next item with same hash */ int index; /* index into associated item list */ }; /************************************************************************ * * * Some predeclarations * * * ************************************************************************/ static int xmlSchemaParseInclude(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node); static int xmlSchemaParseRedefine(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node); static int xmlSchemaTypeFixup(xmlSchemaTypePtr type, xmlSchemaAbstractCtxtPtr ctxt); static const xmlChar * xmlSchemaFacetTypeToString(xmlSchemaTypeType type); static int xmlSchemaParseImport(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node); static int xmlSchemaCheckFacetValues(xmlSchemaTypePtr typeDecl, xmlSchemaParserCtxtPtr ctxt); static void xmlSchemaClearValidCtxt(xmlSchemaValidCtxtPtr vctxt); static xmlSchemaWhitespaceValueType xmlSchemaGetWhiteSpaceFacetValue(xmlSchemaTypePtr type); static xmlSchemaTreeItemPtr xmlSchemaParseModelGroup(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node, xmlSchemaTypeType type, int withParticle); static const xmlChar * xmlSchemaGetComponentTypeStr(xmlSchemaBasicItemPtr item); static xmlSchemaTypeLinkPtr xmlSchemaGetUnionSimpleTypeMemberTypes(xmlSchemaTypePtr type); static void xmlSchemaInternalErr(xmlSchemaAbstractCtxtPtr actxt, const char *funcName, const char *message) LIBXML_ATTR_FORMAT(3,0); static int xmlSchemaCheckCOSSTDerivedOK(xmlSchemaAbstractCtxtPtr ctxt, xmlSchemaTypePtr type, xmlSchemaTypePtr baseType, int subset); static void xmlSchemaCheckElementDeclComponent(xmlSchemaElementPtr elemDecl, xmlSchemaParserCtxtPtr ctxt); static void xmlSchemaComponentListFree(xmlSchemaItemListPtr list); static xmlSchemaQNameRefPtr xmlSchemaParseAttributeGroupRef(xmlSchemaParserCtxtPtr pctxt, xmlSchemaPtr schema, xmlNodePtr node); /************************************************************************ * * * Helper functions * * * ************************************************************************/ /** * xmlSchemaItemTypeToStr: * @type: the type of the schema item * * Returns the component name of a schema item. */ static const xmlChar * xmlSchemaItemTypeToStr(xmlSchemaTypeType type) { switch (type) { case XML_SCHEMA_TYPE_BASIC: return(BAD_CAST "simple type definition"); case XML_SCHEMA_TYPE_SIMPLE: return(BAD_CAST "simple type definition"); case XML_SCHEMA_TYPE_COMPLEX: return(BAD_CAST "complex type definition"); case XML_SCHEMA_TYPE_ELEMENT: return(BAD_CAST "element declaration"); case XML_SCHEMA_TYPE_ATTRIBUTE_USE: return(BAD_CAST "attribute use"); case XML_SCHEMA_TYPE_ATTRIBUTE: return(BAD_CAST "attribute declaration"); case XML_SCHEMA_TYPE_GROUP: return(BAD_CAST "model group definition"); case XML_SCHEMA_TYPE_ATTRIBUTEGROUP: return(BAD_CAST "attribute group definition"); case XML_SCHEMA_TYPE_NOTATION: return(BAD_CAST "notation declaration"); case XML_SCHEMA_TYPE_SEQUENCE: return(BAD_CAST "model group (sequence)"); case XML_SCHEMA_TYPE_CHOICE: return(BAD_CAST "model group (choice)"); case XML_SCHEMA_TYPE_ALL: return(BAD_CAST "model group (all)"); case XML_SCHEMA_TYPE_PARTICLE: return(BAD_CAST "particle"); case XML_SCHEMA_TYPE_IDC_UNIQUE: return(BAD_CAST "unique identity-constraint"); /* return(BAD_CAST "IDC (unique)"); */ case XML_SCHEMA_TYPE_IDC_KEY: return(BAD_CAST "key identity-constraint"); /* return(BAD_CAST "IDC (key)"); */ case XML_SCHEMA_TYPE_IDC_KEYREF: return(BAD_CAST "keyref identity-constraint"); /* return(BAD_CAST "IDC (keyref)"); */ case XML_SCHEMA_TYPE_ANY: return(BAD_CAST "wildcard (any)"); case XML_SCHEMA_EXTRA_QNAMEREF: return(BAD_CAST "[helper component] QName reference"); case XML_SCHEMA_EXTRA_ATTR_USE_PROHIB: return(BAD_CAST "[helper component] attribute use prohibition"); default: return(BAD_CAST "Not a schema component"); } } /** * xmlSchemaGetComponentTypeStr: * @type: the type of the schema item * * Returns the component name of a schema item. */ static const xmlChar * xmlSchemaGetComponentTypeStr(xmlSchemaBasicItemPtr item) { switch (item->type) { case XML_SCHEMA_TYPE_BASIC: if (WXS_IS_COMPLEX(WXS_TYPE_CAST item)) return(BAD_CAST "complex type definition"); else return(BAD_CAST "simple type definition"); default: return(xmlSchemaItemTypeToStr(item->type)); } } /** * xmlSchemaGetComponentNode: * @item: a schema component * * Returns node associated with the schema component. * NOTE that such a node need not be available; plus, a component's * node need not to reflect the component directly, since there is no * one-to-one relationship between the XML Schema representation and * the component representation. */ static xmlNodePtr xmlSchemaGetComponentNode(xmlSchemaBasicItemPtr item) { switch (item->type) { case XML_SCHEMA_TYPE_ELEMENT: return (((xmlSchemaElementPtr) item)->node); case XML_SCHEMA_TYPE_ATTRIBUTE: return (((xmlSchemaAttributePtr) item)->node); case XML_SCHEMA_TYPE_COMPLEX: case XML_SCHEMA_TYPE_SIMPLE: return (((xmlSchemaTypePtr) item)->node); case XML_SCHEMA_TYPE_ANY: case XML_SCHEMA_TYPE_ANY_ATTRIBUTE: return (((xmlSchemaWildcardPtr) item)->node); case XML_SCHEMA_TYPE_PARTICLE: return (((xmlSchemaParticlePtr) item)->node); case XML_SCHEMA_TYPE_SEQUENCE: case XML_SCHEMA_TYPE_CHOICE: case XML_SCHEMA_TYPE_ALL: return (((xmlSchemaModelGroupPtr) item)->node); case XML_SCHEMA_TYPE_GROUP: return (((xmlSchemaModelGroupDefPtr) item)->node); case XML_SCHEMA_TYPE_ATTRIBUTEGROUP: return (((xmlSchemaAttributeGroupPtr) item)->node); case XML_SCHEMA_TYPE_IDC_UNIQUE: case XML_SCHEMA_TYPE_IDC_KEY: case XML_SCHEMA_TYPE_IDC_KEYREF: return (((xmlSchemaIDCPtr) item)->node); case XML_SCHEMA_EXTRA_QNAMEREF: return(((xmlSchemaQNameRefPtr) item)->node); /* TODO: What to do with NOTATIONs? case XML_SCHEMA_TYPE_NOTATION: return (((xmlSchemaNotationPtr) item)->node); */ case XML_SCHEMA_TYPE_ATTRIBUTE_USE: return (((xmlSchemaAttributeUsePtr) item)->node); default: return (NULL); } } #if 0 /** * xmlSchemaGetNextComponent: * @item: a schema component * * Returns the next sibling of the schema component. */ static xmlSchemaBasicItemPtr xmlSchemaGetNextComponent(xmlSchemaBasicItemPtr item) { switch (item->type) { case XML_SCHEMA_TYPE_ELEMENT: return ((xmlSchemaBasicItemPtr) ((xmlSchemaElementPtr) item)->next); case XML_SCHEMA_TYPE_ATTRIBUTE: return ((xmlSchemaBasicItemPtr) ((xmlSchemaAttributePtr) item)->next); case XML_SCHEMA_TYPE_COMPLEX: case XML_SCHEMA_TYPE_SIMPLE: return ((xmlSchemaBasicItemPtr) ((xmlSchemaTypePtr) item)->next); case XML_SCHEMA_TYPE_ANY: case XML_SCHEMA_TYPE_ANY_ATTRIBUTE: return (NULL); case XML_SCHEMA_TYPE_PARTICLE: return ((xmlSchemaBasicItemPtr) ((xmlSchemaParticlePtr) item)->next); case XML_SCHEMA_TYPE_SEQUENCE: case XML_SCHEMA_TYPE_CHOICE: case XML_SCHEMA_TYPE_ALL: return (NULL); case XML_SCHEMA_TYPE_GROUP: return (NULL); case XML_SCHEMA_TYPE_ATTRIBUTEGROUP: return ((xmlSchemaBasicItemPtr) ((xmlSchemaAttributeGroupPtr) item)->next); case XML_SCHEMA_TYPE_IDC_UNIQUE: case XML_SCHEMA_TYPE_IDC_KEY: case XML_SCHEMA_TYPE_IDC_KEYREF: return ((xmlSchemaBasicItemPtr) ((xmlSchemaIDCPtr) item)->next); default: return (NULL); } } #endif /** * xmlSchemaFormatQName: * @buf: the string buffer * @namespaceName: the namespace name * @localName: the local name * * Returns the given QName in the format "{namespaceName}localName" or * just "localName" if @namespaceName is NULL. * * Returns the localName if @namespaceName is NULL, a formatted * string otherwise. */ static const xmlChar* xmlSchemaFormatQName(xmlChar **buf, const xmlChar *namespaceName, const xmlChar *localName) { FREE_AND_NULL(*buf) if (namespaceName != NULL) { *buf = xmlStrdup(BAD_CAST "{"); *buf = xmlStrcat(*buf, namespaceName); *buf = xmlStrcat(*buf, BAD_CAST "}"); } if (localName != NULL) { if (namespaceName == NULL) return(localName); *buf = xmlStrcat(*buf, localName); } else { *buf = xmlStrcat(*buf, BAD_CAST "(NULL)"); } return ((const xmlChar *) *buf); } static const xmlChar* xmlSchemaFormatQNameNs(xmlChar **buf, xmlNsPtr ns, const xmlChar *localName) { if (ns != NULL) return (xmlSchemaFormatQName(buf, ns->href, localName)); else return (xmlSchemaFormatQName(buf, NULL, localName)); } static const xmlChar * xmlSchemaGetComponentName(xmlSchemaBasicItemPtr item) { switch (item->type) { case XML_SCHEMA_TYPE_ELEMENT: return (((xmlSchemaElementPtr) item)->name); case XML_SCHEMA_TYPE_ATTRIBUTE: return (((xmlSchemaAttributePtr) item)->name); case XML_SCHEMA_TYPE_ATTRIBUTEGROUP: return (((xmlSchemaAttributeGroupPtr) item)->name); case XML_SCHEMA_TYPE_BASIC: case XML_SCHEMA_TYPE_SIMPLE: case XML_SCHEMA_TYPE_COMPLEX: return (((xmlSchemaTypePtr) item)->name); case XML_SCHEMA_TYPE_GROUP: return (((xmlSchemaModelGroupDefPtr) item)->name); case XML_SCHEMA_TYPE_IDC_KEY: case XML_SCHEMA_TYPE_IDC_UNIQUE: case XML_SCHEMA_TYPE_IDC_KEYREF: return (((xmlSchemaIDCPtr) item)->name); case XML_SCHEMA_TYPE_ATTRIBUTE_USE: if (WXS_ATTRUSE_DECL(item) != NULL) { return(xmlSchemaGetComponentName( WXS_BASIC_CAST WXS_ATTRUSE_DECL(item))); } else return(NULL); case XML_SCHEMA_EXTRA_QNAMEREF: return (((xmlSchemaQNameRefPtr) item)->name); case XML_SCHEMA_TYPE_NOTATION: return (((xmlSchemaNotationPtr) item)->name); default: /* * Other components cannot have names. */ break; } return (NULL); } #define xmlSchemaGetQNameRefName(r) (WXS_QNAME_CAST (r))->name #define xmlSchemaGetQNameRefTargetNs(r) (WXS_QNAME_CAST (r))->targetNamespace /* static const xmlChar * xmlSchemaGetQNameRefName(void *ref) { return(((xmlSchemaQNameRefPtr) ref)->name); } static const xmlChar * xmlSchemaGetQNameRefTargetNs(void *ref) { return(((xmlSchemaQNameRefPtr) ref)->targetNamespace); } */ static const xmlChar * xmlSchemaGetComponentTargetNs(xmlSchemaBasicItemPtr item) { switch (item->type) { case XML_SCHEMA_TYPE_ELEMENT: return (((xmlSchemaElementPtr) item)->targetNamespace); case XML_SCHEMA_TYPE_ATTRIBUTE: return (((xmlSchemaAttributePtr) item)->targetNamespace); case XML_SCHEMA_TYPE_ATTRIBUTEGROUP: return (((xmlSchemaAttributeGroupPtr) item)->targetNamespace); case XML_SCHEMA_TYPE_BASIC: return (BAD_CAST "http://www.w3.org/2001/XMLSchema"); case XML_SCHEMA_TYPE_SIMPLE: case XML_SCHEMA_TYPE_COMPLEX: return (((xmlSchemaTypePtr) item)->targetNamespace); case XML_SCHEMA_TYPE_GROUP: return (((xmlSchemaModelGroupDefPtr) item)->targetNamespace); case XML_SCHEMA_TYPE_IDC_KEY: case XML_SCHEMA_TYPE_IDC_UNIQUE: case XML_SCHEMA_TYPE_IDC_KEYREF: return (((xmlSchemaIDCPtr) item)->targetNamespace); case XML_SCHEMA_TYPE_ATTRIBUTE_USE: if (WXS_ATTRUSE_DECL(item) != NULL) { return(xmlSchemaGetComponentTargetNs( WXS_BASIC_CAST WXS_ATTRUSE_DECL(item))); } /* TODO: Will returning NULL break something? */ break; case XML_SCHEMA_EXTRA_QNAMEREF: return (((xmlSchemaQNameRefPtr) item)->targetNamespace); case XML_SCHEMA_TYPE_NOTATION: return (((xmlSchemaNotationPtr) item)->targetNamespace); default: /* * Other components cannot have names. */ break; } return (NULL); } static const xmlChar* xmlSchemaGetComponentQName(xmlChar **buf, void *item) { return (xmlSchemaFormatQName(buf, xmlSchemaGetComponentTargetNs((xmlSchemaBasicItemPtr) item), xmlSchemaGetComponentName((xmlSchemaBasicItemPtr) item))); } static const xmlChar* xmlSchemaGetComponentDesignation(xmlChar **buf, void *item) { xmlChar *str = NULL; *buf = xmlStrcat(*buf, WXS_ITEM_TYPE_NAME(item)); *buf = xmlStrcat(*buf, BAD_CAST " '"); *buf = xmlStrcat(*buf, xmlSchemaGetComponentQName(&str, (xmlSchemaBasicItemPtr) item)); *buf = xmlStrcat(*buf, BAD_CAST "'"); FREE_AND_NULL(str); return(*buf); } static const xmlChar* xmlSchemaGetIDCDesignation(xmlChar **buf, xmlSchemaIDCPtr idc) { return(xmlSchemaGetComponentDesignation(buf, idc)); } /** * xmlSchemaWildcardPCToString: * @pc: the type of processContents * * Returns a string representation of the type of * processContents. */ static const xmlChar * xmlSchemaWildcardPCToString(int pc) { switch (pc) { case XML_SCHEMAS_ANY_SKIP: return (BAD_CAST "skip"); case XML_SCHEMAS_ANY_LAX: return (BAD_CAST "lax"); case XML_SCHEMAS_ANY_STRICT: return (BAD_CAST "strict"); default: return (BAD_CAST "invalid process contents"); } } /** * xmlSchemaGetCanonValueWhtspExt: * @val: the precomputed value * @retValue: the returned value * @ws: the whitespace type of the value * @for_hash: non-zero if this is supposed to generate a string for hashing * * Get a the canonical representation of the value. * The caller has to free the returned retValue. * * Returns 0 if the value could be built and -1 in case of * API errors or if the value type is not supported yet. */ static int xmlSchemaGetCanonValueWhtspExt_1(xmlSchemaValPtr val, xmlSchemaWhitespaceValueType ws, xmlChar **retValue, int for_hash) { int list; xmlSchemaValType valType; const xmlChar *value, *value2 = NULL; if ((retValue == NULL) || (val == NULL)) return (-1); list = xmlSchemaValueGetNext(val) ? 1 : 0; *retValue = NULL; do { value = NULL; valType = xmlSchemaGetValType(val); switch (valType) { case XML_SCHEMAS_STRING: case XML_SCHEMAS_NORMSTRING: case XML_SCHEMAS_ANYSIMPLETYPE: value = xmlSchemaValueGetAsString(val); if (value != NULL) { if (ws == XML_SCHEMA_WHITESPACE_COLLAPSE) value2 = xmlSchemaCollapseString(value); else if (ws == XML_SCHEMA_WHITESPACE_REPLACE) value2 = xmlSchemaWhiteSpaceReplace(value); if (value2 != NULL) value = value2; } break; default: if (xmlSchemaGetCanonValue(val, &value2) == -1) { if (value2 != NULL) xmlFree((xmlChar *) value2); goto internal_error; } if (for_hash && valType == XML_SCHEMAS_DECIMAL) { /* We can mostly use the canonical value for hashing, except in the case of decimal. There the canonical representation requires a trailing '.0' even for non-fractional numbers, but for the derived integer types it forbids any decimal point. Nevertheless they compare equal if the value is equal. We need to generate the same hash value for this to work, and it's easiest to just cut off the useless '.0' suffix for the decimal type. */ int len = xmlStrlen(value2); if (len > 2 && value2[len-1] == '0' && value2[len-2] == '.') ((xmlChar*)value2)[len-2] = 0; } value = value2; } if (*retValue == NULL) if (value == NULL) { if (! list) *retValue = xmlStrdup(BAD_CAST ""); } else *retValue = xmlStrdup(value); else if (value != NULL) { /* List. */ *retValue = xmlStrcat((xmlChar *) *retValue, BAD_CAST " "); *retValue = xmlStrcat((xmlChar *) *retValue, value); } FREE_AND_NULL(value2) val = xmlSchemaValueGetNext(val); } while (val != NULL); return (0); internal_error: if (*retValue != NULL) xmlFree((xmlChar *) (*retValue)); if (value2 != NULL) xmlFree((xmlChar *) value2); return (-1); } static int xmlSchemaGetCanonValueWhtspExt(xmlSchemaValPtr val, xmlSchemaWhitespaceValueType ws, xmlChar **retValue) { return xmlSchemaGetCanonValueWhtspExt_1(val, ws, retValue, 0); } static int xmlSchemaGetCanonValueHash(xmlSchemaValPtr val, xmlChar **retValue) { return xmlSchemaGetCanonValueWhtspExt_1(val, XML_SCHEMA_WHITESPACE_COLLAPSE, retValue, 1); } /** * xmlSchemaFormatItemForReport: * @buf: the string buffer * @itemDes: the designation of the item * @itemName: the name of the item * @item: the item as an object * @itemNode: the node of the item * @local: the local name * @parsing: if the function is used during the parse * * Returns a representation of the given item used * for error reports. * * The following order is used to build the resulting * designation if the arguments are not NULL: * 1a. If itemDes not NULL -> itemDes * 1b. If (itemDes not NULL) and (itemName not NULL) * -> itemDes + itemName * 2. If the preceding was NULL and (item not NULL) -> item * 3. If the preceding was NULL and (itemNode not NULL) -> itemNode * * If the itemNode is an attribute node, the name of the attribute * will be appended to the result. * * Returns the formatted string and sets @buf to the resulting value. */ static xmlChar* xmlSchemaFormatItemForReport(xmlChar **buf, const xmlChar *itemDes, xmlSchemaBasicItemPtr item, xmlNodePtr itemNode) { xmlChar *str = NULL; int named = 1; if (*buf != NULL) { xmlFree(*buf); *buf = NULL; } if (itemDes != NULL) { *buf = xmlStrdup(itemDes); } else if (item != NULL) { switch (item->type) { case XML_SCHEMA_TYPE_BASIC: { xmlSchemaTypePtr type = WXS_TYPE_CAST item; if (WXS_IS_ATOMIC(type)) *buf = xmlStrdup(BAD_CAST "atomic type 'xs:"); else if (WXS_IS_LIST(type)) *buf = xmlStrdup(BAD_CAST "list type 'xs:"); else if (WXS_IS_UNION(type)) *buf = xmlStrdup(BAD_CAST "union type 'xs:"); else *buf = xmlStrdup(BAD_CAST "simple type 'xs:"); *buf = xmlStrcat(*buf, type->name); *buf = xmlStrcat(*buf, BAD_CAST "'"); } break; case XML_SCHEMA_TYPE_SIMPLE: { xmlSchemaTypePtr type = WXS_TYPE_CAST item; if (type->flags & XML_SCHEMAS_TYPE_GLOBAL) { *buf = xmlStrdup(BAD_CAST""); } else { *buf = xmlStrdup(BAD_CAST "local "); } if (WXS_IS_ATOMIC(type)) *buf = xmlStrcat(*buf, BAD_CAST "atomic type"); else if (WXS_IS_LIST(type)) *buf = xmlStrcat(*buf, BAD_CAST "list type"); else if (WXS_IS_UNION(type)) *buf = xmlStrcat(*buf, BAD_CAST "union type"); else *buf = xmlStrcat(*buf, BAD_CAST "simple type"); if (type->flags & XML_SCHEMAS_TYPE_GLOBAL) { *buf = xmlStrcat(*buf, BAD_CAST " '"); *buf = xmlStrcat(*buf, type->name); *buf = xmlStrcat(*buf, BAD_CAST "'"); } } break; case XML_SCHEMA_TYPE_COMPLEX: { xmlSchemaTypePtr type = WXS_TYPE_CAST item; if (type->flags & XML_SCHEMAS_TYPE_GLOBAL) *buf = xmlStrdup(BAD_CAST ""); else *buf = xmlStrdup(BAD_CAST "local "); *buf = xmlStrcat(*buf, BAD_CAST "complex type"); if (type->flags & XML_SCHEMAS_TYPE_GLOBAL) { *buf = xmlStrcat(*buf, BAD_CAST " '"); *buf = xmlStrcat(*buf, type->name); *buf = xmlStrcat(*buf, BAD_CAST "'"); } } break; case XML_SCHEMA_TYPE_ATTRIBUTE_USE: { xmlSchemaAttributeUsePtr ause; ause = WXS_ATTR_USE_CAST item; *buf = xmlStrdup(BAD_CAST "attribute use "); if (WXS_ATTRUSE_DECL(ause) != NULL) { *buf = xmlStrcat(*buf, BAD_CAST "'"); *buf = xmlStrcat(*buf, xmlSchemaGetComponentQName(&str, WXS_ATTRUSE_DECL(ause))); FREE_AND_NULL(str) *buf = xmlStrcat(*buf, BAD_CAST "'"); } else { *buf = xmlStrcat(*buf, BAD_CAST "(unknown)"); } } break; case XML_SCHEMA_TYPE_ATTRIBUTE: { xmlSchemaAttributePtr attr; attr = (xmlSchemaAttributePtr) item; *buf = xmlStrdup(BAD_CAST "attribute decl."); *buf = xmlStrcat(*buf, BAD_CAST " '"); *buf = xmlStrcat(*buf, xmlSchemaFormatQName(&str, attr->targetNamespace, attr->name)); FREE_AND_NULL(str) *buf = xmlStrcat(*buf, BAD_CAST "'"); } break; case XML_SCHEMA_TYPE_ATTRIBUTEGROUP: xmlSchemaGetComponentDesignation(buf, item); break; case XML_SCHEMA_TYPE_ELEMENT: { xmlSchemaElementPtr elem; elem = (xmlSchemaElementPtr) item; *buf = xmlStrdup(BAD_CAST "element decl."); *buf = xmlStrcat(*buf, BAD_CAST " '"); *buf = xmlStrcat(*buf, xmlSchemaFormatQName(&str, elem->targetNamespace, elem->name)); *buf = xmlStrcat(*buf, BAD_CAST "'"); } break; case XML_SCHEMA_TYPE_IDC_UNIQUE: case XML_SCHEMA_TYPE_IDC_KEY: case XML_SCHEMA_TYPE_IDC_KEYREF: if (item->type == XML_SCHEMA_TYPE_IDC_UNIQUE) *buf = xmlStrdup(BAD_CAST "unique '"); else if (item->type == XML_SCHEMA_TYPE_IDC_KEY) *buf = xmlStrdup(BAD_CAST "key '"); else *buf = xmlStrdup(BAD_CAST "keyRef '"); *buf = xmlStrcat(*buf, ((xmlSchemaIDCPtr) item)->name); *buf = xmlStrcat(*buf, BAD_CAST "'"); break; case XML_SCHEMA_TYPE_ANY: case XML_SCHEMA_TYPE_ANY_ATTRIBUTE: *buf = xmlStrdup(xmlSchemaWildcardPCToString( ((xmlSchemaWildcardPtr) item)->processContents)); *buf = xmlStrcat(*buf, BAD_CAST " wildcard"); break; case XML_SCHEMA_FACET_MININCLUSIVE: case XML_SCHEMA_FACET_MINEXCLUSIVE: case XML_SCHEMA_FACET_MAXINCLUSIVE: case XML_SCHEMA_FACET_MAXEXCLUSIVE: case XML_SCHEMA_FACET_TOTALDIGITS: case XML_SCHEMA_FACET_FRACTIONDIGITS: case XML_SCHEMA_FACET_PATTERN: case XML_SCHEMA_FACET_ENUMERATION: case XML_SCHEMA_FACET_WHITESPACE: case XML_SCHEMA_FACET_LENGTH: case XML_SCHEMA_FACET_MAXLENGTH: case XML_SCHEMA_FACET_MINLENGTH: *buf = xmlStrdup(BAD_CAST "facet '"); *buf = xmlStrcat(*buf, xmlSchemaFacetTypeToString(item->type)); *buf = xmlStrcat(*buf, BAD_CAST "'"); break; case XML_SCHEMA_TYPE_GROUP: { *buf = xmlStrdup(BAD_CAST "model group def."); *buf = xmlStrcat(*buf, BAD_CAST " '"); *buf = xmlStrcat(*buf, xmlSchemaGetComponentQName(&str, item)); *buf = xmlStrcat(*buf, BAD_CAST "'"); FREE_AND_NULL(str) } break; case XML_SCHEMA_TYPE_SEQUENCE: case XML_SCHEMA_TYPE_CHOICE: case XML_SCHEMA_TYPE_ALL: case XML_SCHEMA_TYPE_PARTICLE: *buf = xmlStrdup(WXS_ITEM_TYPE_NAME(item)); break; case XML_SCHEMA_TYPE_NOTATION: { *buf = xmlStrdup(WXS_ITEM_TYPE_NAME(item)); *buf = xmlStrcat(*buf, BAD_CAST " '"); *buf = xmlStrcat(*buf, xmlSchemaGetComponentQName(&str, item)); *buf = xmlStrcat(*buf, BAD_CAST "'"); FREE_AND_NULL(str); } /* Falls through. */ default: named = 0; } } else named = 0; if ((named == 0) && (itemNode != NULL)) { xmlNodePtr elem; if (itemNode->type == XML_ATTRIBUTE_NODE) elem = itemNode->parent; else elem = itemNode; *buf = xmlStrdup(BAD_CAST "Element '"); if (elem->ns != NULL) { *buf = xmlStrcat(*buf, xmlSchemaFormatQName(&str, elem->ns->href, elem->name)); FREE_AND_NULL(str) } else *buf = xmlStrcat(*buf, elem->name); *buf = xmlStrcat(*buf, BAD_CAST "'"); } if ((itemNode != NULL) && (itemNode->type == XML_ATTRIBUTE_NODE)) { *buf = xmlStrcat(*buf, BAD_CAST ", attribute '"); if (itemNode->ns != NULL) { *buf = xmlStrcat(*buf, xmlSchemaFormatQName(&str, itemNode->ns->href, itemNode->name)); FREE_AND_NULL(str) } else *buf = xmlStrcat(*buf, itemNode->name); *buf = xmlStrcat(*buf, BAD_CAST "'"); } FREE_AND_NULL(str) return (xmlEscapeFormatString(buf)); } /** * xmlSchemaFormatFacetEnumSet: * @buf: the string buffer * @type: the type holding the enumeration facets * * Builds a string consisting of all enumeration elements. * * Returns a string of all enumeration elements. */ static const xmlChar * xmlSchemaFormatFacetEnumSet(xmlSchemaAbstractCtxtPtr actxt, xmlChar **buf, xmlSchemaTypePtr type) { xmlSchemaFacetPtr facet; xmlSchemaWhitespaceValueType ws; xmlChar *value = NULL; int res, found = 0; if (*buf != NULL) xmlFree(*buf); *buf = NULL; do { /* * Use the whitespace type of the base type. */ ws = xmlSchemaGetWhiteSpaceFacetValue(type->baseType); for (facet = type->facets; facet != NULL; facet = facet->next) { if (facet->type != XML_SCHEMA_FACET_ENUMERATION) continue; found = 1; res = xmlSchemaGetCanonValueWhtspExt(facet->val, ws, &value); if (res == -1) { xmlSchemaInternalErr(actxt, "xmlSchemaFormatFacetEnumSet", "compute the canonical lexical representation"); if (*buf != NULL) xmlFree(*buf); *buf = NULL; return (NULL); } if (*buf == NULL) *buf = xmlStrdup(BAD_CAST "'"); else *buf = xmlStrcat(*buf, BAD_CAST ", '"); *buf = xmlStrcat(*buf, BAD_CAST value); *buf = xmlStrcat(*buf, BAD_CAST "'"); if (value != NULL) { xmlFree((xmlChar *)value); value = NULL; } } /* * The enumeration facet of a type restricts the enumeration * facet of the ancestor type; i.e., such restricted enumerations * do not belong to the set of the given type. Thus we break * on the first found enumeration. */ if (found) break; type = type->baseType; } while ((type != NULL) && (type->type != XML_SCHEMA_TYPE_BASIC)); return ((const xmlChar *) *buf); } /************************************************************************ * * * Error functions * * * ************************************************************************/ #if 0 static void xmlSchemaErrMemory(const char *msg) { __xmlSimpleError(XML_FROM_SCHEMASP, XML_ERR_NO_MEMORY, NULL, NULL, msg); } #endif static void xmlSchemaPSimpleErr(const char *msg) { __xmlSimpleError(XML_FROM_SCHEMASP, XML_ERR_NO_MEMORY, NULL, NULL, msg); } /** * xmlSchemaPErrMemory: * @node: a context node * @extra: extra information * * Handle an out of memory condition */ static void xmlSchemaPErrMemory(xmlSchemaParserCtxtPtr ctxt, const char *extra, xmlNodePtr node) { if (ctxt != NULL) ctxt->nberrors++; __xmlSimpleError(XML_FROM_SCHEMASP, XML_ERR_NO_MEMORY, node, NULL, extra); } /** * xmlSchemaPErr: * @ctxt: the parsing context * @node: the context node * @error: the error code * @msg: the error message * @str1: extra data * @str2: extra data * * Handle a parser error */ static void LIBXML_ATTR_FORMAT(4,0) xmlSchemaPErr(xmlSchemaParserCtxtPtr ctxt, xmlNodePtr node, int error, const char *msg, const xmlChar * str1, const xmlChar * str2) { xmlGenericErrorFunc channel = NULL; xmlStructuredErrorFunc schannel = NULL; void *data = NULL; if (ctxt != NULL) { ctxt->nberrors++; ctxt->err = error; channel = ctxt->error; data = ctxt->errCtxt; schannel = ctxt->serror; } __xmlRaiseError(schannel, channel, data, ctxt, node, XML_FROM_SCHEMASP, error, XML_ERR_ERROR, NULL, 0, (const char *) str1, (const char *) str2, NULL, 0, 0, msg, str1, str2); } /** * xmlSchemaPErr2: * @ctxt: the parsing context * @node: the context node * @node: the current child * @error: the error code * @msg: the error message * @str1: extra data * @str2: extra data * * Handle a parser error */ static void LIBXML_ATTR_FORMAT(5,0) xmlSchemaPErr2(xmlSchemaParserCtxtPtr ctxt, xmlNodePtr node, xmlNodePtr child, int error, const char *msg, const xmlChar * str1, const xmlChar * str2) { if (child != NULL) xmlSchemaPErr(ctxt, child, error, msg, str1, str2); else xmlSchemaPErr(ctxt, node, error, msg, str1, str2); } /** * xmlSchemaPErrExt: * @ctxt: the parsing context * @node: the context node * @error: the error code * @strData1: extra data * @strData2: extra data * @strData3: extra data * @msg: the message * @str1: extra parameter for the message display * @str2: extra parameter for the message display * @str3: extra parameter for the message display * @str4: extra parameter for the message display * @str5: extra parameter for the message display * * Handle a parser error */ static void LIBXML_ATTR_FORMAT(7,0) xmlSchemaPErrExt(xmlSchemaParserCtxtPtr ctxt, xmlNodePtr node, int error, const xmlChar * strData1, const xmlChar * strData2, const xmlChar * strData3, const char *msg, const xmlChar * str1, const xmlChar * str2, const xmlChar * str3, const xmlChar * str4, const xmlChar * str5) { xmlGenericErrorFunc channel = NULL; xmlStructuredErrorFunc schannel = NULL; void *data = NULL; if (ctxt != NULL) { ctxt->nberrors++; ctxt->err = error; channel = ctxt->error; data = ctxt->errCtxt; schannel = ctxt->serror; } __xmlRaiseError(schannel, channel, data, ctxt, node, XML_FROM_SCHEMASP, error, XML_ERR_ERROR, NULL, 0, (const char *) strData1, (const char *) strData2, (const char *) strData3, 0, 0, msg, str1, str2, str3, str4, str5); } /************************************************************************ * * * Allround error functions * * * ************************************************************************/ /** * xmlSchemaVTypeErrMemory: * @node: a context node * @extra: extra information * * Handle an out of memory condition */ static void xmlSchemaVErrMemory(xmlSchemaValidCtxtPtr ctxt, const char *extra, xmlNodePtr node) { if (ctxt != NULL) { ctxt->nberrors++; ctxt->err = XML_SCHEMAV_INTERNAL; } __xmlSimpleError(XML_FROM_SCHEMASV, XML_ERR_NO_MEMORY, node, NULL, extra); } static void LIBXML_ATTR_FORMAT(2,0) xmlSchemaPSimpleInternalErr(xmlNodePtr node, const char *msg, const xmlChar *str) { __xmlSimpleError(XML_FROM_SCHEMASP, XML_SCHEMAP_INTERNAL, node, msg, (const char *) str); } #define WXS_ERROR_TYPE_ERROR 1 #define WXS_ERROR_TYPE_WARNING 2 /** * xmlSchemaErr4Line: * @ctxt: the validation context * @errorLevel: the error level * @error: the error code * @node: the context node * @line: the line number * @msg: the error message * @str1: extra data * @str2: extra data * @str3: extra data * @str4: extra data * * Handle a validation error */ static void LIBXML_ATTR_FORMAT(6,0) xmlSchemaErr4Line(xmlSchemaAbstractCtxtPtr ctxt, xmlErrorLevel errorLevel, int error, xmlNodePtr node, int line, const char *msg, const xmlChar *str1, const xmlChar *str2, const xmlChar *str3, const xmlChar *str4) { xmlStructuredErrorFunc schannel = NULL; xmlGenericErrorFunc channel = NULL; void *data = NULL; if (ctxt != NULL) { if (ctxt->type == XML_SCHEMA_CTXT_VALIDATOR) { xmlSchemaValidCtxtPtr vctxt = (xmlSchemaValidCtxtPtr) ctxt; const char *file = NULL; int col = 0; if (errorLevel != XML_ERR_WARNING) { vctxt->nberrors++; vctxt->err = error; channel = vctxt->error; } else { channel = vctxt->warning; } schannel = vctxt->serror; data = vctxt->errCtxt; /* * Error node. If we specify a line number, then * do not channel any node to the error function. */ if (line == 0) { if ((node == NULL) && (vctxt->depth >= 0) && (vctxt->inode != NULL)) { node = vctxt->inode->node; } /* * Get filename and line if no node-tree. */ if ((node == NULL) && (vctxt->parserCtxt != NULL) && (vctxt->parserCtxt->input != NULL)) { file = vctxt->parserCtxt->input->filename; line = vctxt->parserCtxt->input->line; col = vctxt->parserCtxt->input->col; } } else { /* * Override the given node's (if any) position * and channel only the given line number. */ node = NULL; /* * Get filename. */ if (vctxt->doc != NULL) file = (const char *) vctxt->doc->URL; else if ((vctxt->parserCtxt != NULL) && (vctxt->parserCtxt->input != NULL)) file = vctxt->parserCtxt->input->filename; } if (vctxt->locFunc != NULL) { if ((file == NULL) || (line == 0)) { unsigned long l; const char *f; vctxt->locFunc(vctxt->locCtxt, &f, &l); if (file == NULL) file = f; if (line == 0) line = (int) l; } } if ((file == NULL) && (vctxt->filename != NULL)) file = vctxt->filename; __xmlRaiseError(schannel, channel, data, ctxt, node, XML_FROM_SCHEMASV, error, errorLevel, file, line, (const char *) str1, (const char *) str2, (const char *) str3, 0, col, msg, str1, str2, str3, str4); } else if (ctxt->type == XML_SCHEMA_CTXT_PARSER) { xmlSchemaParserCtxtPtr pctxt = (xmlSchemaParserCtxtPtr) ctxt; if (errorLevel != XML_ERR_WARNING) { pctxt->nberrors++; pctxt->err = error; channel = pctxt->error; } else { channel = pctxt->warning; } schannel = pctxt->serror; data = pctxt->errCtxt; __xmlRaiseError(schannel, channel, data, ctxt, node, XML_FROM_SCHEMASP, error, errorLevel, NULL, 0, (const char *) str1, (const char *) str2, (const char *) str3, 0, 0, msg, str1, str2, str3, str4); } else { TODO } } } /** * xmlSchemaErr3: * @ctxt: the validation context * @node: the context node * @error: the error code * @msg: the error message * @str1: extra data * @str2: extra data * @str3: extra data * * Handle a validation error */ static void LIBXML_ATTR_FORMAT(4,0) xmlSchemaErr3(xmlSchemaAbstractCtxtPtr actxt, int error, xmlNodePtr node, const char *msg, const xmlChar *str1, const xmlChar *str2, const xmlChar *str3) { xmlSchemaErr4Line(actxt, XML_ERR_ERROR, error, node, 0, msg, str1, str2, str3, NULL); } static void LIBXML_ATTR_FORMAT(4,0) xmlSchemaErr4(xmlSchemaAbstractCtxtPtr actxt, int error, xmlNodePtr node, const char *msg, const xmlChar *str1, const xmlChar *str2, const xmlChar *str3, const xmlChar *str4) { xmlSchemaErr4Line(actxt, XML_ERR_ERROR, error, node, 0, msg, str1, str2, str3, str4); } static void LIBXML_ATTR_FORMAT(4,0) xmlSchemaErr(xmlSchemaAbstractCtxtPtr actxt, int error, xmlNodePtr node, const char *msg, const xmlChar *str1, const xmlChar *str2) { xmlSchemaErr4(actxt, error, node, msg, str1, str2, NULL, NULL); } static xmlChar * xmlSchemaFormatNodeForError(xmlChar ** msg, xmlSchemaAbstractCtxtPtr actxt, xmlNodePtr node) { xmlChar *str = NULL; *msg = NULL; if ((node != NULL) && (node->type != XML_ELEMENT_NODE) && (node->type != XML_ATTRIBUTE_NODE)) { /* * Don't try to format other nodes than element and * attribute nodes. * Play safe and return an empty string. */ *msg = xmlStrdup(BAD_CAST ""); return(*msg); } if (node != NULL) { /* * Work on tree nodes. */ if (node->type == XML_ATTRIBUTE_NODE) { xmlNodePtr elem = node->parent; *msg = xmlStrdup(BAD_CAST "Element '"); if (elem->ns != NULL) *msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str, elem->ns->href, elem->name)); else *msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str, NULL, elem->name)); FREE_AND_NULL(str); *msg = xmlStrcat(*msg, BAD_CAST "', "); *msg = xmlStrcat(*msg, BAD_CAST "attribute '"); } else { *msg = xmlStrdup(BAD_CAST "Element '"); } if (node->ns != NULL) *msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str, node->ns->href, node->name)); else *msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str, NULL, node->name)); FREE_AND_NULL(str); *msg = xmlStrcat(*msg, BAD_CAST "': "); } else if (actxt->type == XML_SCHEMA_CTXT_VALIDATOR) { xmlSchemaValidCtxtPtr vctxt = (xmlSchemaValidCtxtPtr) actxt; /* * Work on node infos. */ if (vctxt->inode->nodeType == XML_ATTRIBUTE_NODE) { xmlSchemaNodeInfoPtr ielem = vctxt->elemInfos[vctxt->depth]; *msg = xmlStrdup(BAD_CAST "Element '"); *msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str, ielem->nsName, ielem->localName)); FREE_AND_NULL(str); *msg = xmlStrcat(*msg, BAD_CAST "', "); *msg = xmlStrcat(*msg, BAD_CAST "attribute '"); } else { *msg = xmlStrdup(BAD_CAST "Element '"); } *msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str, vctxt->inode->nsName, vctxt->inode->localName)); FREE_AND_NULL(str); *msg = xmlStrcat(*msg, BAD_CAST "': "); } else if (actxt->type == XML_SCHEMA_CTXT_PARSER) { /* * Hmm, no node while parsing? * Return an empty string, in case NULL will break something. */ *msg = xmlStrdup(BAD_CAST ""); } else { TODO return (NULL); } /* * xmlSchemaFormatItemForReport() also returns an escaped format * string, so do this before calling it below (in the future). */ xmlEscapeFormatString(msg); /* * VAL TODO: The output of the given schema component is currently * disabled. */ #if 0 if ((type != NULL) && (xmlSchemaIsGlobalItem(type))) { *msg = xmlStrcat(*msg, BAD_CAST " ["); *msg = xmlStrcat(*msg, xmlSchemaFormatItemForReport(&str, NULL, type, NULL, 0)); FREE_AND_NULL(str) *msg = xmlStrcat(*msg, BAD_CAST "]"); } #endif return (*msg); } static void LIBXML_ATTR_FORMAT(3,0) xmlSchemaInternalErr2(xmlSchemaAbstractCtxtPtr actxt, const char *funcName, const char *message, const xmlChar *str1, const xmlChar *str2) { xmlChar *msg = NULL; if (actxt == NULL) return; msg = xmlStrdup(BAD_CAST "Internal error: %s, "); msg = xmlStrcat(msg, BAD_CAST message); msg = xmlStrcat(msg, BAD_CAST ".\n"); if (actxt->type == XML_SCHEMA_CTXT_VALIDATOR) xmlSchemaErr3(actxt, XML_SCHEMAV_INTERNAL, NULL, (const char *) msg, (const xmlChar *) funcName, str1, str2); else if (actxt->type == XML_SCHEMA_CTXT_PARSER) xmlSchemaErr3(actxt, XML_SCHEMAP_INTERNAL, NULL, (const char *) msg, (const xmlChar *) funcName, str1, str2); FREE_AND_NULL(msg) } static void LIBXML_ATTR_FORMAT(3,0) xmlSchemaInternalErr(xmlSchemaAbstractCtxtPtr actxt, const char *funcName, const char *message) { xmlSchemaInternalErr2(actxt, funcName, message, NULL, NULL); } #if 0 static void LIBXML_ATTR_FORMAT(3,0) xmlSchemaPInternalErr(xmlSchemaParserCtxtPtr pctxt, const char *funcName, const char *message, const xmlChar *str1, const xmlChar *str2) { xmlSchemaInternalErr2(ACTXT_CAST pctxt, funcName, message, str1, str2); } #endif static void LIBXML_ATTR_FORMAT(5,0) xmlSchemaCustomErr4(xmlSchemaAbstractCtxtPtr actxt, xmlParserErrors error, xmlNodePtr node, xmlSchemaBasicItemPtr item, const char *message, const xmlChar *str1, const xmlChar *str2, const xmlChar *str3, const xmlChar *str4) { xmlChar *msg = NULL; if ((node == NULL) && (item != NULL) && (actxt->type == XML_SCHEMA_CTXT_PARSER)) { node = WXS_ITEM_NODE(item); xmlSchemaFormatItemForReport(&msg, NULL, item, NULL); msg = xmlStrcat(msg, BAD_CAST ": "); } else xmlSchemaFormatNodeForError(&msg, actxt, node); msg = xmlStrcat(msg, (const xmlChar *) message); msg = xmlStrcat(msg, BAD_CAST ".\n"); xmlSchemaErr4(actxt, error, node, (const char *) msg, str1, str2, str3, str4); FREE_AND_NULL(msg) } static void LIBXML_ATTR_FORMAT(5,0) xmlSchemaCustomErr(xmlSchemaAbstractCtxtPtr actxt, xmlParserErrors error, xmlNodePtr node, xmlSchemaBasicItemPtr item, const char *message, const xmlChar *str1, const xmlChar *str2) { xmlSchemaCustomErr4(actxt, error, node, item, message, str1, str2, NULL, NULL); } static void LIBXML_ATTR_FORMAT(5,0) xmlSchemaCustomWarning(xmlSchemaAbstractCtxtPtr actxt, xmlParserErrors error, xmlNodePtr node, xmlSchemaTypePtr type ATTRIBUTE_UNUSED, const char *message, const xmlChar *str1, const xmlChar *str2, const xmlChar *str3) { xmlChar *msg = NULL; xmlSchemaFormatNodeForError(&msg, actxt, node); msg = xmlStrcat(msg, (const xmlChar *) message); msg = xmlStrcat(msg, BAD_CAST ".\n"); /* URGENT TODO: Set the error code to something sane. */ xmlSchemaErr4Line(actxt, XML_ERR_WARNING, error, node, 0, (const char *) msg, str1, str2, str3, NULL); FREE_AND_NULL(msg) } static void LIBXML_ATTR_FORMAT(5,0) xmlSchemaKeyrefErr(xmlSchemaValidCtxtPtr vctxt, xmlParserErrors error, xmlSchemaPSVIIDCNodePtr idcNode, xmlSchemaTypePtr type ATTRIBUTE_UNUSED, const char *message, const xmlChar *str1, const xmlChar *str2) { xmlChar *msg = NULL, *qname = NULL; msg = xmlStrdup(BAD_CAST "Element '%s': "); msg = xmlStrcat(msg, (const xmlChar *) message); msg = xmlStrcat(msg, BAD_CAST ".\n"); xmlSchemaErr4Line(ACTXT_CAST vctxt, XML_ERR_ERROR, error, NULL, idcNode->nodeLine, (const char *) msg, xmlSchemaFormatQName(&qname, vctxt->nodeQNames->items[idcNode->nodeQNameID +1], vctxt->nodeQNames->items[idcNode->nodeQNameID]), str1, str2, NULL); FREE_AND_NULL(qname); FREE_AND_NULL(msg); } static int xmlSchemaEvalErrorNodeType(xmlSchemaAbstractCtxtPtr actxt, xmlNodePtr node) { if (node != NULL) return (node->type); if ((actxt->type == XML_SCHEMA_CTXT_VALIDATOR) && (((xmlSchemaValidCtxtPtr) actxt)->inode != NULL)) return ( ((xmlSchemaValidCtxtPtr) actxt)->inode->nodeType); return (-1); } static int xmlSchemaIsGlobalItem(xmlSchemaTypePtr item) { switch (item->type) { case XML_SCHEMA_TYPE_COMPLEX: case XML_SCHEMA_TYPE_SIMPLE: if (item->flags & XML_SCHEMAS_TYPE_GLOBAL) return(1); break; case XML_SCHEMA_TYPE_GROUP: return (1); case XML_SCHEMA_TYPE_ELEMENT: if ( ((xmlSchemaElementPtr) item)->flags & XML_SCHEMAS_ELEM_GLOBAL) return(1); break; case XML_SCHEMA_TYPE_ATTRIBUTE: if ( ((xmlSchemaAttributePtr) item)->flags & XML_SCHEMAS_ATTR_GLOBAL) return(1); break; /* Note that attribute groups are always global. */ default: return(1); } return (0); } static void xmlSchemaSimpleTypeErr(xmlSchemaAbstractCtxtPtr actxt, xmlParserErrors error, xmlNodePtr node, const xmlChar *value, xmlSchemaTypePtr type, int displayValue) { xmlChar *msg = NULL; xmlSchemaFormatNodeForError(&msg, actxt, node); if (displayValue || (xmlSchemaEvalErrorNodeType(actxt, node) == XML_ATTRIBUTE_NODE)) msg = xmlStrcat(msg, BAD_CAST "'%s' is not a valid value of "); else msg = xmlStrcat(msg, BAD_CAST "The character content is not a valid " "value of "); if (! xmlSchemaIsGlobalItem(type)) msg = xmlStrcat(msg, BAD_CAST "the local "); else msg = xmlStrcat(msg, BAD_CAST "the "); if (WXS_IS_ATOMIC(type)) msg = xmlStrcat(msg, BAD_CAST "atomic type"); else if (WXS_IS_LIST(type)) msg = xmlStrcat(msg, BAD_CAST "list type"); else if (WXS_IS_UNION(type)) msg = xmlStrcat(msg, BAD_CAST "union type"); if (xmlSchemaIsGlobalItem(type)) { xmlChar *str = NULL; msg = xmlStrcat(msg, BAD_CAST " '"); if (type->builtInType != 0) { msg = xmlStrcat(msg, BAD_CAST "xs:"); str = xmlStrdup(type->name); } else { const xmlChar *qName = xmlSchemaFormatQName(&str, type->targetNamespace, type->name); if (!str) str = xmlStrdup(qName); } msg = xmlStrcat(msg, xmlEscapeFormatString(&str)); msg = xmlStrcat(msg, BAD_CAST "'"); FREE_AND_NULL(str); } msg = xmlStrcat(msg, BAD_CAST ".\n"); if (displayValue || (xmlSchemaEvalErrorNodeType(actxt, node) == XML_ATTRIBUTE_NODE)) xmlSchemaErr(actxt, error, node, (const char *) msg, value, NULL); else xmlSchemaErr(actxt, error, node, (const char *) msg, NULL, NULL); FREE_AND_NULL(msg) } static const xmlChar * xmlSchemaFormatErrorNodeQName(xmlChar ** str, xmlSchemaNodeInfoPtr ni, xmlNodePtr node) { if (node != NULL) { if (node->ns != NULL) return (xmlSchemaFormatQName(str, node->ns->href, node->name)); else return (xmlSchemaFormatQName(str, NULL, node->name)); } else if (ni != NULL) return (xmlSchemaFormatQName(str, ni->nsName, ni->localName)); return (NULL); } static void xmlSchemaIllegalAttrErr(xmlSchemaAbstractCtxtPtr actxt, xmlParserErrors error, xmlSchemaAttrInfoPtr ni, xmlNodePtr node) { xmlChar *msg = NULL, *str = NULL; xmlSchemaFormatNodeForError(&msg, actxt, node); msg = xmlStrcat(msg, BAD_CAST "The attribute '%s' is not allowed.\n"); xmlSchemaErr(actxt, error, node, (const char *) msg, xmlSchemaFormatErrorNodeQName(&str, (xmlSchemaNodeInfoPtr) ni, node), NULL); FREE_AND_NULL(str) FREE_AND_NULL(msg) } static void LIBXML_ATTR_FORMAT(5,0) xmlSchemaComplexTypeErr(xmlSchemaAbstractCtxtPtr actxt, xmlParserErrors error, xmlNodePtr node, xmlSchemaTypePtr type ATTRIBUTE_UNUSED, const char *message, int nbval, int nbneg, xmlChar **values) { xmlChar *str = NULL, *msg = NULL; xmlChar *localName, *nsName; const xmlChar *cur, *end; int i; xmlSchemaFormatNodeForError(&msg, actxt, node); msg = xmlStrcat(msg, (const xmlChar *) message); msg = xmlStrcat(msg, BAD_CAST "."); /* * Note that is does not make sense to report that we have a * wildcard here, since the wildcard might be unfolded into * multiple transitions. */ if (nbval + nbneg > 0) { if (nbval + nbneg > 1) { str = xmlStrdup(BAD_CAST " Expected is one of ( "); } else str = xmlStrdup(BAD_CAST " Expected is ( "); nsName = NULL; for (i = 0; i < nbval + nbneg; i++) { cur = values[i]; if (cur == NULL) continue; if ((cur[0] == 'n') && (cur[1] == 'o') && (cur[2] == 't') && (cur[3] == ' ')) { cur += 4; str = xmlStrcat(str, BAD_CAST "##other"); } /* * Get the local name. */ localName = NULL; end = cur; if (*end == '*') { localName = xmlStrdup(BAD_CAST "*"); end++; } else { while ((*end != 0) && (*end != '|')) end++; localName = xmlStrncat(localName, BAD_CAST cur, end - cur); } if (*end != 0) { end++; /* * Skip "*|*" if they come with negated expressions, since * they represent the same negated wildcard. */ if ((nbneg == 0) || (*end != '*') || (*localName != '*')) { /* * Get the namespace name. */ cur = end; if (*end == '*') { nsName = xmlStrdup(BAD_CAST "{*}"); } else { while (*end != 0) end++; if (i >= nbval) nsName = xmlStrdup(BAD_CAST "{##other:"); else nsName = xmlStrdup(BAD_CAST "{"); nsName = xmlStrncat(nsName, BAD_CAST cur, end - cur); nsName = xmlStrcat(nsName, BAD_CAST "}"); } str = xmlStrcat(str, BAD_CAST nsName); FREE_AND_NULL(nsName) } else { FREE_AND_NULL(localName); continue; } } str = xmlStrcat(str, BAD_CAST localName); FREE_AND_NULL(localName); if (i < nbval + nbneg -1) str = xmlStrcat(str, BAD_CAST ", "); } str = xmlStrcat(str, BAD_CAST " ).\n"); msg = xmlStrcat(msg, xmlEscapeFormatString(&str)); FREE_AND_NULL(str) } else msg = xmlStrcat(msg, BAD_CAST "\n"); xmlSchemaErr(actxt, error, node, (const char *) msg, NULL, NULL); xmlFree(msg); } static void LIBXML_ATTR_FORMAT(8,0) xmlSchemaFacetErr(xmlSchemaAbstractCtxtPtr actxt, xmlParserErrors error, xmlNodePtr node, const xmlChar *value, unsigned long length, xmlSchemaTypePtr type, xmlSchemaFacetPtr facet, const char *message, const xmlChar *str1, const xmlChar *str2) { xmlChar *str = NULL, *msg = NULL; xmlSchemaTypeType facetType; int nodeType = xmlSchemaEvalErrorNodeType(actxt, node); xmlSchemaFormatNodeForError(&msg, actxt, node); if (error == XML_SCHEMAV_CVC_ENUMERATION_VALID) { facetType = XML_SCHEMA_FACET_ENUMERATION; /* * If enumerations are validated, one must not expect the * facet to be given. */ } else facetType = facet->type; msg = xmlStrcat(msg, BAD_CAST "["); msg = xmlStrcat(msg, BAD_CAST "facet '"); msg = xmlStrcat(msg, xmlSchemaFacetTypeToString(facetType)); msg = xmlStrcat(msg, BAD_CAST "'] "); if (message == NULL) { /* * Use a default message. */ if ((facetType == XML_SCHEMA_FACET_LENGTH) || (facetType == XML_SCHEMA_FACET_MINLENGTH) || (facetType == XML_SCHEMA_FACET_MAXLENGTH)) { char len[25], actLen[25]; /* FIXME, TODO: What is the max expected string length of the * this value? */ if (nodeType == XML_ATTRIBUTE_NODE) msg = xmlStrcat(msg, BAD_CAST "The value '%s' has a length of '%s'; "); else msg = xmlStrcat(msg, BAD_CAST "The value has a length of '%s'; "); snprintf(len, 24, "%lu", xmlSchemaGetFacetValueAsULong(facet)); snprintf(actLen, 24, "%lu", length); if (facetType == XML_SCHEMA_FACET_LENGTH) msg = xmlStrcat(msg, BAD_CAST "this differs from the allowed length of '%s'.\n"); else if (facetType == XML_SCHEMA_FACET_MAXLENGTH) msg = xmlStrcat(msg, BAD_CAST "this exceeds the allowed maximum length of '%s'.\n"); else if (facetType == XML_SCHEMA_FACET_MINLENGTH) msg = xmlStrcat(msg, BAD_CAST "this underruns the allowed minimum length of '%s'.\n"); if (nodeType == XML_ATTRIBUTE_NODE) xmlSchemaErr3(actxt, error, node, (const char *) msg, value, (const xmlChar *) actLen, (const xmlChar *) len); else xmlSchemaErr(actxt, error, node, (const char *) msg, (const xmlChar *) actLen, (const xmlChar *) len); } else if (facetType == XML_SCHEMA_FACET_ENUMERATION) { msg = xmlStrcat(msg, BAD_CAST "The value '%s' is not an element " "of the set {%s}.\n"); xmlSchemaErr(actxt, error, node, (const char *) msg, value, xmlSchemaFormatFacetEnumSet(actxt, &str, type)); } else if (facetType == XML_SCHEMA_FACET_PATTERN) { msg = xmlStrcat(msg, BAD_CAST "The value '%s' is not accepted " "by the pattern '%s'.\n"); xmlSchemaErr(actxt, error, node, (const char *) msg, value, facet->value); } else if (facetType == XML_SCHEMA_FACET_MININCLUSIVE) { msg = xmlStrcat(msg, BAD_CAST "The value '%s' is less than the " "minimum value allowed ('%s').\n"); xmlSchemaErr(actxt, error, node, (const char *) msg, value, facet->value); } else if (facetType == XML_SCHEMA_FACET_MAXINCLUSIVE) { msg = xmlStrcat(msg, BAD_CAST "The value '%s' is greater than the " "maximum value allowed ('%s').\n"); xmlSchemaErr(actxt, error, node, (const char *) msg, value, facet->value); } else if (facetType == XML_SCHEMA_FACET_MINEXCLUSIVE) { msg = xmlStrcat(msg, BAD_CAST "The value '%s' must be greater than " "'%s'.\n"); xmlSchemaErr(actxt, error, node, (const char *) msg, value, facet->value); } else if (facetType == XML_SCHEMA_FACET_MAXEXCLUSIVE) { msg = xmlStrcat(msg, BAD_CAST "The value '%s' must be less than " "'%s'.\n"); xmlSchemaErr(actxt, error, node, (const char *) msg, value, facet->value); } else if (facetType == XML_SCHEMA_FACET_TOTALDIGITS) { msg = xmlStrcat(msg, BAD_CAST "The value '%s' has more " "digits than are allowed ('%s').\n"); xmlSchemaErr(actxt, error, node, (const char*) msg, value, facet->value); } else if (facetType == XML_SCHEMA_FACET_FRACTIONDIGITS) { msg = xmlStrcat(msg, BAD_CAST "The value '%s' has more fractional " "digits than are allowed ('%s').\n"); xmlSchemaErr(actxt, error, node, (const char*) msg, value, facet->value); } else if (nodeType == XML_ATTRIBUTE_NODE) { msg = xmlStrcat(msg, BAD_CAST "The value '%s' is not facet-valid.\n"); xmlSchemaErr(actxt, error, node, (const char *) msg, value, NULL); } else { msg = xmlStrcat(msg, BAD_CAST "The value is not facet-valid.\n"); xmlSchemaErr(actxt, error, node, (const char *) msg, NULL, NULL); } } else { msg = xmlStrcat(msg, (const xmlChar *) message); msg = xmlStrcat(msg, BAD_CAST ".\n"); xmlSchemaErr(actxt, error, node, (const char *) msg, str1, str2); } FREE_AND_NULL(str) xmlFree(msg); } #define VERROR(err, type, msg) \ xmlSchemaCustomErr(ACTXT_CAST vctxt, err, NULL, type, msg, NULL, NULL); #define VERROR_INT(func, msg) xmlSchemaInternalErr(ACTXT_CAST vctxt, func, msg); #define PERROR_INT(func, msg) xmlSchemaInternalErr(ACTXT_CAST pctxt, func, msg); #define PERROR_INT2(func, msg) xmlSchemaInternalErr(ACTXT_CAST ctxt, func, msg); #define AERROR_INT(func, msg) xmlSchemaInternalErr(actxt, func, msg); /** * xmlSchemaPMissingAttrErr: * @ctxt: the schema validation context * @ownerItem: the owner as a schema object * @ownerElem: the owner as an element node * @node: the parent element node of the missing attribute node * @type: the corresponding type of the attribute node * * Reports an illegal attribute. */ static void xmlSchemaPMissingAttrErr(xmlSchemaParserCtxtPtr ctxt, xmlParserErrors error, xmlSchemaBasicItemPtr ownerItem, xmlNodePtr ownerElem, const char *name, const char *message) { xmlChar *des = NULL; xmlSchemaFormatItemForReport(&des, NULL, ownerItem, ownerElem); if (message != NULL) xmlSchemaPErr(ctxt, ownerElem, error, "%s: %s.\n", BAD_CAST des, BAD_CAST message); else xmlSchemaPErr(ctxt, ownerElem, error, "%s: The attribute '%s' is required but missing.\n", BAD_CAST des, BAD_CAST name); FREE_AND_NULL(des); } /** * xmlSchemaPResCompAttrErr: * @ctxt: the schema validation context * @error: the error code * @ownerItem: the owner as a schema object * @ownerElem: the owner as an element node * @name: the name of the attribute holding the QName * @refName: the referenced local name * @refURI: the referenced namespace URI * @message: optional message * * Used to report QName attribute values that failed to resolve * to schema components. */ static void xmlSchemaPResCompAttrErr(xmlSchemaParserCtxtPtr ctxt, xmlParserErrors error, xmlSchemaBasicItemPtr ownerItem, xmlNodePtr ownerElem, const char *name, const xmlChar *refName, const xmlChar *refURI, xmlSchemaTypeType refType, const char *refTypeStr) { xmlChar *des = NULL, *strA = NULL; xmlSchemaFormatItemForReport(&des, NULL, ownerItem, ownerElem); if (refTypeStr == NULL) refTypeStr = (const char *) xmlSchemaItemTypeToStr(refType); xmlSchemaPErrExt(ctxt, ownerElem, error, NULL, NULL, NULL, "%s, attribute '%s': The QName value '%s' does not resolve to a(n) " "%s.\n", BAD_CAST des, BAD_CAST name, xmlSchemaFormatQName(&strA, refURI, refName), BAD_CAST refTypeStr, NULL); FREE_AND_NULL(des) FREE_AND_NULL(strA) } /** * xmlSchemaPCustomAttrErr: * @ctxt: the schema parser context * @error: the error code * @ownerDes: the designation of the owner * @ownerItem: the owner as a schema object * @attr: the illegal attribute node * * Reports an illegal attribute during the parse. */ static void xmlSchemaPCustomAttrErr(xmlSchemaParserCtxtPtr ctxt, xmlParserErrors error, xmlChar **ownerDes, xmlSchemaBasicItemPtr ownerItem, xmlAttrPtr attr, const char *msg) { xmlChar *des = NULL; if (ownerDes == NULL) xmlSchemaFormatItemForReport(&des, NULL, ownerItem, attr->parent); else if (*ownerDes == NULL) { xmlSchemaFormatItemForReport(ownerDes, NULL, ownerItem, attr->parent); des = *ownerDes; } else des = *ownerDes; if (attr == NULL) { xmlSchemaPErrExt(ctxt, NULL, error, NULL, NULL, NULL, "%s, attribute '%s': %s.\n", BAD_CAST des, (const xmlChar *) "Unknown", (const xmlChar *) msg, NULL, NULL); } else { xmlSchemaPErrExt(ctxt, (xmlNodePtr) attr, error, NULL, NULL, NULL, "%s, attribute '%s': %s.\n", BAD_CAST des, attr->name, (const xmlChar *) msg, NULL, NULL); } if (ownerDes == NULL) FREE_AND_NULL(des); } /** * xmlSchemaPIllegalAttrErr: * @ctxt: the schema parser context * @error: the error code * @ownerItem: the attribute's owner item * @attr: the illegal attribute node * * Reports an illegal attribute during the parse. */ static void xmlSchemaPIllegalAttrErr(xmlSchemaParserCtxtPtr ctxt, xmlParserErrors error, xmlSchemaBasicItemPtr ownerComp ATTRIBUTE_UNUSED, xmlAttrPtr attr) { xmlChar *strA = NULL, *strB = NULL; xmlSchemaFormatNodeForError(&strA, ACTXT_CAST ctxt, attr->parent); xmlSchemaErr4(ACTXT_CAST ctxt, error, (xmlNodePtr) attr, "%sThe attribute '%s' is not allowed.\n", BAD_CAST strA, xmlSchemaFormatQNameNs(&strB, attr->ns, attr->name), NULL, NULL); FREE_AND_NULL(strA); FREE_AND_NULL(strB); } /** * xmlSchemaPCustomErr: * @ctxt: the schema parser context * @error: the error code * @itemDes: the designation of the schema item * @item: the schema item * @itemElem: the node of the schema item * @message: the error message * @str1: an optional param for the error message * @str2: an optional param for the error message * @str3: an optional param for the error message * * Reports an error during parsing. */ static void LIBXML_ATTR_FORMAT(5,0) xmlSchemaPCustomErrExt(xmlSchemaParserCtxtPtr ctxt, xmlParserErrors error, xmlSchemaBasicItemPtr item, xmlNodePtr itemElem, const char *message, const xmlChar *str1, const xmlChar *str2, const xmlChar *str3) { xmlChar *des = NULL, *msg = NULL; xmlSchemaFormatItemForReport(&des, NULL, item, itemElem); msg = xmlStrdup(BAD_CAST "%s: "); msg = xmlStrcat(msg, (const xmlChar *) message); msg = xmlStrcat(msg, BAD_CAST ".\n"); if ((itemElem == NULL) && (item != NULL)) itemElem = WXS_ITEM_NODE(item); xmlSchemaPErrExt(ctxt, itemElem, error, NULL, NULL, NULL, (const char *) msg, BAD_CAST des, str1, str2, str3, NULL); FREE_AND_NULL(des); FREE_AND_NULL(msg); } /** * xmlSchemaPCustomErr: * @ctxt: the schema parser context * @error: the error code * @itemDes: the designation of the schema item * @item: the schema item * @itemElem: the node of the schema item * @message: the error message * @str1: the optional param for the error message * * Reports an error during parsing. */ static void LIBXML_ATTR_FORMAT(5,0) xmlSchemaPCustomErr(xmlSchemaParserCtxtPtr ctxt, xmlParserErrors error, xmlSchemaBasicItemPtr item, xmlNodePtr itemElem, const char *message, const xmlChar *str1) { xmlSchemaPCustomErrExt(ctxt, error, item, itemElem, message, str1, NULL, NULL); } /** * xmlSchemaPAttrUseErr: * @ctxt: the schema parser context * @error: the error code * @itemDes: the designation of the schema type * @item: the schema type * @itemElem: the node of the schema type * @attr: the invalid schema attribute * @message: the error message * @str1: the optional param for the error message * * Reports an attribute use error during parsing. */ static void LIBXML_ATTR_FORMAT(6,0) xmlSchemaPAttrUseErr4(xmlSchemaParserCtxtPtr ctxt, xmlParserErrors error, xmlNodePtr node, xmlSchemaBasicItemPtr ownerItem, const xmlSchemaAttributeUsePtr attruse, const char *message, const xmlChar *str1, const xmlChar *str2, const xmlChar *str3,const xmlChar *str4) { xmlChar *str = NULL, *msg = NULL; xmlSchemaFormatItemForReport(&msg, NULL, ownerItem, NULL); msg = xmlStrcat(msg, BAD_CAST ", "); msg = xmlStrcat(msg, BAD_CAST xmlSchemaFormatItemForReport(&str, NULL, WXS_BASIC_CAST attruse, NULL)); FREE_AND_NULL(str); msg = xmlStrcat(msg, BAD_CAST ": "); msg = xmlStrcat(msg, (const xmlChar *) message); msg = xmlStrcat(msg, BAD_CAST ".\n"); xmlSchemaErr4(ACTXT_CAST ctxt, error, node, (const char *) msg, str1, str2, str3, str4); xmlFree(msg); } /** * xmlSchemaPIllegalFacetAtomicErr: * @ctxt: the schema parser context * @error: the error code * @type: the schema type * @baseType: the base type of type * @facet: the illegal facet * * Reports an illegal facet for atomic simple types. */ static void xmlSchemaPIllegalFacetAtomicErr(xmlSchemaParserCtxtPtr ctxt, xmlParserErrors error, xmlSchemaTypePtr type, xmlSchemaTypePtr baseType, xmlSchemaFacetPtr facet) { xmlChar *des = NULL, *strT = NULL; xmlSchemaFormatItemForReport(&des, NULL, WXS_BASIC_CAST type, type->node); xmlSchemaPErrExt(ctxt, type->node, error, NULL, NULL, NULL, "%s: The facet '%s' is not allowed on types derived from the " "type %s.\n", BAD_CAST des, xmlSchemaFacetTypeToString(facet->type), xmlSchemaFormatItemForReport(&strT, NULL, WXS_BASIC_CAST baseType, NULL), NULL, NULL); FREE_AND_NULL(des); FREE_AND_NULL(strT); } /** * xmlSchemaPIllegalFacetListUnionErr: * @ctxt: the schema parser context * @error: the error code * @itemDes: the designation of the schema item involved * @item: the schema item involved * @facet: the illegal facet * * Reports an illegal facet for <list> and <union>. */ static void xmlSchemaPIllegalFacetListUnionErr(xmlSchemaParserCtxtPtr ctxt, xmlParserErrors error, xmlSchemaTypePtr type, xmlSchemaFacetPtr facet) { xmlChar *des = NULL; xmlSchemaFormatItemForReport(&des, NULL, WXS_BASIC_CAST type, type->node); xmlSchemaPErr(ctxt, type->node, error, "%s: The facet '%s' is not allowed.\n", BAD_CAST des, xmlSchemaFacetTypeToString(facet->type)); FREE_AND_NULL(des); } /** * xmlSchemaPMutualExclAttrErr: * @ctxt: the schema validation context * @error: the error code * @elemDes: the designation of the parent element node * @attr: the bad attribute node * @type: the corresponding type of the attribute node * * Reports an illegal attribute. */ static void xmlSchemaPMutualExclAttrErr(xmlSchemaParserCtxtPtr ctxt, xmlParserErrors error, xmlSchemaBasicItemPtr ownerItem, xmlAttrPtr attr, const char *name1, const char *name2) { xmlChar *des = NULL; xmlSchemaFormatItemForReport(&des, NULL, WXS_BASIC_CAST ownerItem, attr->parent); xmlSchemaPErrExt(ctxt, (xmlNodePtr) attr, error, NULL, NULL, NULL, "%s: The attributes '%s' and '%s' are mutually exclusive.\n", BAD_CAST des, BAD_CAST name1, BAD_CAST name2, NULL, NULL); FREE_AND_NULL(des); } /** * xmlSchemaPSimpleTypeErr: * @ctxt: the schema validation context * @error: the error code * @type: the type specifier * @ownerItem: the schema object if existent * @node: the validated node * @value: the validated value * * Reports a simple type validation error. * TODO: Should this report the value of an element as well? */ static void LIBXML_ATTR_FORMAT(8,0) xmlSchemaPSimpleTypeErr(xmlSchemaParserCtxtPtr ctxt, xmlParserErrors error, xmlSchemaBasicItemPtr ownerItem ATTRIBUTE_UNUSED, xmlNodePtr node, xmlSchemaTypePtr type, const char *expected, const xmlChar *value, const char *message, const xmlChar *str1, const xmlChar *str2) { xmlChar *msg = NULL; xmlSchemaFormatNodeForError(&msg, ACTXT_CAST ctxt, node); if (message == NULL) { /* * Use default messages. */ if (type != NULL) { if (node->type == XML_ATTRIBUTE_NODE) msg = xmlStrcat(msg, BAD_CAST "'%s' is not a valid value of "); else msg = xmlStrcat(msg, BAD_CAST "The character content is not a " "valid value of "); if (! xmlSchemaIsGlobalItem(type)) msg = xmlStrcat(msg, BAD_CAST "the local "); else msg = xmlStrcat(msg, BAD_CAST "the "); if (WXS_IS_ATOMIC(type)) msg = xmlStrcat(msg, BAD_CAST "atomic type"); else if (WXS_IS_LIST(type)) msg = xmlStrcat(msg, BAD_CAST "list type"); else if (WXS_IS_UNION(type)) msg = xmlStrcat(msg, BAD_CAST "union type"); if (xmlSchemaIsGlobalItem(type)) { xmlChar *str = NULL; msg = xmlStrcat(msg, BAD_CAST " '"); if (type->builtInType != 0) { msg = xmlStrcat(msg, BAD_CAST "xs:"); str = xmlStrdup(type->name); } else { const xmlChar *qName = xmlSchemaFormatQName(&str, type->targetNamespace, type->name); if (!str) str = xmlStrdup(qName); } msg = xmlStrcat(msg, xmlEscapeFormatString(&str)); msg = xmlStrcat(msg, BAD_CAST "'."); FREE_AND_NULL(str); } } else { if (node->type == XML_ATTRIBUTE_NODE) msg = xmlStrcat(msg, BAD_CAST "The value '%s' is not valid."); else msg = xmlStrcat(msg, BAD_CAST "The character content is not " "valid."); } if (expected) { xmlChar *expectedEscaped = xmlCharStrdup(expected); msg = xmlStrcat(msg, BAD_CAST " Expected is '"); msg = xmlStrcat(msg, xmlEscapeFormatString(&expectedEscaped)); FREE_AND_NULL(expectedEscaped); msg = xmlStrcat(msg, BAD_CAST "'.\n"); } else msg = xmlStrcat(msg, BAD_CAST "\n"); if (node->type == XML_ATTRIBUTE_NODE) xmlSchemaPErr(ctxt, node, error, (const char *) msg, value, NULL); else xmlSchemaPErr(ctxt, node, error, (const char *) msg, NULL, NULL); } else { msg = xmlStrcat(msg, BAD_CAST message); msg = xmlStrcat(msg, BAD_CAST ".\n"); xmlSchemaPErrExt(ctxt, node, error, NULL, NULL, NULL, (const char*) msg, str1, str2, NULL, NULL, NULL); } /* Cleanup. */ FREE_AND_NULL(msg) } /** * xmlSchemaPContentErr: * @ctxt: the schema parser context * @error: the error code * @ownerItem: the owner item of the holder of the content * @ownerElem: the node of the holder of the content * @child: the invalid child node * @message: the optional error message * @content: the optional string describing the correct content * * Reports an error concerning the content of a schema element. */ static void xmlSchemaPContentErr(xmlSchemaParserCtxtPtr ctxt, xmlParserErrors error, xmlSchemaBasicItemPtr ownerItem, xmlNodePtr ownerElem, xmlNodePtr child, const char *message, const char *content) { xmlChar *des = NULL; xmlSchemaFormatItemForReport(&des, NULL, ownerItem, ownerElem); if (message != NULL) xmlSchemaPErr2(ctxt, ownerElem, child, error, "%s: %s.\n", BAD_CAST des, BAD_CAST message); else { if (content != NULL) { xmlSchemaPErr2(ctxt, ownerElem, child, error, "%s: The content is not valid. Expected is %s.\n", BAD_CAST des, BAD_CAST content); } else { xmlSchemaPErr2(ctxt, ownerElem, child, error, "%s: The content is not valid.\n", BAD_CAST des, NULL); } } FREE_AND_NULL(des) } /************************************************************************ * * * Streamable error functions * * * ************************************************************************/ /************************************************************************ * * * Validation helper functions * * * ************************************************************************/ /************************************************************************ * * * Allocation functions * * * ************************************************************************/ /** * xmlSchemaNewSchemaForParserCtxt: * @ctxt: a schema validation context * * Allocate a new Schema structure. * * Returns the newly allocated structure or NULL in case or error */ static xmlSchemaPtr xmlSchemaNewSchema(xmlSchemaParserCtxtPtr ctxt) { xmlSchemaPtr ret; ret = (xmlSchemaPtr) xmlMalloc(sizeof(xmlSchema)); if (ret == NULL) { xmlSchemaPErrMemory(ctxt, "allocating schema", NULL); return (NULL); } memset(ret, 0, sizeof(xmlSchema)); ret->dict = ctxt->dict; xmlDictReference(ret->dict); return (ret); } /** * xmlSchemaNewFacet: * * Allocate a new Facet structure. * * Returns the newly allocated structure or NULL in case or error */ xmlSchemaFacetPtr xmlSchemaNewFacet(void) { xmlSchemaFacetPtr ret; ret = (xmlSchemaFacetPtr) xmlMalloc(sizeof(xmlSchemaFacet)); if (ret == NULL) { return (NULL); } memset(ret, 0, sizeof(xmlSchemaFacet)); return (ret); } /** * xmlSchemaNewAnnot: * @ctxt: a schema validation context * @node: a node * * Allocate a new annotation structure. * * Returns the newly allocated structure or NULL in case or error */ static xmlSchemaAnnotPtr xmlSchemaNewAnnot(xmlSchemaParserCtxtPtr ctxt, xmlNodePtr node) { xmlSchemaAnnotPtr ret; ret = (xmlSchemaAnnotPtr) xmlMalloc(sizeof(xmlSchemaAnnot)); if (ret == NULL) { xmlSchemaPErrMemory(ctxt, "allocating annotation", node); return (NULL); } memset(ret, 0, sizeof(xmlSchemaAnnot)); ret->content = node; return (ret); } static xmlSchemaItemListPtr xmlSchemaItemListCreate(void) { xmlSchemaItemListPtr ret; ret = xmlMalloc(sizeof(xmlSchemaItemList)); if (ret == NULL) { xmlSchemaPErrMemory(NULL, "allocating an item list structure", NULL); return (NULL); } memset(ret, 0, sizeof(xmlSchemaItemList)); return (ret); } static void xmlSchemaItemListClear(xmlSchemaItemListPtr list) { if (list->items != NULL) { xmlFree(list->items); list->items = NULL; } list->nbItems = 0; list->sizeItems = 0; } static int xmlSchemaItemListAdd(xmlSchemaItemListPtr list, void *item) { if (list->items == NULL) { list->items = (void **) xmlMalloc( 20 * sizeof(void *)); if (list->items == NULL) { xmlSchemaPErrMemory(NULL, "allocating new item list", NULL); return(-1); } list->sizeItems = 20; } else if (list->sizeItems <= list->nbItems) { list->sizeItems *= 2; list->items = (void **) xmlRealloc(list->items, list->sizeItems * sizeof(void *)); if (list->items == NULL) { xmlSchemaPErrMemory(NULL, "growing item list", NULL); list->sizeItems = 0; return(-1); } } list->items[list->nbItems++] = item; return(0); } static int xmlSchemaItemListAddSize(xmlSchemaItemListPtr list, int initialSize, void *item) { if (list->items == NULL) { if (initialSize <= 0) initialSize = 1; list->items = (void **) xmlMalloc( initialSize * sizeof(void *)); if (list->items == NULL) { xmlSchemaPErrMemory(NULL, "allocating new item list", NULL); return(-1); } list->sizeItems = initialSize; } else if (list->sizeItems <= list->nbItems) { list->sizeItems *= 2; list->items = (void **) xmlRealloc(list->items, list->sizeItems * sizeof(void *)); if (list->items == NULL) { xmlSchemaPErrMemory(NULL, "growing item list", NULL); list->sizeItems = 0; return(-1); } } list->items[list->nbItems++] = item; return(0); } static int xmlSchemaItemListInsert(xmlSchemaItemListPtr list, void *item, int idx) { if (list->items == NULL) { list->items = (void **) xmlMalloc( 20 * sizeof(void *)); if (list->items == NULL) { xmlSchemaPErrMemory(NULL, "allocating new item list", NULL); return(-1); } list->sizeItems = 20; } else if (list->sizeItems <= list->nbItems) { list->sizeItems *= 2; list->items = (void **) xmlRealloc(list->items, list->sizeItems * sizeof(void *)); if (list->items == NULL) { xmlSchemaPErrMemory(NULL, "growing item list", NULL); list->sizeItems = 0; return(-1); } } /* * Just append if the index is greater/equal than the item count. */ if (idx >= list->nbItems) { list->items[list->nbItems++] = item; } else { int i; for (i = list->nbItems; i > idx; i--) list->items[i] = list->items[i-1]; list->items[idx] = item; list->nbItems++; } return(0); } #if 0 /* enable if ever needed */ static int xmlSchemaItemListInsertSize(xmlSchemaItemListPtr list, int initialSize, void *item, int idx) { if (list->items == NULL) { if (initialSize <= 0) initialSize = 1; list->items = (void **) xmlMalloc( initialSize * sizeof(void *)); if (list->items == NULL) { xmlSchemaPErrMemory(NULL, "allocating new item list", NULL); return(-1); } list->sizeItems = initialSize; } else if (list->sizeItems <= list->nbItems) { list->sizeItems *= 2; list->items = (void **) xmlRealloc(list->items, list->sizeItems * sizeof(void *)); if (list->items == NULL) { xmlSchemaPErrMemory(NULL, "growing item list", NULL); list->sizeItems = 0; return(-1); } } /* * Just append if the index is greater/equal than the item count. */ if (idx >= list->nbItems) { list->items[list->nbItems++] = item; } else { int i; for (i = list->nbItems; i > idx; i--) list->items[i] = list->items[i-1]; list->items[idx] = item; list->nbItems++; } return(0); } #endif static int xmlSchemaItemListRemove(xmlSchemaItemListPtr list, int idx) { int i; if ((list->items == NULL) || (idx >= list->nbItems)) { xmlSchemaPSimpleErr("Internal error: xmlSchemaItemListRemove, " "index error.\n"); return(-1); } if (list->nbItems == 1) { /* TODO: Really free the list? */ xmlFree(list->items); list->items = NULL; list->nbItems = 0; list->sizeItems = 0; } else if (list->nbItems -1 == idx) { list->nbItems--; } else { for (i = idx; i < list->nbItems -1; i++) list->items[i] = list->items[i+1]; list->nbItems--; } return(0); } /** * xmlSchemaItemListFree: * @annot: a schema type structure * * Deallocate a annotation structure */ static void xmlSchemaItemListFree(xmlSchemaItemListPtr list) { if (list == NULL) return; if (list->items != NULL) xmlFree(list->items); xmlFree(list); } static void xmlSchemaBucketFree(xmlSchemaBucketPtr bucket) { if (bucket == NULL) return; if (bucket->globals != NULL) { xmlSchemaComponentListFree(bucket->globals); xmlSchemaItemListFree(bucket->globals); } if (bucket->locals != NULL) { xmlSchemaComponentListFree(bucket->locals); xmlSchemaItemListFree(bucket->locals); } if (bucket->relations != NULL) { xmlSchemaSchemaRelationPtr prev, cur = bucket->relations; do { prev = cur; cur = cur->next; xmlFree(prev); } while (cur != NULL); } if ((! bucket->preserveDoc) && (bucket->doc != NULL)) { xmlFreeDoc(bucket->doc); } if (bucket->type == XML_SCHEMA_SCHEMA_IMPORT) { if (WXS_IMPBUCKET(bucket)->schema != NULL) xmlSchemaFree(WXS_IMPBUCKET(bucket)->schema); } xmlFree(bucket); } static void xmlSchemaBucketFreeEntry(void *bucket, const xmlChar *name ATTRIBUTE_UNUSED) { xmlSchemaBucketFree((xmlSchemaBucketPtr) bucket); } static xmlSchemaBucketPtr xmlSchemaBucketCreate(xmlSchemaParserCtxtPtr pctxt, int type, const xmlChar *targetNamespace) { xmlSchemaBucketPtr ret; int size; xmlSchemaPtr mainSchema; if (WXS_CONSTRUCTOR(pctxt)->mainSchema == NULL) { PERROR_INT("xmlSchemaBucketCreate", "no main schema on constructor"); return(NULL); } mainSchema = WXS_CONSTRUCTOR(pctxt)->mainSchema; /* Create the schema bucket. */ if (WXS_IS_BUCKET_INCREDEF(type)) size = sizeof(xmlSchemaInclude); else size = sizeof(xmlSchemaImport); ret = (xmlSchemaBucketPtr) xmlMalloc(size); if (ret == NULL) { xmlSchemaPErrMemory(NULL, "allocating schema bucket", NULL); return(NULL); } memset(ret, 0, size); ret->targetNamespace = targetNamespace; ret->type = type; ret->globals = xmlSchemaItemListCreate(); if (ret->globals == NULL) { xmlFree(ret); return(NULL); } ret->locals = xmlSchemaItemListCreate(); if (ret->locals == NULL) { xmlFree(ret); return(NULL); } /* * The following will assure that only the first bucket is marked as * XML_SCHEMA_SCHEMA_MAIN and it points to the *main* schema. * For each following import buckets an xmlSchema will be created. * An xmlSchema will be created for every distinct targetNamespace. * We assign the targetNamespace to the schemata here. */ if (! WXS_HAS_BUCKETS(pctxt)) { if (WXS_IS_BUCKET_INCREDEF(type)) { PERROR_INT("xmlSchemaBucketCreate", "first bucket but it's an include or redefine"); xmlSchemaBucketFree(ret); return(NULL); } /* Force the type to be XML_SCHEMA_SCHEMA_MAIN. */ ret->type = XML_SCHEMA_SCHEMA_MAIN; /* Point to the *main* schema. */ WXS_CONSTRUCTOR(pctxt)->mainBucket = ret; WXS_IMPBUCKET(ret)->schema = mainSchema; /* * Ensure that the main schema gets a targetNamespace. */ mainSchema->targetNamespace = targetNamespace; } else { if (type == XML_SCHEMA_SCHEMA_MAIN) { PERROR_INT("xmlSchemaBucketCreate", "main bucket but it's not the first one"); xmlSchemaBucketFree(ret); return(NULL); } else if (type == XML_SCHEMA_SCHEMA_IMPORT) { /* * Create a schema for imports and assign the * targetNamespace. */ WXS_IMPBUCKET(ret)->schema = xmlSchemaNewSchema(pctxt); if (WXS_IMPBUCKET(ret)->schema == NULL) { xmlSchemaBucketFree(ret); return(NULL); } WXS_IMPBUCKET(ret)->schema->targetNamespace = targetNamespace; } } if (WXS_IS_BUCKET_IMPMAIN(type)) { int res; /* * Imports go into the "schemasImports" slot of the main *schema*. * Note that we create an import entry for the main schema as well; i.e., * even if there's only one schema, we'll get an import. */ if (mainSchema->schemasImports == NULL) { mainSchema->schemasImports = xmlHashCreateDict(5, WXS_CONSTRUCTOR(pctxt)->dict); if (mainSchema->schemasImports == NULL) { xmlSchemaBucketFree(ret); return(NULL); } } if (targetNamespace == NULL) res = xmlHashAddEntry(mainSchema->schemasImports, XML_SCHEMAS_NO_NAMESPACE, ret); else res = xmlHashAddEntry(mainSchema->schemasImports, targetNamespace, ret); if (res != 0) { PERROR_INT("xmlSchemaBucketCreate", "failed to add the schema bucket to the hash"); xmlSchemaBucketFree(ret); return(NULL); } } else { /* Set the @ownerImport of an include bucket. */ if (WXS_IS_BUCKET_IMPMAIN(WXS_CONSTRUCTOR(pctxt)->bucket->type)) WXS_INCBUCKET(ret)->ownerImport = WXS_IMPBUCKET(WXS_CONSTRUCTOR(pctxt)->bucket); else WXS_INCBUCKET(ret)->ownerImport = WXS_INCBUCKET(WXS_CONSTRUCTOR(pctxt)->bucket)->ownerImport; /* Includes got into the "includes" slot of the *main* schema. */ if (mainSchema->includes == NULL) { mainSchema->includes = xmlSchemaItemListCreate(); if (mainSchema->includes == NULL) { xmlSchemaBucketFree(ret); return(NULL); } } xmlSchemaItemListAdd(mainSchema->includes, ret); } /* * Add to list of all buckets; this is used for lookup * during schema construction time only. */ if (xmlSchemaItemListAdd(WXS_CONSTRUCTOR(pctxt)->buckets, ret) == -1) return(NULL); return(ret); } static int xmlSchemaAddItemSize(xmlSchemaItemListPtr *list, int initialSize, void *item) { if (*list == NULL) { *list = xmlSchemaItemListCreate(); if (*list == NULL) return(-1); } xmlSchemaItemListAddSize(*list, initialSize, item); return(0); } /** * xmlSchemaFreeAnnot: * @annot: a schema type structure * * Deallocate a annotation structure */ static void xmlSchemaFreeAnnot(xmlSchemaAnnotPtr annot) { if (annot == NULL) return; if (annot->next == NULL) { xmlFree(annot); } else { xmlSchemaAnnotPtr prev; do { prev = annot; annot = annot->next; xmlFree(prev); } while (annot != NULL); } } /** * xmlSchemaFreeNotation: * @schema: a schema notation structure * * Deallocate a Schema Notation structure. */ static void xmlSchemaFreeNotation(xmlSchemaNotationPtr nota) { if (nota == NULL) return; xmlFree(nota); } /** * xmlSchemaFreeAttribute: * @attr: an attribute declaration * * Deallocates an attribute declaration structure. */ static void xmlSchemaFreeAttribute(xmlSchemaAttributePtr attr) { if (attr == NULL) return; if (attr->annot != NULL) xmlSchemaFreeAnnot(attr->annot); if (attr->defVal != NULL) xmlSchemaFreeValue(attr->defVal); xmlFree(attr); } /** * xmlSchemaFreeAttributeUse: * @use: an attribute use * * Deallocates an attribute use structure. */ static void xmlSchemaFreeAttributeUse(xmlSchemaAttributeUsePtr use) { if (use == NULL) return; if (use->annot != NULL) xmlSchemaFreeAnnot(use->annot); if (use->defVal != NULL) xmlSchemaFreeValue(use->defVal); xmlFree(use); } /** * xmlSchemaFreeAttributeUseProhib: * @prohib: an attribute use prohibition * * Deallocates an attribute use structure. */ static void xmlSchemaFreeAttributeUseProhib(xmlSchemaAttributeUseProhibPtr prohib) { if (prohib == NULL) return; xmlFree(prohib); } /** * xmlSchemaFreeWildcardNsSet: * set: a schema wildcard namespace * * Deallocates a list of wildcard constraint structures. */ static void xmlSchemaFreeWildcardNsSet(xmlSchemaWildcardNsPtr set) { xmlSchemaWildcardNsPtr next; while (set != NULL) { next = set->next; xmlFree(set); set = next; } } /** * xmlSchemaFreeWildcard: * @wildcard: a wildcard structure * * Deallocates a wildcard structure. */ void xmlSchemaFreeWildcard(xmlSchemaWildcardPtr wildcard) { if (wildcard == NULL) return; if (wildcard->annot != NULL) xmlSchemaFreeAnnot(wildcard->annot); if (wildcard->nsSet != NULL) xmlSchemaFreeWildcardNsSet(wildcard->nsSet); if (wildcard->negNsSet != NULL) xmlFree(wildcard->negNsSet); xmlFree(wildcard); } /** * xmlSchemaFreeAttributeGroup: * @schema: a schema attribute group structure * * Deallocate a Schema Attribute Group structure. */ static void xmlSchemaFreeAttributeGroup(xmlSchemaAttributeGroupPtr attrGr) { if (attrGr == NULL) return; if (attrGr->annot != NULL) xmlSchemaFreeAnnot(attrGr->annot); if (attrGr->attrUses != NULL) xmlSchemaItemListFree(WXS_LIST_CAST attrGr->attrUses); xmlFree(attrGr); } /** * xmlSchemaFreeQNameRef: * @item: a QName reference structure * * Deallocatea a QName reference structure. */ static void xmlSchemaFreeQNameRef(xmlSchemaQNameRefPtr item) { xmlFree(item); } /** * xmlSchemaFreeTypeLinkList: * @alink: a type link * * Deallocate a list of types. */ static void xmlSchemaFreeTypeLinkList(xmlSchemaTypeLinkPtr link) { xmlSchemaTypeLinkPtr next; while (link != NULL) { next = link->next; xmlFree(link); link = next; } } static void xmlSchemaFreeIDCStateObjList(xmlSchemaIDCStateObjPtr sto) { xmlSchemaIDCStateObjPtr next; while (sto != NULL) { next = sto->next; if (sto->history != NULL) xmlFree(sto->history); if (sto->xpathCtxt != NULL) xmlFreeStreamCtxt((xmlStreamCtxtPtr) sto->xpathCtxt); xmlFree(sto); sto = next; } } /** * xmlSchemaFreeIDC: * @idc: a identity-constraint definition * * Deallocates an identity-constraint definition. */ static void xmlSchemaFreeIDC(xmlSchemaIDCPtr idcDef) { xmlSchemaIDCSelectPtr cur, prev; if (idcDef == NULL) return; if (idcDef->annot != NULL) xmlSchemaFreeAnnot(idcDef->annot); /* Selector */ if (idcDef->selector != NULL) { if (idcDef->selector->xpathComp != NULL) xmlFreePattern((xmlPatternPtr) idcDef->selector->xpathComp); xmlFree(idcDef->selector); } /* Fields */ if (idcDef->fields != NULL) { cur = idcDef->fields; do { prev = cur; cur = cur->next; if (prev->xpathComp != NULL) xmlFreePattern((xmlPatternPtr) prev->xpathComp); xmlFree(prev); } while (cur != NULL); } xmlFree(idcDef); } /** * xmlSchemaFreeElement: * @schema: a schema element structure * * Deallocate a Schema Element structure. */ static void xmlSchemaFreeElement(xmlSchemaElementPtr elem) { if (elem == NULL) return; if (elem->annot != NULL) xmlSchemaFreeAnnot(elem->annot); if (elem->contModel != NULL) xmlRegFreeRegexp(elem->contModel); if (elem->defVal != NULL) xmlSchemaFreeValue(elem->defVal); xmlFree(elem); } /** * xmlSchemaFreeFacet: * @facet: a schema facet structure * * Deallocate a Schema Facet structure. */ void xmlSchemaFreeFacet(xmlSchemaFacetPtr facet) { if (facet == NULL) return; if (facet->val != NULL) xmlSchemaFreeValue(facet->val); if (facet->regexp != NULL) xmlRegFreeRegexp(facet->regexp); if (facet->annot != NULL) xmlSchemaFreeAnnot(facet->annot); xmlFree(facet); } /** * xmlSchemaFreeType: * @type: a schema type structure * * Deallocate a Schema Type structure. */ void xmlSchemaFreeType(xmlSchemaTypePtr type) { if (type == NULL) return; if (type->annot != NULL) xmlSchemaFreeAnnot(type->annot); if (type->facets != NULL) { xmlSchemaFacetPtr facet, next; facet = type->facets; while (facet != NULL) { next = facet->next; xmlSchemaFreeFacet(facet); facet = next; } } if (type->attrUses != NULL) xmlSchemaItemListFree((xmlSchemaItemListPtr) type->attrUses); if (type->memberTypes != NULL) xmlSchemaFreeTypeLinkList(type->memberTypes); if (type->facetSet != NULL) { xmlSchemaFacetLinkPtr next, link; link = type->facetSet; do { next = link->next; xmlFree(link); link = next; } while (link != NULL); } if (type->contModel != NULL) xmlRegFreeRegexp(type->contModel); xmlFree(type); } /** * xmlSchemaFreeModelGroupDef: * @item: a schema model group definition * * Deallocates a schema model group definition. */ static void xmlSchemaFreeModelGroupDef(xmlSchemaModelGroupDefPtr item) { if (item->annot != NULL) xmlSchemaFreeAnnot(item->annot); xmlFree(item); } /** * xmlSchemaFreeModelGroup: * @item: a schema model group * * Deallocates a schema model group structure. */ static void xmlSchemaFreeModelGroup(xmlSchemaModelGroupPtr item) { if (item->annot != NULL) xmlSchemaFreeAnnot(item->annot); xmlFree(item); } static void xmlSchemaComponentListFree(xmlSchemaItemListPtr list) { if ((list == NULL) || (list->nbItems == 0)) return; { xmlSchemaTreeItemPtr item; xmlSchemaTreeItemPtr *items = (xmlSchemaTreeItemPtr *) list->items; int i; for (i = 0; i < list->nbItems; i++) { item = items[i]; if (item == NULL) continue; switch (item->type) { case XML_SCHEMA_TYPE_SIMPLE: case XML_SCHEMA_TYPE_COMPLEX: xmlSchemaFreeType((xmlSchemaTypePtr) item); break; case XML_SCHEMA_TYPE_ATTRIBUTE: xmlSchemaFreeAttribute((xmlSchemaAttributePtr) item); break; case XML_SCHEMA_TYPE_ATTRIBUTE_USE: xmlSchemaFreeAttributeUse((xmlSchemaAttributeUsePtr) item); break; case XML_SCHEMA_EXTRA_ATTR_USE_PROHIB: xmlSchemaFreeAttributeUseProhib( (xmlSchemaAttributeUseProhibPtr) item); break; case XML_SCHEMA_TYPE_ELEMENT: xmlSchemaFreeElement((xmlSchemaElementPtr) item); break; case XML_SCHEMA_TYPE_PARTICLE: if (item->annot != NULL) xmlSchemaFreeAnnot(item->annot); xmlFree(item); break; case XML_SCHEMA_TYPE_SEQUENCE: case XML_SCHEMA_TYPE_CHOICE: case XML_SCHEMA_TYPE_ALL: xmlSchemaFreeModelGroup((xmlSchemaModelGroupPtr) item); break; case XML_SCHEMA_TYPE_ATTRIBUTEGROUP: xmlSchemaFreeAttributeGroup( (xmlSchemaAttributeGroupPtr) item); break; case XML_SCHEMA_TYPE_GROUP: xmlSchemaFreeModelGroupDef( (xmlSchemaModelGroupDefPtr) item); break; case XML_SCHEMA_TYPE_ANY: case XML_SCHEMA_TYPE_ANY_ATTRIBUTE: xmlSchemaFreeWildcard((xmlSchemaWildcardPtr) item); break; case XML_SCHEMA_TYPE_IDC_KEY: case XML_SCHEMA_TYPE_IDC_UNIQUE: case XML_SCHEMA_TYPE_IDC_KEYREF: xmlSchemaFreeIDC((xmlSchemaIDCPtr) item); break; case XML_SCHEMA_TYPE_NOTATION: xmlSchemaFreeNotation((xmlSchemaNotationPtr) item); break; case XML_SCHEMA_EXTRA_QNAMEREF: xmlSchemaFreeQNameRef((xmlSchemaQNameRefPtr) item); break; default: { /* TODO: This should never be hit. */ xmlSchemaPSimpleInternalErr(NULL, "Internal error: xmlSchemaComponentListFree, " "unexpected component type '%s'\n", (const xmlChar *) WXS_ITEM_TYPE_NAME(item)); } break; } } list->nbItems = 0; } } /** * xmlSchemaFree: * @schema: a schema structure * * Deallocate a Schema structure. */ void xmlSchemaFree(xmlSchemaPtr schema) { if (schema == NULL) return; /* @volatiles is not used anymore :-/ */ if (schema->volatiles != NULL) TODO /* * Note that those slots are not responsible for freeing * schema components anymore; this will now be done by * the schema buckets. */ if (schema->notaDecl != NULL) xmlHashFree(schema->notaDecl, NULL); if (schema->attrDecl != NULL) xmlHashFree(schema->attrDecl, NULL); if (schema->attrgrpDecl != NULL) xmlHashFree(schema->attrgrpDecl, NULL); if (schema->elemDecl != NULL) xmlHashFree(schema->elemDecl, NULL); if (schema->typeDecl != NULL) xmlHashFree(schema->typeDecl, NULL); if (schema->groupDecl != NULL) xmlHashFree(schema->groupDecl, NULL); if (schema->idcDef != NULL) xmlHashFree(schema->idcDef, NULL); if (schema->schemasImports != NULL) xmlHashFree(schema->schemasImports, xmlSchemaBucketFreeEntry); if (schema->includes != NULL) { xmlSchemaItemListPtr list = (xmlSchemaItemListPtr) schema->includes; int i; for (i = 0; i < list->nbItems; i++) { xmlSchemaBucketFree((xmlSchemaBucketPtr) list->items[i]); } xmlSchemaItemListFree(list); } if (schema->annot != NULL) xmlSchemaFreeAnnot(schema->annot); /* Never free the doc here, since this will be done by the buckets. */ xmlDictFree(schema->dict); xmlFree(schema); } /************************************************************************ * * * Debug functions * * * ************************************************************************/ #ifdef LIBXML_OUTPUT_ENABLED static void xmlSchemaTypeDump(xmlSchemaTypePtr type, FILE * output); /* forward */ /** * xmlSchemaElementDump: * @elem: an element * @output: the file output * * Dump the element */ static void xmlSchemaElementDump(void *payload, void *data, const xmlChar * name ATTRIBUTE_UNUSED, const xmlChar * namespace ATTRIBUTE_UNUSED, const xmlChar * context ATTRIBUTE_UNUSED) { xmlSchemaElementPtr elem = (xmlSchemaElementPtr) payload; FILE *output = (FILE *) data; if (elem == NULL) return; fprintf(output, "Element"); if (elem->flags & XML_SCHEMAS_ELEM_GLOBAL) fprintf(output, " (global)"); fprintf(output, ": '%s' ", elem->name); if (namespace != NULL) fprintf(output, "ns '%s'", namespace); fprintf(output, "\n"); #if 0 if ((elem->minOccurs != 1) || (elem->maxOccurs != 1)) { fprintf(output, " min %d ", elem->minOccurs); if (elem->maxOccurs >= UNBOUNDED) fprintf(output, "max: unbounded\n"); else if (elem->maxOccurs != 1) fprintf(output, "max: %d\n", elem->maxOccurs); else fprintf(output, "\n"); } #endif /* * Misc other properties. */ if ((elem->flags & XML_SCHEMAS_ELEM_NILLABLE) || (elem->flags & XML_SCHEMAS_ELEM_ABSTRACT) || (elem->flags & XML_SCHEMAS_ELEM_FIXED) || (elem->flags & XML_SCHEMAS_ELEM_DEFAULT)) { fprintf(output, " props: "); if (elem->flags & XML_SCHEMAS_ELEM_FIXED) fprintf(output, "[fixed] "); if (elem->flags & XML_SCHEMAS_ELEM_DEFAULT) fprintf(output, "[default] "); if (elem->flags & XML_SCHEMAS_ELEM_ABSTRACT) fprintf(output, "[abstract] "); if (elem->flags & XML_SCHEMAS_ELEM_NILLABLE) fprintf(output, "[nillable] "); fprintf(output, "\n"); } /* * Default/fixed value. */ if (elem->value != NULL) fprintf(output, " value: '%s'\n", elem->value); /* * Type. */ if (elem->namedType != NULL) { fprintf(output, " type: '%s' ", elem->namedType); if (elem->namedTypeNs != NULL) fprintf(output, "ns '%s'\n", elem->namedTypeNs); else fprintf(output, "\n"); } else if (elem->subtypes != NULL) { /* * Dump local types. */ xmlSchemaTypeDump(elem->subtypes, output); } /* * Substitution group. */ if (elem->substGroup != NULL) { fprintf(output, " substitutionGroup: '%s' ", elem->substGroup); if (elem->substGroupNs != NULL) fprintf(output, "ns '%s'\n", elem->substGroupNs); else fprintf(output, "\n"); } } /** * xmlSchemaAnnotDump: * @output: the file output * @annot: a annotation * * Dump the annotation */ static void xmlSchemaAnnotDump(FILE * output, xmlSchemaAnnotPtr annot) { xmlChar *content; if (annot == NULL) return; content = xmlNodeGetContent(annot->content); if (content != NULL) { fprintf(output, " Annot: %s\n", content); xmlFree(content); } else fprintf(output, " Annot: empty\n"); } /** * xmlSchemaContentModelDump: * @particle: the schema particle * @output: the file output * @depth: the depth used for indentation * * Dump a SchemaType structure */ static void xmlSchemaContentModelDump(xmlSchemaParticlePtr particle, FILE * output, int depth) { xmlChar *str = NULL; xmlSchemaTreeItemPtr term; char shift[100]; int i; if (particle == NULL) return; for (i = 0;((i < depth) && (i < 25));i++) shift[2 * i] = shift[2 * i + 1] = ' '; shift[2 * i] = shift[2 * i + 1] = 0; fprintf(output, "%s", shift); if (particle->children == NULL) { fprintf(output, "MISSING particle term\n"); return; } term = particle->children; if (term == NULL) { fprintf(output, "(NULL)"); } else { switch (term->type) { case XML_SCHEMA_TYPE_ELEMENT: fprintf(output, "ELEM '%s'", xmlSchemaFormatQName(&str, ((xmlSchemaElementPtr)term)->targetNamespace, ((xmlSchemaElementPtr)term)->name)); FREE_AND_NULL(str); break; case XML_SCHEMA_TYPE_SEQUENCE: fprintf(output, "SEQUENCE"); break; case XML_SCHEMA_TYPE_CHOICE: fprintf(output, "CHOICE"); break; case XML_SCHEMA_TYPE_ALL: fprintf(output, "ALL"); break; case XML_SCHEMA_TYPE_ANY: fprintf(output, "ANY"); break; default: fprintf(output, "UNKNOWN\n"); return; } } if (particle->minOccurs != 1) fprintf(output, " min: %d", particle->minOccurs); if (particle->maxOccurs >= UNBOUNDED) fprintf(output, " max: unbounded"); else if (particle->maxOccurs != 1) fprintf(output, " max: %d", particle->maxOccurs); fprintf(output, "\n"); if (term && ((term->type == XML_SCHEMA_TYPE_SEQUENCE) || (term->type == XML_SCHEMA_TYPE_CHOICE) || (term->type == XML_SCHEMA_TYPE_ALL)) && (term->children != NULL)) { xmlSchemaContentModelDump((xmlSchemaParticlePtr) term->children, output, depth +1); } if (particle->next != NULL) xmlSchemaContentModelDump((xmlSchemaParticlePtr) particle->next, output, depth); } /** * xmlSchemaAttrUsesDump: * @uses: attribute uses list * @output: the file output * * Dumps a list of attribute use components. */ static void xmlSchemaAttrUsesDump(xmlSchemaItemListPtr uses, FILE * output) { xmlSchemaAttributeUsePtr use; xmlSchemaAttributeUseProhibPtr prohib; xmlSchemaQNameRefPtr ref; const xmlChar *name, *tns; xmlChar *str = NULL; int i; if ((uses == NULL) || (uses->nbItems == 0)) return; fprintf(output, " attributes:\n"); for (i = 0; i < uses->nbItems; i++) { use = uses->items[i]; if (use->type == XML_SCHEMA_EXTRA_ATTR_USE_PROHIB) { fprintf(output, " [prohibition] "); prohib = (xmlSchemaAttributeUseProhibPtr) use; name = prohib->name; tns = prohib->targetNamespace; } else if (use->type == XML_SCHEMA_EXTRA_QNAMEREF) { fprintf(output, " [reference] "); ref = (xmlSchemaQNameRefPtr) use; name = ref->name; tns = ref->targetNamespace; } else { fprintf(output, " [use] "); name = WXS_ATTRUSE_DECL_NAME(use); tns = WXS_ATTRUSE_DECL_TNS(use); } fprintf(output, "'%s'\n", (const char *) xmlSchemaFormatQName(&str, tns, name)); FREE_AND_NULL(str); } } /** * xmlSchemaTypeDump: * @output: the file output * @type: a type structure * * Dump a SchemaType structure */ static void xmlSchemaTypeDump(xmlSchemaTypePtr type, FILE * output) { if (type == NULL) { fprintf(output, "Type: NULL\n"); return; } fprintf(output, "Type: "); if (type->name != NULL) fprintf(output, "'%s' ", type->name); else fprintf(output, "(no name) "); if (type->targetNamespace != NULL) fprintf(output, "ns '%s' ", type->targetNamespace); switch (type->type) { case XML_SCHEMA_TYPE_BASIC: fprintf(output, "[basic] "); break; case XML_SCHEMA_TYPE_SIMPLE: fprintf(output, "[simple] "); break; case XML_SCHEMA_TYPE_COMPLEX: fprintf(output, "[complex] "); break; case XML_SCHEMA_TYPE_SEQUENCE: fprintf(output, "[sequence] "); break; case XML_SCHEMA_TYPE_CHOICE: fprintf(output, "[choice] "); break; case XML_SCHEMA_TYPE_ALL: fprintf(output, "[all] "); break; case XML_SCHEMA_TYPE_UR: fprintf(output, "[ur] "); break; case XML_SCHEMA_TYPE_RESTRICTION: fprintf(output, "[restriction] "); break; case XML_SCHEMA_TYPE_EXTENSION: fprintf(output, "[extension] "); break; default: fprintf(output, "[unknown type %d] ", type->type); break; } fprintf(output, "content: "); switch (type->contentType) { case XML_SCHEMA_CONTENT_UNKNOWN: fprintf(output, "[unknown] "); break; case XML_SCHEMA_CONTENT_EMPTY: fprintf(output, "[empty] "); break; case XML_SCHEMA_CONTENT_ELEMENTS: fprintf(output, "[element] "); break; case XML_SCHEMA_CONTENT_MIXED: fprintf(output, "[mixed] "); break; case XML_SCHEMA_CONTENT_MIXED_OR_ELEMENTS: /* not used. */ break; case XML_SCHEMA_CONTENT_BASIC: fprintf(output, "[basic] "); break; case XML_SCHEMA_CONTENT_SIMPLE: fprintf(output, "[simple] "); break; case XML_SCHEMA_CONTENT_ANY: fprintf(output, "[any] "); break; } fprintf(output, "\n"); if (type->base != NULL) { fprintf(output, " base type: '%s'", type->base); if (type->baseNs != NULL) fprintf(output, " ns '%s'\n", type->baseNs); else fprintf(output, "\n"); } if (type->attrUses != NULL) xmlSchemaAttrUsesDump(type->attrUses, output); if (type->annot != NULL) xmlSchemaAnnotDump(output, type->annot); #ifdef DUMP_CONTENT_MODEL if ((type->type == XML_SCHEMA_TYPE_COMPLEX) && (type->subtypes != NULL)) { xmlSchemaContentModelDump((xmlSchemaParticlePtr) type->subtypes, output, 1); } #endif } static void xmlSchemaTypeDumpEntry(void *type, void *output, const xmlChar *name ATTRIBUTE_UNUSED) { xmlSchemaTypeDump((xmlSchemaTypePtr) type, (FILE *) output); } /** * xmlSchemaDump: * @output: the file output * @schema: a schema structure * * Dump a Schema structure. */ void xmlSchemaDump(FILE * output, xmlSchemaPtr schema) { if (output == NULL) return; if (schema == NULL) { fprintf(output, "Schemas: NULL\n"); return; } fprintf(output, "Schemas: "); if (schema->name != NULL) fprintf(output, "%s, ", schema->name); else fprintf(output, "no name, "); if (schema->targetNamespace != NULL) fprintf(output, "%s", (const char *) schema->targetNamespace); else fprintf(output, "no target namespace"); fprintf(output, "\n"); if (schema->annot != NULL) xmlSchemaAnnotDump(output, schema->annot); xmlHashScan(schema->typeDecl, xmlSchemaTypeDumpEntry, output); xmlHashScanFull(schema->elemDecl, xmlSchemaElementDump, output); } #ifdef DEBUG_IDC_NODE_TABLE /** * xmlSchemaDebugDumpIDCTable: * @vctxt: the WXS validation context * * Displays the current IDC table for debug purposes. */ static void xmlSchemaDebugDumpIDCTable(FILE * output, const xmlChar *namespaceName, const xmlChar *localName, xmlSchemaPSVIIDCBindingPtr bind) { xmlChar *str = NULL; const xmlChar *value; xmlSchemaPSVIIDCNodePtr tab; xmlSchemaPSVIIDCKeyPtr key; int i, j, res; fprintf(output, "IDC: TABLES on '%s'\n", xmlSchemaFormatQName(&str, namespaceName, localName)); FREE_AND_NULL(str) if (bind == NULL) return; do { fprintf(output, "IDC: BINDING '%s' (%d)\n", xmlSchemaGetComponentQName(&str, bind->definition), bind->nbNodes); FREE_AND_NULL(str) for (i = 0; i < bind->nbNodes; i++) { tab = bind->nodeTable[i]; fprintf(output, " ( "); for (j = 0; j < bind->definition->nbFields; j++) { key = tab->keys[j]; if ((key != NULL) && (key->val != NULL)) { res = xmlSchemaGetCanonValue(key->val, &value); if (res >= 0) fprintf(output, "'%s' ", value); else fprintf(output, "CANON-VALUE-FAILED "); if (res == 0) FREE_AND_NULL(value) } else if (key != NULL) fprintf(output, "(no val), "); else fprintf(output, "(key missing), "); } fprintf(output, ")\n"); } if (bind->dupls && bind->dupls->nbItems) { fprintf(output, "IDC: dupls (%d):\n", bind->dupls->nbItems); for (i = 0; i < bind->dupls->nbItems; i++) { tab = bind->dupls->items[i]; fprintf(output, " ( "); for (j = 0; j < bind->definition->nbFields; j++) { key = tab->keys[j]; if ((key != NULL) && (key->val != NULL)) { res = xmlSchemaGetCanonValue(key->val, &value); if (res >= 0) fprintf(output, "'%s' ", value); else fprintf(output, "CANON-VALUE-FAILED "); if (res == 0) FREE_AND_NULL(value) } else if (key != NULL) fprintf(output, "(no val), "); else fprintf(output, "(key missing), "); } fprintf(output, ")\n"); } } bind = bind->next; } while (bind != NULL); } #endif /* DEBUG_IDC */ #endif /* LIBXML_OUTPUT_ENABLED */ /************************************************************************ * * * Utilities * * * ************************************************************************/ /** * xmlSchemaGetPropNode: * @node: the element node * @name: the name of the attribute * * Seeks an attribute with a name of @name in * no namespace. * * Returns the attribute or NULL if not present. */ static xmlAttrPtr xmlSchemaGetPropNode(xmlNodePtr node, const char *name) { xmlAttrPtr prop; if ((node == NULL) || (name == NULL)) return(NULL); prop = node->properties; while (prop != NULL) { if ((prop->ns == NULL) && xmlStrEqual(prop->name, BAD_CAST name)) return(prop); prop = prop->next; } return (NULL); } /** * xmlSchemaGetPropNodeNs: * @node: the element node * @uri: the uri * @name: the name of the attribute * * Seeks an attribute with a local name of @name and * a namespace URI of @uri. * * Returns the attribute or NULL if not present. */ static xmlAttrPtr xmlSchemaGetPropNodeNs(xmlNodePtr node, const char *uri, const char *name) { xmlAttrPtr prop; if ((node == NULL) || (name == NULL)) return(NULL); prop = node->properties; while (prop != NULL) { if ((prop->ns != NULL) && xmlStrEqual(prop->name, BAD_CAST name) && xmlStrEqual(prop->ns->href, BAD_CAST uri)) return(prop); prop = prop->next; } return (NULL); } static const xmlChar * xmlSchemaGetNodeContent(xmlSchemaParserCtxtPtr ctxt, xmlNodePtr node) { xmlChar *val; const xmlChar *ret; val = xmlNodeGetContent(node); if (val == NULL) val = xmlStrdup((xmlChar *)""); ret = xmlDictLookup(ctxt->dict, val, -1); xmlFree(val); return(ret); } static const xmlChar * xmlSchemaGetNodeContentNoDict(xmlNodePtr node) { return((const xmlChar*) xmlNodeGetContent(node)); } /** * xmlSchemaGetProp: * @ctxt: the parser context * @node: the node * @name: the property name * * Read a attribute value and internalize the string * * Returns the string or NULL if not present. */ static const xmlChar * xmlSchemaGetProp(xmlSchemaParserCtxtPtr ctxt, xmlNodePtr node, const char *name) { xmlChar *val; const xmlChar *ret; val = xmlGetNoNsProp(node, BAD_CAST name); if (val == NULL) return(NULL); ret = xmlDictLookup(ctxt->dict, val, -1); xmlFree(val); return(ret); } /************************************************************************ * * * Parsing functions * * * ************************************************************************/ #define WXS_FIND_GLOBAL_ITEM(slot) \ if (xmlStrEqual(nsName, schema->targetNamespace)) { \ ret = xmlHashLookup(schema->slot, name); \ if (ret != NULL) goto exit; \ } \ if (xmlHashSize(schema->schemasImports) > 1) { \ xmlSchemaImportPtr import; \ if (nsName == NULL) \ import = xmlHashLookup(schema->schemasImports, \ XML_SCHEMAS_NO_NAMESPACE); \ else \ import = xmlHashLookup(schema->schemasImports, nsName); \ if (import == NULL) \ goto exit; \ ret = xmlHashLookup(import->schema->slot, name); \ } /** * xmlSchemaGetElem: * @schema: the schema context * @name: the element name * @ns: the element namespace * * Lookup a global element declaration in the schema. * * Returns the element declaration or NULL if not found. */ static xmlSchemaElementPtr xmlSchemaGetElem(xmlSchemaPtr schema, const xmlChar * name, const xmlChar * nsName) { xmlSchemaElementPtr ret = NULL; if ((name == NULL) || (schema == NULL)) return(NULL); if (schema != NULL) { WXS_FIND_GLOBAL_ITEM(elemDecl) } exit: #ifdef DEBUG if (ret == NULL) { if (nsName == NULL) fprintf(stderr, "Unable to lookup element decl. %s", name); else fprintf(stderr, "Unable to lookup element decl. %s:%s", name, nsName); } #endif return (ret); } /** * xmlSchemaGetType: * @schema: the main schema * @name: the type's name * nsName: the type's namespace * * Lookup a type in the schemas or the predefined types * * Returns the group definition or NULL if not found. */ static xmlSchemaTypePtr xmlSchemaGetType(xmlSchemaPtr schema, const xmlChar * name, const xmlChar * nsName) { xmlSchemaTypePtr ret = NULL; if (name == NULL) return (NULL); /* First try the built-in types. */ if ((nsName != NULL) && xmlStrEqual(nsName, xmlSchemaNs)) { ret = xmlSchemaGetPredefinedType(name, nsName); if (ret != NULL) goto exit; /* * Note that we try the parsed schemas as well here * since one might have parsed the S4S, which contain more * than the built-in types. * TODO: Can we optimize this? */ } if (schema != NULL) { WXS_FIND_GLOBAL_ITEM(typeDecl) } exit: #ifdef DEBUG if (ret == NULL) { if (nsName == NULL) fprintf(stderr, "Unable to lookup type %s", name); else fprintf(stderr, "Unable to lookup type %s:%s", name, nsName); } #endif return (ret); } /** * xmlSchemaGetAttributeDecl: * @schema: the context of the schema * @name: the name of the attribute * @ns: the target namespace of the attribute * * Lookup a an attribute in the schema or imported schemas * * Returns the attribute declaration or NULL if not found. */ static xmlSchemaAttributePtr xmlSchemaGetAttributeDecl(xmlSchemaPtr schema, const xmlChar * name, const xmlChar * nsName) { xmlSchemaAttributePtr ret = NULL; if ((name == NULL) || (schema == NULL)) return (NULL); if (schema != NULL) { WXS_FIND_GLOBAL_ITEM(attrDecl) } exit: #ifdef DEBUG if (ret == NULL) { if (nsName == NULL) fprintf(stderr, "Unable to lookup attribute %s", name); else fprintf(stderr, "Unable to lookup attribute %s:%s", name, nsName); } #endif return (ret); } /** * xmlSchemaGetAttributeGroup: * @schema: the context of the schema * @name: the name of the attribute group * @ns: the target namespace of the attribute group * * Lookup a an attribute group in the schema or imported schemas * * Returns the attribute group definition or NULL if not found. */ static xmlSchemaAttributeGroupPtr xmlSchemaGetAttributeGroup(xmlSchemaPtr schema, const xmlChar * name, const xmlChar * nsName) { xmlSchemaAttributeGroupPtr ret = NULL; if ((name == NULL) || (schema == NULL)) return (NULL); if (schema != NULL) { WXS_FIND_GLOBAL_ITEM(attrgrpDecl) } exit: /* TODO: if ((ret != NULL) && (ret->redef != NULL)) { * Return the last redefinition. * ret = ret->redef; } */ #ifdef DEBUG if (ret == NULL) { if (nsName == NULL) fprintf(stderr, "Unable to lookup attribute group %s", name); else fprintf(stderr, "Unable to lookup attribute group %s:%s", name, nsName); } #endif return (ret); } /** * xmlSchemaGetGroup: * @schema: the context of the schema * @name: the name of the group * @ns: the target namespace of the group * * Lookup a group in the schema or imported schemas * * Returns the group definition or NULL if not found. */ static xmlSchemaModelGroupDefPtr xmlSchemaGetGroup(xmlSchemaPtr schema, const xmlChar * name, const xmlChar * nsName) { xmlSchemaModelGroupDefPtr ret = NULL; if ((name == NULL) || (schema == NULL)) return (NULL); if (schema != NULL) { WXS_FIND_GLOBAL_ITEM(groupDecl) } exit: #ifdef DEBUG if (ret == NULL) { if (nsName == NULL) fprintf(stderr, "Unable to lookup group %s", name); else fprintf(stderr, "Unable to lookup group %s:%s", name, nsName); } #endif return (ret); } static xmlSchemaNotationPtr xmlSchemaGetNotation(xmlSchemaPtr schema, const xmlChar *name, const xmlChar *nsName) { xmlSchemaNotationPtr ret = NULL; if ((name == NULL) || (schema == NULL)) return (NULL); if (schema != NULL) { WXS_FIND_GLOBAL_ITEM(notaDecl) } exit: return (ret); } static xmlSchemaIDCPtr xmlSchemaGetIDC(xmlSchemaPtr schema, const xmlChar *name, const xmlChar *nsName) { xmlSchemaIDCPtr ret = NULL; if ((name == NULL) || (schema == NULL)) return (NULL); if (schema != NULL) { WXS_FIND_GLOBAL_ITEM(idcDef) } exit: return (ret); } /** * xmlSchemaGetNamedComponent: * @schema: the schema * @name: the name of the group * @ns: the target namespace of the group * * Lookup a group in the schema or imported schemas * * Returns the group definition or NULL if not found. */ static xmlSchemaBasicItemPtr xmlSchemaGetNamedComponent(xmlSchemaPtr schema, xmlSchemaTypeType itemType, const xmlChar *name, const xmlChar *targetNs) { switch (itemType) { case XML_SCHEMA_TYPE_GROUP: return ((xmlSchemaBasicItemPtr) xmlSchemaGetGroup(schema, name, targetNs)); case XML_SCHEMA_TYPE_ELEMENT: return ((xmlSchemaBasicItemPtr) xmlSchemaGetElem(schema, name, targetNs)); default: TODO return (NULL); } } /************************************************************************ * * * Parsing functions * * * ************************************************************************/ #define IS_BLANK_NODE(n) \ (((n)->type == XML_TEXT_NODE) && (xmlSchemaIsBlank((n)->content, -1))) /** * xmlSchemaIsBlank: * @str: a string * @len: the length of the string or -1 * * Check if a string is ignorable * * Returns 1 if the string is NULL or made of blanks chars, 0 otherwise */ static int xmlSchemaIsBlank(xmlChar * str, int len) { if (str == NULL) return (1); if (len < 0) { while (*str != 0) { if (!(IS_BLANK_CH(*str))) return (0); str++; } } else while ((*str != 0) && (len != 0)) { if (!(IS_BLANK_CH(*str))) return (0); str++; len--; } return (1); } #define WXS_COMP_NAME(c, t) ((t) (c))->name #define WXS_COMP_TNS(c, t) ((t) (c))->targetNamespace /* * xmlSchemaFindRedefCompInGraph: * ATTENTION TODO: This uses pointer comp. for strings. */ static xmlSchemaBasicItemPtr xmlSchemaFindRedefCompInGraph(xmlSchemaBucketPtr bucket, xmlSchemaTypeType type, const xmlChar *name, const xmlChar *nsName) { xmlSchemaBasicItemPtr ret; int i; if ((bucket == NULL) || (name == NULL)) return(NULL); if ((bucket->globals == NULL) || (bucket->globals->nbItems == 0)) goto subschemas; /* * Search in global components. */ for (i = 0; i < bucket->globals->nbItems; i++) { ret = bucket->globals->items[i]; if (ret->type == type) { switch (type) { case XML_SCHEMA_TYPE_COMPLEX: case XML_SCHEMA_TYPE_SIMPLE: if ((WXS_COMP_NAME(ret, xmlSchemaTypePtr) == name) && (WXS_COMP_TNS(ret, xmlSchemaTypePtr) == nsName)) { return(ret); } break; case XML_SCHEMA_TYPE_GROUP: if ((WXS_COMP_NAME(ret, xmlSchemaModelGroupDefPtr) == name) && (WXS_COMP_TNS(ret, xmlSchemaModelGroupDefPtr) == nsName)) { return(ret); } break; case XML_SCHEMA_TYPE_ATTRIBUTEGROUP: if ((WXS_COMP_NAME(ret, xmlSchemaAttributeGroupPtr) == name) && (WXS_COMP_TNS(ret, xmlSchemaAttributeGroupPtr) == nsName)) { return(ret); } break; default: /* Should not be hit. */ return(NULL); } } } subschemas: /* * Process imported/included schemas. */ if (bucket->relations != NULL) { xmlSchemaSchemaRelationPtr rel = bucket->relations; /* * TODO: Marking the bucket will not avoid multiple searches * in the same schema, but avoids at least circularity. */ bucket->flags |= XML_SCHEMA_BUCKET_MARKED; do { if ((rel->bucket != NULL) && ((rel->bucket->flags & XML_SCHEMA_BUCKET_MARKED) == 0)) { ret = xmlSchemaFindRedefCompInGraph(rel->bucket, type, name, nsName); if (ret != NULL) return(ret); } rel = rel->next; } while (rel != NULL); bucket->flags ^= XML_SCHEMA_BUCKET_MARKED; } return(NULL); } /** * xmlSchemaAddNotation: * @ctxt: a schema parser context * @schema: the schema being built * @name: the item name * * Add an XML schema annotation declaration * *WARNING* this interface is highly subject to change * * Returns the new structure or NULL in case of error */ static xmlSchemaNotationPtr xmlSchemaAddNotation(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, const xmlChar *name, const xmlChar *nsName, xmlNodePtr node ATTRIBUTE_UNUSED) { xmlSchemaNotationPtr ret = NULL; if ((ctxt == NULL) || (schema == NULL) || (name == NULL)) return (NULL); ret = (xmlSchemaNotationPtr) xmlMalloc(sizeof(xmlSchemaNotation)); if (ret == NULL) { xmlSchemaPErrMemory(ctxt, "add annotation", NULL); return (NULL); } memset(ret, 0, sizeof(xmlSchemaNotation)); ret->type = XML_SCHEMA_TYPE_NOTATION; ret->name = name; ret->targetNamespace = nsName; /* TODO: do we need the node to be set? * ret->node = node;*/ WXS_ADD_GLOBAL(ctxt, ret); return (ret); } /** * xmlSchemaAddAttribute: * @ctxt: a schema parser context * @schema: the schema being built * @name: the item name * @namespace: the namespace * * Add an XML schema Attribute declaration * *WARNING* this interface is highly subject to change * * Returns the new structure or NULL in case of error */ static xmlSchemaAttributePtr xmlSchemaAddAttribute(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, const xmlChar * name, const xmlChar * nsName, xmlNodePtr node, int topLevel) { xmlSchemaAttributePtr ret = NULL; if ((ctxt == NULL) || (schema == NULL)) return (NULL); ret = (xmlSchemaAttributePtr) xmlMalloc(sizeof(xmlSchemaAttribute)); if (ret == NULL) { xmlSchemaPErrMemory(ctxt, "allocating attribute", NULL); return (NULL); } memset(ret, 0, sizeof(xmlSchemaAttribute)); ret->type = XML_SCHEMA_TYPE_ATTRIBUTE; ret->node = node; ret->name = name; ret->targetNamespace = nsName; if (topLevel) WXS_ADD_GLOBAL(ctxt, ret); else WXS_ADD_LOCAL(ctxt, ret); WXS_ADD_PENDING(ctxt, ret); return (ret); } /** * xmlSchemaAddAttributeUse: * @ctxt: a schema parser context * @schema: the schema being built * @name: the item name * @namespace: the namespace * * Add an XML schema Attribute declaration * *WARNING* this interface is highly subject to change * * Returns the new structure or NULL in case of error */ static xmlSchemaAttributeUsePtr xmlSchemaAddAttributeUse(xmlSchemaParserCtxtPtr pctxt, xmlNodePtr node) { xmlSchemaAttributeUsePtr ret = NULL; if (pctxt == NULL) return (NULL); ret = (xmlSchemaAttributeUsePtr) xmlMalloc(sizeof(xmlSchemaAttributeUse)); if (ret == NULL) { xmlSchemaPErrMemory(pctxt, "allocating attribute", NULL); return (NULL); } memset(ret, 0, sizeof(xmlSchemaAttributeUse)); ret->type = XML_SCHEMA_TYPE_ATTRIBUTE_USE; ret->node = node; WXS_ADD_LOCAL(pctxt, ret); return (ret); } /* * xmlSchemaAddRedef: * * Adds a redefinition information. This is used at a later stage to: * resolve references to the redefined components and to check constraints. */ static xmlSchemaRedefPtr xmlSchemaAddRedef(xmlSchemaParserCtxtPtr pctxt, xmlSchemaBucketPtr targetBucket, void *item, const xmlChar *refName, const xmlChar *refTargetNs) { xmlSchemaRedefPtr ret; ret = (xmlSchemaRedefPtr) xmlMalloc(sizeof(xmlSchemaRedef)); if (ret == NULL) { xmlSchemaPErrMemory(pctxt, "allocating redefinition info", NULL); return (NULL); } memset(ret, 0, sizeof(xmlSchemaRedef)); ret->item = item; ret->targetBucket = targetBucket; ret->refName = refName; ret->refTargetNs = refTargetNs; if (WXS_CONSTRUCTOR(pctxt)->redefs == NULL) WXS_CONSTRUCTOR(pctxt)->redefs = ret; else WXS_CONSTRUCTOR(pctxt)->lastRedef->next = ret; WXS_CONSTRUCTOR(pctxt)->lastRedef = ret; return (ret); } /** * xmlSchemaAddAttributeGroupDefinition: * @ctxt: a schema parser context * @schema: the schema being built * @name: the item name * @nsName: the target namespace * @node: the corresponding node * * Add an XML schema Attribute Group definition. * * Returns the new structure or NULL in case of error */ static xmlSchemaAttributeGroupPtr xmlSchemaAddAttributeGroupDefinition(xmlSchemaParserCtxtPtr pctxt, xmlSchemaPtr schema ATTRIBUTE_UNUSED, const xmlChar *name, const xmlChar *nsName, xmlNodePtr node) { xmlSchemaAttributeGroupPtr ret = NULL; if ((pctxt == NULL) || (name == NULL)) return (NULL); ret = (xmlSchemaAttributeGroupPtr) xmlMalloc(sizeof(xmlSchemaAttributeGroup)); if (ret == NULL) { xmlSchemaPErrMemory(pctxt, "allocating attribute group", NULL); return (NULL); } memset(ret, 0, sizeof(xmlSchemaAttributeGroup)); ret->type = XML_SCHEMA_TYPE_ATTRIBUTEGROUP; ret->name = name; ret->targetNamespace = nsName; ret->node = node; /* TODO: Remove the flag. */ ret->flags |= XML_SCHEMAS_ATTRGROUP_GLOBAL; if (pctxt->isRedefine) { pctxt->redef = xmlSchemaAddRedef(pctxt, pctxt->redefined, ret, name, nsName); if (pctxt->redef == NULL) { xmlFree(ret); return(NULL); } pctxt->redefCounter = 0; } WXS_ADD_GLOBAL(pctxt, ret); WXS_ADD_PENDING(pctxt, ret); return (ret); } /** * xmlSchemaAddElement: * @ctxt: a schema parser context * @schema: the schema being built * @name: the type name * @namespace: the type namespace * * Add an XML schema Element declaration * *WARNING* this interface is highly subject to change * * Returns the new structure or NULL in case of error */ static xmlSchemaElementPtr xmlSchemaAddElement(xmlSchemaParserCtxtPtr ctxt, const xmlChar * name, const xmlChar * nsName, xmlNodePtr node, int topLevel) { xmlSchemaElementPtr ret = NULL; if ((ctxt == NULL) || (name == NULL)) return (NULL); ret = (xmlSchemaElementPtr) xmlMalloc(sizeof(xmlSchemaElement)); if (ret == NULL) { xmlSchemaPErrMemory(ctxt, "allocating element", NULL); return (NULL); } memset(ret, 0, sizeof(xmlSchemaElement)); ret->type = XML_SCHEMA_TYPE_ELEMENT; ret->name = name; ret->targetNamespace = nsName; ret->node = node; if (topLevel) WXS_ADD_GLOBAL(ctxt, ret); else WXS_ADD_LOCAL(ctxt, ret); WXS_ADD_PENDING(ctxt, ret); return (ret); } /** * xmlSchemaAddType: * @ctxt: a schema parser context * @schema: the schema being built * @name: the item name * @namespace: the namespace * * Add an XML schema item * *WARNING* this interface is highly subject to change * * Returns the new structure or NULL in case of error */ static xmlSchemaTypePtr xmlSchemaAddType(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlSchemaTypeType type, const xmlChar * name, const xmlChar * nsName, xmlNodePtr node, int topLevel) { xmlSchemaTypePtr ret = NULL; if ((ctxt == NULL) || (schema == NULL)) return (NULL); ret = (xmlSchemaTypePtr) xmlMalloc(sizeof(xmlSchemaType)); if (ret == NULL) { xmlSchemaPErrMemory(ctxt, "allocating type", NULL); return (NULL); } memset(ret, 0, sizeof(xmlSchemaType)); ret->type = type; ret->name = name; ret->targetNamespace = nsName; ret->node = node; if (topLevel) { if (ctxt->isRedefine) { ctxt->redef = xmlSchemaAddRedef(ctxt, ctxt->redefined, ret, name, nsName); if (ctxt->redef == NULL) { xmlFree(ret); return(NULL); } ctxt->redefCounter = 0; } WXS_ADD_GLOBAL(ctxt, ret); } else WXS_ADD_LOCAL(ctxt, ret); WXS_ADD_PENDING(ctxt, ret); return (ret); } static xmlSchemaQNameRefPtr xmlSchemaNewQNameRef(xmlSchemaParserCtxtPtr pctxt, xmlSchemaTypeType refType, const xmlChar *refName, const xmlChar *refNs) { xmlSchemaQNameRefPtr ret; ret = (xmlSchemaQNameRefPtr) xmlMalloc(sizeof(xmlSchemaQNameRef)); if (ret == NULL) { xmlSchemaPErrMemory(pctxt, "allocating QName reference item", NULL); return (NULL); } ret->node = NULL; ret->type = XML_SCHEMA_EXTRA_QNAMEREF; ret->name = refName; ret->targetNamespace = refNs; ret->item = NULL; ret->itemType = refType; /* * Store the reference item in the schema. */ WXS_ADD_LOCAL(pctxt, ret); return (ret); } static xmlSchemaAttributeUseProhibPtr xmlSchemaAddAttributeUseProhib(xmlSchemaParserCtxtPtr pctxt) { xmlSchemaAttributeUseProhibPtr ret; ret = (xmlSchemaAttributeUseProhibPtr) xmlMalloc(sizeof(xmlSchemaAttributeUseProhib)); if (ret == NULL) { xmlSchemaPErrMemory(pctxt, "allocating attribute use prohibition", NULL); return (NULL); } memset(ret, 0, sizeof(xmlSchemaAttributeUseProhib)); ret->type = XML_SCHEMA_EXTRA_ATTR_USE_PROHIB; WXS_ADD_LOCAL(pctxt, ret); return (ret); } /** * xmlSchemaAddModelGroup: * @ctxt: a schema parser context * @schema: the schema being built * @type: the "compositor" type of the model group * @node: the node in the schema doc * * Adds a schema model group * *WARNING* this interface is highly subject to change * * Returns the new structure or NULL in case of error */ static xmlSchemaModelGroupPtr xmlSchemaAddModelGroup(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlSchemaTypeType type, xmlNodePtr node) { xmlSchemaModelGroupPtr ret = NULL; if ((ctxt == NULL) || (schema == NULL)) return (NULL); ret = (xmlSchemaModelGroupPtr) xmlMalloc(sizeof(xmlSchemaModelGroup)); if (ret == NULL) { xmlSchemaPErrMemory(ctxt, "allocating model group component", NULL); return (NULL); } memset(ret, 0, sizeof(xmlSchemaModelGroup)); ret->type = type; ret->node = node; WXS_ADD_LOCAL(ctxt, ret); if ((type == XML_SCHEMA_TYPE_SEQUENCE) || (type == XML_SCHEMA_TYPE_CHOICE)) WXS_ADD_PENDING(ctxt, ret); return (ret); } /** * xmlSchemaAddParticle: * @ctxt: a schema parser context * @schema: the schema being built * @node: the corresponding node in the schema doc * @min: the minOccurs * @max: the maxOccurs * * Adds an XML schema particle component. * *WARNING* this interface is highly subject to change * * Returns the new structure or NULL in case of error */ static xmlSchemaParticlePtr xmlSchemaAddParticle(xmlSchemaParserCtxtPtr ctxt, xmlNodePtr node, int min, int max) { xmlSchemaParticlePtr ret = NULL; if (ctxt == NULL) return (NULL); #ifdef DEBUG fprintf(stderr, "Adding particle component\n"); #endif ret = (xmlSchemaParticlePtr) xmlMalloc(sizeof(xmlSchemaParticle)); if (ret == NULL) { xmlSchemaPErrMemory(ctxt, "allocating particle component", NULL); return (NULL); } ret->type = XML_SCHEMA_TYPE_PARTICLE; ret->annot = NULL; ret->node = node; ret->minOccurs = min; ret->maxOccurs = max; ret->next = NULL; ret->children = NULL; WXS_ADD_LOCAL(ctxt, ret); /* * Note that addition to pending components will be done locally * to the specific parsing function, since the most particles * need not to be fixed up (i.e. the reference to be resolved). * REMOVED: WXS_ADD_PENDING(ctxt, ret); */ return (ret); } /** * xmlSchemaAddModelGroupDefinition: * @ctxt: a schema validation context * @schema: the schema being built * @name: the group name * * Add an XML schema Group definition * * Returns the new structure or NULL in case of error */ static xmlSchemaModelGroupDefPtr xmlSchemaAddModelGroupDefinition(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, const xmlChar *name, const xmlChar *nsName, xmlNodePtr node) { xmlSchemaModelGroupDefPtr ret = NULL; if ((ctxt == NULL) || (schema == NULL) || (name == NULL)) return (NULL); ret = (xmlSchemaModelGroupDefPtr) xmlMalloc(sizeof(xmlSchemaModelGroupDef)); if (ret == NULL) { xmlSchemaPErrMemory(ctxt, "adding group", NULL); return (NULL); } memset(ret, 0, sizeof(xmlSchemaModelGroupDef)); ret->name = name; ret->type = XML_SCHEMA_TYPE_GROUP; ret->node = node; ret->targetNamespace = nsName; if (ctxt->isRedefine) { ctxt->redef = xmlSchemaAddRedef(ctxt, ctxt->redefined, ret, name, nsName); if (ctxt->redef == NULL) { xmlFree(ret); return(NULL); } ctxt->redefCounter = 0; } WXS_ADD_GLOBAL(ctxt, ret); WXS_ADD_PENDING(ctxt, ret); return (ret); } /** * xmlSchemaNewWildcardNs: * @ctxt: a schema validation context * * Creates a new wildcard namespace constraint. * * Returns the new structure or NULL in case of error */ static xmlSchemaWildcardNsPtr xmlSchemaNewWildcardNsConstraint(xmlSchemaParserCtxtPtr ctxt) { xmlSchemaWildcardNsPtr ret; ret = (xmlSchemaWildcardNsPtr) xmlMalloc(sizeof(xmlSchemaWildcardNs)); if (ret == NULL) { xmlSchemaPErrMemory(ctxt, "creating wildcard namespace constraint", NULL); return (NULL); } ret->value = NULL; ret->next = NULL; return (ret); } static xmlSchemaIDCPtr xmlSchemaAddIDC(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, const xmlChar *name, const xmlChar *nsName, int category, xmlNodePtr node) { xmlSchemaIDCPtr ret = NULL; if ((ctxt == NULL) || (schema == NULL) || (name == NULL)) return (NULL); ret = (xmlSchemaIDCPtr) xmlMalloc(sizeof(xmlSchemaIDC)); if (ret == NULL) { xmlSchemaPErrMemory(ctxt, "allocating an identity-constraint definition", NULL); return (NULL); } memset(ret, 0, sizeof(xmlSchemaIDC)); /* The target namespace of the parent element declaration. */ ret->targetNamespace = nsName; ret->name = name; ret->type = category; ret->node = node; WXS_ADD_GLOBAL(ctxt, ret); /* * Only keyrefs need to be fixup up. */ if (category == XML_SCHEMA_TYPE_IDC_KEYREF) WXS_ADD_PENDING(ctxt, ret); return (ret); } /** * xmlSchemaAddWildcard: * @ctxt: a schema validation context * @schema: a schema * * Adds a wildcard. * It corresponds to a xsd:anyAttribute and xsd:any. * * Returns the new structure or NULL in case of error */ static xmlSchemaWildcardPtr xmlSchemaAddWildcard(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlSchemaTypeType type, xmlNodePtr node) { xmlSchemaWildcardPtr ret = NULL; if ((ctxt == NULL) || (schema == NULL)) return (NULL); ret = (xmlSchemaWildcardPtr) xmlMalloc(sizeof(xmlSchemaWildcard)); if (ret == NULL) { xmlSchemaPErrMemory(ctxt, "adding wildcard", NULL); return (NULL); } memset(ret, 0, sizeof(xmlSchemaWildcard)); ret->type = type; ret->node = node; WXS_ADD_LOCAL(ctxt, ret); return (ret); } static void xmlSchemaSubstGroupFree(xmlSchemaSubstGroupPtr group) { if (group == NULL) return; if (group->members != NULL) xmlSchemaItemListFree(group->members); xmlFree(group); } static void xmlSchemaSubstGroupFreeEntry(void *group, const xmlChar *name ATTRIBUTE_UNUSED) { xmlSchemaSubstGroupFree((xmlSchemaSubstGroupPtr) group); } static xmlSchemaSubstGroupPtr xmlSchemaSubstGroupAdd(xmlSchemaParserCtxtPtr pctxt, xmlSchemaElementPtr head) { xmlSchemaSubstGroupPtr ret; /* Init subst group hash. */ if (WXS_SUBST_GROUPS(pctxt) == NULL) { WXS_SUBST_GROUPS(pctxt) = xmlHashCreateDict(10, pctxt->dict); if (WXS_SUBST_GROUPS(pctxt) == NULL) return(NULL); } /* Create a new substitution group. */ ret = (xmlSchemaSubstGroupPtr) xmlMalloc(sizeof(xmlSchemaSubstGroup)); if (ret == NULL) { xmlSchemaPErrMemory(NULL, "allocating a substitution group container", NULL); return(NULL); } memset(ret, 0, sizeof(xmlSchemaSubstGroup)); ret->head = head; /* Create list of members. */ ret->members = xmlSchemaItemListCreate(); if (ret->members == NULL) { xmlSchemaSubstGroupFree(ret); return(NULL); } /* Add subst group to hash. */ if (xmlHashAddEntry2(WXS_SUBST_GROUPS(pctxt), head->name, head->targetNamespace, ret) != 0) { PERROR_INT("xmlSchemaSubstGroupAdd", "failed to add a new substitution container"); xmlSchemaSubstGroupFree(ret); return(NULL); } return(ret); } static xmlSchemaSubstGroupPtr xmlSchemaSubstGroupGet(xmlSchemaParserCtxtPtr pctxt, xmlSchemaElementPtr head) { if (WXS_SUBST_GROUPS(pctxt) == NULL) return(NULL); return(xmlHashLookup2(WXS_SUBST_GROUPS(pctxt), head->name, head->targetNamespace)); } /** * xmlSchemaAddElementSubstitutionMember: * @pctxt: a schema parser context * @head: the head of the substitution group * @member: the new member of the substitution group * * Allocate a new annotation structure. * * Returns the newly allocated structure or NULL in case or error */ static int xmlSchemaAddElementSubstitutionMember(xmlSchemaParserCtxtPtr pctxt, xmlSchemaElementPtr head, xmlSchemaElementPtr member) { xmlSchemaSubstGroupPtr substGroup = NULL; if ((pctxt == NULL) || (head == NULL) || (member == NULL)) return (-1); substGroup = xmlSchemaSubstGroupGet(pctxt, head); if (substGroup == NULL) substGroup = xmlSchemaSubstGroupAdd(pctxt, head); if (substGroup == NULL) return(-1); if (xmlSchemaItemListAdd(substGroup->members, member) == -1) return(-1); return(0); } /************************************************************************ * * * Utilities for parsing * * * ************************************************************************/ /** * xmlSchemaPValAttrNodeQNameValue: * @ctxt: a schema parser context * @schema: the schema context * @ownerItem: the parent as a schema object * @value: the QName value * @uri: the resulting namespace URI if found * @local: the resulting local part if found, the attribute value otherwise * * Extracts the local name and the URI of a QName value and validates it. * This one is intended to be used on attribute values that * should resolve to schema components. * * Returns 0, in case the QName is valid, a positive error code * if not valid and -1 if an internal error occurs. */ static int xmlSchemaPValAttrNodeQNameValue(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlSchemaBasicItemPtr ownerItem, xmlAttrPtr attr, const xmlChar *value, const xmlChar **uri, const xmlChar **local) { const xmlChar *pref; xmlNsPtr ns; int len, ret; *uri = NULL; *local = NULL; ret = xmlValidateQName(value, 1); if (ret > 0) { xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, ownerItem, (xmlNodePtr) attr, xmlSchemaGetBuiltInType(XML_SCHEMAS_QNAME), NULL, value, NULL, NULL, NULL); *local = value; return (ctxt->err); } else if (ret < 0) return (-1); if (!strchr((char *) value, ':')) { ns = xmlSearchNs(attr->doc, attr->parent, NULL); if (ns) *uri = xmlDictLookup(ctxt->dict, ns->href, -1); else if (schema->flags & XML_SCHEMAS_INCLUDING_CONVERT_NS) { /* TODO: move XML_SCHEMAS_INCLUDING_CONVERT_NS to the * parser context. */ /* * This one takes care of included schemas with no * target namespace. */ *uri = ctxt->targetNamespace; } *local = xmlDictLookup(ctxt->dict, value, -1); return (0); } /* * At this point xmlSplitQName3 has to return a local name. */ *local = xmlSplitQName3(value, &len); *local = xmlDictLookup(ctxt->dict, *local, -1); pref = xmlDictLookup(ctxt->dict, value, len); ns = xmlSearchNs(attr->doc, attr->parent, pref); if (ns == NULL) { xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, ownerItem, (xmlNodePtr) attr, xmlSchemaGetBuiltInType(XML_SCHEMAS_QNAME), NULL, value, "The value '%s' of simple type 'xs:QName' has no " "corresponding namespace declaration in scope", value, NULL); return (ctxt->err); } else { *uri = xmlDictLookup(ctxt->dict, ns->href, -1); } return (0); } /** * xmlSchemaPValAttrNodeQName: * @ctxt: a schema parser context * @schema: the schema context * @ownerItem: the owner as a schema object * @attr: the attribute node * @uri: the resulting namespace URI if found * @local: the resulting local part if found, the attribute value otherwise * * Extracts and validates the QName of an attribute value. * This one is intended to be used on attribute values that * should resolve to schema components. * * Returns 0, in case the QName is valid, a positive error code * if not valid and -1 if an internal error occurs. */ static int xmlSchemaPValAttrNodeQName(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlSchemaBasicItemPtr ownerItem, xmlAttrPtr attr, const xmlChar **uri, const xmlChar **local) { const xmlChar *value; value = xmlSchemaGetNodeContent(ctxt, (xmlNodePtr) attr); return (xmlSchemaPValAttrNodeQNameValue(ctxt, schema, ownerItem, attr, value, uri, local)); } /** * xmlSchemaPValAttrQName: * @ctxt: a schema parser context * @schema: the schema context * @ownerItem: the owner as a schema object * @ownerElem: the parent node of the attribute * @name: the name of the attribute * @uri: the resulting namespace URI if found * @local: the resulting local part if found, the attribute value otherwise * * Extracts and validates the QName of an attribute value. * * Returns 0, in case the QName is valid, a positive error code * if not valid and -1 if an internal error occurs. */ static int xmlSchemaPValAttrQName(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlSchemaBasicItemPtr ownerItem, xmlNodePtr ownerElem, const char *name, const xmlChar **uri, const xmlChar **local) { xmlAttrPtr attr; attr = xmlSchemaGetPropNode(ownerElem, name); if (attr == NULL) { *local = NULL; *uri = NULL; return (0); } return (xmlSchemaPValAttrNodeQName(ctxt, schema, ownerItem, attr, uri, local)); } /** * xmlSchemaPValAttrID: * @ctxt: a schema parser context * * Extracts and validates the ID of an attribute value. * * Returns 0, in case the ID is valid, a positive error code * if not valid and -1 if an internal error occurs. */ static int xmlSchemaPValAttrNodeID(xmlSchemaParserCtxtPtr ctxt, xmlAttrPtr attr) { int ret; const xmlChar *value; if (attr == NULL) return(0); value = xmlSchemaGetNodeContentNoDict((xmlNodePtr) attr); ret = xmlValidateNCName(value, 1); if (ret == 0) { /* * NOTE: the IDness might have already be declared in the DTD */ if (attr->atype != XML_ATTRIBUTE_ID) { xmlIDPtr res; xmlChar *strip; /* * TODO: Use xmlSchemaStrip here; it's not exported at this * moment. */ strip = xmlSchemaCollapseString(value); if (strip != NULL) { xmlFree((xmlChar *) value); value = strip; } res = xmlAddID(NULL, attr->doc, value, attr); if (res == NULL) { ret = XML_SCHEMAP_S4S_ATTR_INVALID_VALUE; xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, NULL, (xmlNodePtr) attr, xmlSchemaGetBuiltInType(XML_SCHEMAS_ID), NULL, NULL, "Duplicate value '%s' of simple " "type 'xs:ID'", value, NULL); } else attr->atype = XML_ATTRIBUTE_ID; } } else if (ret > 0) { ret = XML_SCHEMAP_S4S_ATTR_INVALID_VALUE; xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, NULL, (xmlNodePtr) attr, xmlSchemaGetBuiltInType(XML_SCHEMAS_ID), NULL, NULL, "The value '%s' of simple type 'xs:ID' is " "not a valid 'xs:NCName'", value, NULL); } if (value != NULL) xmlFree((xmlChar *)value); return (ret); } static int xmlSchemaPValAttrID(xmlSchemaParserCtxtPtr ctxt, xmlNodePtr ownerElem, const xmlChar *name) { xmlAttrPtr attr; attr = xmlSchemaGetPropNode(ownerElem, (const char *) name); if (attr == NULL) return(0); return(xmlSchemaPValAttrNodeID(ctxt, attr)); } /** * xmlGetMaxOccurs: * @ctxt: a schema validation context * @node: a subtree containing XML Schema information * * Get the maxOccurs property * * Returns the default if not found, or the value */ static int xmlGetMaxOccurs(xmlSchemaParserCtxtPtr ctxt, xmlNodePtr node, int min, int max, int def, const char *expected) { const xmlChar *val, *cur; int ret = 0; xmlAttrPtr attr; attr = xmlSchemaGetPropNode(node, "maxOccurs"); if (attr == NULL) return (def); val = xmlSchemaGetNodeContent(ctxt, (xmlNodePtr) attr); if (xmlStrEqual(val, (const xmlChar *) "unbounded")) { if (max != UNBOUNDED) { xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, /* XML_SCHEMAP_INVALID_MINOCCURS, */ NULL, (xmlNodePtr) attr, NULL, expected, val, NULL, NULL, NULL); return (def); } else return (UNBOUNDED); /* encoding it with -1 might be another option */ } cur = val; while (IS_BLANK_CH(*cur)) cur++; if (*cur == 0) { xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, /* XML_SCHEMAP_INVALID_MINOCCURS, */ NULL, (xmlNodePtr) attr, NULL, expected, val, NULL, NULL, NULL); return (def); } while ((*cur >= '0') && (*cur <= '9')) { if (ret > INT_MAX / 10) { ret = INT_MAX; } else { int digit = *cur - '0'; ret *= 10; if (ret > INT_MAX - digit) ret = INT_MAX; else ret += digit; } cur++; } while (IS_BLANK_CH(*cur)) cur++; /* * TODO: Restrict the maximal value to Integer. */ if ((*cur != 0) || (ret < min) || ((max != -1) && (ret > max))) { xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, /* XML_SCHEMAP_INVALID_MINOCCURS, */ NULL, (xmlNodePtr) attr, NULL, expected, val, NULL, NULL, NULL); return (def); } return (ret); } /** * xmlGetMinOccurs: * @ctxt: a schema validation context * @node: a subtree containing XML Schema information * * Get the minOccurs property * * Returns the default if not found, or the value */ static int xmlGetMinOccurs(xmlSchemaParserCtxtPtr ctxt, xmlNodePtr node, int min, int max, int def, const char *expected) { const xmlChar *val, *cur; int ret = 0; xmlAttrPtr attr; attr = xmlSchemaGetPropNode(node, "minOccurs"); if (attr == NULL) return (def); val = xmlSchemaGetNodeContent(ctxt, (xmlNodePtr) attr); cur = val; while (IS_BLANK_CH(*cur)) cur++; if (*cur == 0) { xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, /* XML_SCHEMAP_INVALID_MINOCCURS, */ NULL, (xmlNodePtr) attr, NULL, expected, val, NULL, NULL, NULL); return (def); } while ((*cur >= '0') && (*cur <= '9')) { if (ret > INT_MAX / 10) { ret = INT_MAX; } else { int digit = *cur - '0'; ret *= 10; if (ret > INT_MAX - digit) ret = INT_MAX; else ret += digit; } cur++; } while (IS_BLANK_CH(*cur)) cur++; /* * TODO: Restrict the maximal value to Integer. */ if ((*cur != 0) || (ret < min) || ((max != -1) && (ret > max))) { xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, /* XML_SCHEMAP_INVALID_MINOCCURS, */ NULL, (xmlNodePtr) attr, NULL, expected, val, NULL, NULL, NULL); return (def); } return (ret); } /** * xmlSchemaPGetBoolNodeValue: * @ctxt: a schema validation context * @ownerItem: the owner as a schema item * @node: the node holding the value * * Converts a boolean string value into 1 or 0. * * Returns 0 or 1. */ static int xmlSchemaPGetBoolNodeValue(xmlSchemaParserCtxtPtr ctxt, xmlSchemaBasicItemPtr ownerItem, xmlNodePtr node) { xmlChar *value = NULL; int res = 0; value = xmlNodeGetContent(node); /* * 3.2.2.1 Lexical representation * An instance of a datatype that is defined as `boolean` * can have the following legal literals {true, false, 1, 0}. */ if (xmlStrEqual(BAD_CAST value, BAD_CAST "true")) res = 1; else if (xmlStrEqual(BAD_CAST value, BAD_CAST "false")) res = 0; else if (xmlStrEqual(BAD_CAST value, BAD_CAST "1")) res = 1; else if (xmlStrEqual(BAD_CAST value, BAD_CAST "0")) res = 0; else { xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_INVALID_BOOLEAN, ownerItem, node, xmlSchemaGetBuiltInType(XML_SCHEMAS_BOOLEAN), NULL, BAD_CAST value, NULL, NULL, NULL); } if (value != NULL) xmlFree(value); return (res); } /** * xmlGetBooleanProp: * @ctxt: a schema validation context * @node: a subtree containing XML Schema information * @name: the attribute name * @def: the default value * * Evaluate if a boolean property is set * * Returns the default if not found, 0 if found to be false, * 1 if found to be true */ static int xmlGetBooleanProp(xmlSchemaParserCtxtPtr ctxt, xmlNodePtr node, const char *name, int def) { const xmlChar *val; val = xmlSchemaGetProp(ctxt, node, name); if (val == NULL) return (def); /* * 3.2.2.1 Lexical representation * An instance of a datatype that is defined as `boolean` * can have the following legal literals {true, false, 1, 0}. */ if (xmlStrEqual(val, BAD_CAST "true")) def = 1; else if (xmlStrEqual(val, BAD_CAST "false")) def = 0; else if (xmlStrEqual(val, BAD_CAST "1")) def = 1; else if (xmlStrEqual(val, BAD_CAST "0")) def = 0; else { xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_INVALID_BOOLEAN, NULL, (xmlNodePtr) xmlSchemaGetPropNode(node, name), xmlSchemaGetBuiltInType(XML_SCHEMAS_BOOLEAN), NULL, val, NULL, NULL, NULL); } return (def); } /************************************************************************ * * * Schema extraction from an Infoset * * * ************************************************************************/ static xmlSchemaTypePtr xmlSchemaParseSimpleType(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node, int topLevel); static xmlSchemaTypePtr xmlSchemaParseComplexType(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node, int topLevel); static xmlSchemaTypePtr xmlSchemaParseRestriction(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node, xmlSchemaTypeType parentType); static xmlSchemaBasicItemPtr xmlSchemaParseLocalAttribute(xmlSchemaParserCtxtPtr pctxt, xmlSchemaPtr schema, xmlNodePtr node, xmlSchemaItemListPtr uses, int parentType); static xmlSchemaTypePtr xmlSchemaParseList(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node); static xmlSchemaWildcardPtr xmlSchemaParseAnyAttribute(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node); /** * xmlSchemaPValAttrNodeValue: * * @pctxt: a schema parser context * @ownerItem: the schema object owner if existent * @attr: the schema attribute node being validated * @value: the value * @type: the built-in type to be validated against * * Validates a value against the given built-in type. * This one is intended to be used internally for validation * of schema attribute values during parsing of the schema. * * Returns 0 if the value is valid, a positive error code * number otherwise and -1 in case of an internal or API error. */ static int xmlSchemaPValAttrNodeValue(xmlSchemaParserCtxtPtr pctxt, xmlSchemaBasicItemPtr ownerItem, xmlAttrPtr attr, const xmlChar *value, xmlSchemaTypePtr type) { int ret = 0; /* * NOTE: Should we move this to xmlschematypes.c? Hmm, but this * one is really meant to be used internally, so better not. */ if ((pctxt == NULL) || (type == NULL) || (attr == NULL)) return (-1); if (type->type != XML_SCHEMA_TYPE_BASIC) { PERROR_INT("xmlSchemaPValAttrNodeValue", "the given type is not a built-in type"); return (-1); } switch (type->builtInType) { case XML_SCHEMAS_NCNAME: case XML_SCHEMAS_QNAME: case XML_SCHEMAS_ANYURI: case XML_SCHEMAS_TOKEN: case XML_SCHEMAS_LANGUAGE: ret = xmlSchemaValPredefTypeNode(type, value, NULL, (xmlNodePtr) attr); break; default: { PERROR_INT("xmlSchemaPValAttrNodeValue", "validation using the given type is not supported while " "parsing a schema"); return (-1); } } /* * TODO: Should we use the S4S error codes instead? */ if (ret < 0) { PERROR_INT("xmlSchemaPValAttrNodeValue", "failed to validate a schema attribute value"); return (-1); } else if (ret > 0) { if (WXS_IS_LIST(type)) ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_2; else ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1; xmlSchemaPSimpleTypeErr(pctxt, ret, ownerItem, (xmlNodePtr) attr, type, NULL, value, NULL, NULL, NULL); } return (ret); } /** * xmlSchemaPValAttrNode: * * @ctxt: a schema parser context * @ownerItem: the schema object owner if existent * @attr: the schema attribute node being validated * @type: the built-in type to be validated against * @value: the resulting value if any * * Extracts and validates a value against the given built-in type. * This one is intended to be used internally for validation * of schema attribute values during parsing of the schema. * * Returns 0 if the value is valid, a positive error code * number otherwise and -1 in case of an internal or API error. */ static int xmlSchemaPValAttrNode(xmlSchemaParserCtxtPtr ctxt, xmlSchemaBasicItemPtr ownerItem, xmlAttrPtr attr, xmlSchemaTypePtr type, const xmlChar **value) { const xmlChar *val; if ((ctxt == NULL) || (type == NULL) || (attr == NULL)) return (-1); val = xmlSchemaGetNodeContent(ctxt, (xmlNodePtr) attr); if (value != NULL) *value = val; return (xmlSchemaPValAttrNodeValue(ctxt, ownerItem, attr, val, type)); } /** * xmlSchemaPValAttr: * * @ctxt: a schema parser context * @node: the element node of the attribute * @ownerItem: the schema object owner if existent * @ownerElem: the owner element node * @name: the name of the schema attribute node * @type: the built-in type to be validated against * @value: the resulting value if any * * Extracts and validates a value against the given built-in type. * This one is intended to be used internally for validation * of schema attribute values during parsing of the schema. * * Returns 0 if the value is valid, a positive error code * number otherwise and -1 in case of an internal or API error. */ static int xmlSchemaPValAttr(xmlSchemaParserCtxtPtr ctxt, xmlSchemaBasicItemPtr ownerItem, xmlNodePtr ownerElem, const char *name, xmlSchemaTypePtr type, const xmlChar **value) { xmlAttrPtr attr; if ((ctxt == NULL) || (type == NULL)) { if (value != NULL) *value = NULL; return (-1); } if (type->type != XML_SCHEMA_TYPE_BASIC) { if (value != NULL) *value = NULL; xmlSchemaPErr(ctxt, ownerElem, XML_SCHEMAP_INTERNAL, "Internal error: xmlSchemaPValAttr, the given " "type '%s' is not a built-in type.\n", type->name, NULL); return (-1); } attr = xmlSchemaGetPropNode(ownerElem, name); if (attr == NULL) { if (value != NULL) *value = NULL; return (0); } return (xmlSchemaPValAttrNode(ctxt, ownerItem, attr, type, value)); } static int xmlSchemaCheckReference(xmlSchemaParserCtxtPtr pctxt, xmlSchemaPtr schema ATTRIBUTE_UNUSED, xmlNodePtr node, xmlAttrPtr attr, const xmlChar *namespaceName) { /* TODO: Pointer comparison instead? */ if (xmlStrEqual(pctxt->targetNamespace, namespaceName)) return (0); if (xmlStrEqual(xmlSchemaNs, namespaceName)) return (0); /* * Check if the referenced namespace was <import>ed. */ if (WXS_BUCKET(pctxt)->relations != NULL) { xmlSchemaSchemaRelationPtr rel; rel = WXS_BUCKET(pctxt)->relations; do { if (WXS_IS_BUCKET_IMPMAIN(rel->type) && xmlStrEqual(namespaceName, rel->importNamespace)) return (0); rel = rel->next; } while (rel != NULL); } /* * No matching <import>ed namespace found. */ { xmlNodePtr n = (attr != NULL) ? (xmlNodePtr) attr : node; if (namespaceName == NULL) xmlSchemaCustomErr(ACTXT_CAST pctxt, XML_SCHEMAP_SRC_RESOLVE, n, NULL, "References from this schema to components in no " "namespace are not allowed, since not indicated by an " "import statement", NULL, NULL); else xmlSchemaCustomErr(ACTXT_CAST pctxt, XML_SCHEMAP_SRC_RESOLVE, n, NULL, "References from this schema to components in the " "namespace '%s' are not allowed, since not indicated by an " "import statement", namespaceName, NULL); } return (XML_SCHEMAP_SRC_RESOLVE); } /** * xmlSchemaParseLocalAttributes: * @ctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * @type: the hosting type where the attributes will be anchored * * Parses attribute uses and attribute declarations and * attribute group references. */ static int xmlSchemaParseLocalAttributes(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr *child, xmlSchemaItemListPtr *list, int parentType, int *hasRefs) { void *item; while ((IS_SCHEMA((*child), "attribute")) || (IS_SCHEMA((*child), "attributeGroup"))) { if (IS_SCHEMA((*child), "attribute")) { item = xmlSchemaParseLocalAttribute(ctxt, schema, *child, *list, parentType); } else { item = xmlSchemaParseAttributeGroupRef(ctxt, schema, *child); if ((item != NULL) && (hasRefs != NULL)) *hasRefs = 1; } if (item != NULL) { if (*list == NULL) { /* TODO: Customize grow factor. */ *list = xmlSchemaItemListCreate(); if (*list == NULL) return(-1); } if (xmlSchemaItemListAddSize(*list, 2, item) == -1) return(-1); } *child = (*child)->next; } return (0); } /** * xmlSchemaParseAnnotation: * @ctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * * parse a XML schema Attribute declaration * *WARNING* this interface is highly subject to change * * Returns -1 in case of error, 0 if the declaration is improper and * 1 in case of success. */ static xmlSchemaAnnotPtr xmlSchemaParseAnnotation(xmlSchemaParserCtxtPtr ctxt, xmlNodePtr node, int needed) { xmlSchemaAnnotPtr ret; xmlNodePtr child = NULL; xmlAttrPtr attr; int barked = 0; /* * INFO: S4S completed. */ /* * id = ID * {any attributes with non-schema namespace . . .}> * Content: (appinfo | documentation)* */ if ((ctxt == NULL) || (node == NULL)) return (NULL); if (needed) ret = xmlSchemaNewAnnot(ctxt, node); else ret = NULL; attr = node->properties; while (attr != NULL) { if (((attr->ns == NULL) && (!xmlStrEqual(attr->name, BAD_CAST "id"))) || ((attr->ns != NULL) && xmlStrEqual(attr->ns->href, xmlSchemaNs))) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } xmlSchemaPValAttrID(ctxt, node, BAD_CAST "id"); /* * And now for the children... */ child = node->children; while (child != NULL) { if (IS_SCHEMA(child, "appinfo")) { /* TODO: make available the content of "appinfo". */ /* * source = anyURI * {any attributes with non-schema namespace . . .}> * Content: ({any})* */ attr = child->properties; while (attr != NULL) { if (((attr->ns == NULL) && (!xmlStrEqual(attr->name, BAD_CAST "source"))) || ((attr->ns != NULL) && xmlStrEqual(attr->ns->href, xmlSchemaNs))) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } xmlSchemaPValAttr(ctxt, NULL, child, "source", xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYURI), NULL); child = child->next; } else if (IS_SCHEMA(child, "documentation")) { /* TODO: make available the content of "documentation". */ /* * source = anyURI * {any attributes with non-schema namespace . . .}> * Content: ({any})* */ attr = child->properties; while (attr != NULL) { if (attr->ns == NULL) { if (!xmlStrEqual(attr->name, BAD_CAST "source")) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else { if (xmlStrEqual(attr->ns->href, xmlSchemaNs) || (xmlStrEqual(attr->name, BAD_CAST "lang") && (!xmlStrEqual(attr->ns->href, XML_XML_NAMESPACE)))) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } attr = attr->next; } /* * Attribute "xml:lang". */ attr = xmlSchemaGetPropNodeNs(child, (const char *) XML_XML_NAMESPACE, "lang"); if (attr != NULL) xmlSchemaPValAttrNode(ctxt, NULL, attr, xmlSchemaGetBuiltInType(XML_SCHEMAS_LANGUAGE), NULL); child = child->next; } else { if (!barked) xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(appinfo | documentation)*"); barked = 1; child = child->next; } } return (ret); } /** * xmlSchemaParseFacet: * @ctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * * parse a XML schema Facet declaration * *WARNING* this interface is highly subject to change * * Returns the new type structure or NULL in case of error */ static xmlSchemaFacetPtr xmlSchemaParseFacet(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node) { xmlSchemaFacetPtr facet; xmlNodePtr child = NULL; const xmlChar *value; if ((ctxt == NULL) || (schema == NULL) || (node == NULL)) return (NULL); facet = xmlSchemaNewFacet(); if (facet == NULL) { xmlSchemaPErrMemory(ctxt, "allocating facet", node); return (NULL); } facet->node = node; value = xmlSchemaGetProp(ctxt, node, "value"); if (value == NULL) { xmlSchemaPErr2(ctxt, node, child, XML_SCHEMAP_FACET_NO_VALUE, "Facet %s has no value\n", node->name, NULL); xmlSchemaFreeFacet(facet); return (NULL); } if (IS_SCHEMA(node, "minInclusive")) { facet->type = XML_SCHEMA_FACET_MININCLUSIVE; } else if (IS_SCHEMA(node, "minExclusive")) { facet->type = XML_SCHEMA_FACET_MINEXCLUSIVE; } else if (IS_SCHEMA(node, "maxInclusive")) { facet->type = XML_SCHEMA_FACET_MAXINCLUSIVE; } else if (IS_SCHEMA(node, "maxExclusive")) { facet->type = XML_SCHEMA_FACET_MAXEXCLUSIVE; } else if (IS_SCHEMA(node, "totalDigits")) { facet->type = XML_SCHEMA_FACET_TOTALDIGITS; } else if (IS_SCHEMA(node, "fractionDigits")) { facet->type = XML_SCHEMA_FACET_FRACTIONDIGITS; } else if (IS_SCHEMA(node, "pattern")) { facet->type = XML_SCHEMA_FACET_PATTERN; } else if (IS_SCHEMA(node, "enumeration")) { facet->type = XML_SCHEMA_FACET_ENUMERATION; } else if (IS_SCHEMA(node, "whiteSpace")) { facet->type = XML_SCHEMA_FACET_WHITESPACE; } else if (IS_SCHEMA(node, "length")) { facet->type = XML_SCHEMA_FACET_LENGTH; } else if (IS_SCHEMA(node, "maxLength")) { facet->type = XML_SCHEMA_FACET_MAXLENGTH; } else if (IS_SCHEMA(node, "minLength")) { facet->type = XML_SCHEMA_FACET_MINLENGTH; } else { xmlSchemaPErr2(ctxt, node, child, XML_SCHEMAP_UNKNOWN_FACET_TYPE, "Unknown facet type %s\n", node->name, NULL); xmlSchemaFreeFacet(facet); return (NULL); } xmlSchemaPValAttrID(ctxt, node, BAD_CAST "id"); facet->value = value; if ((facet->type != XML_SCHEMA_FACET_PATTERN) && (facet->type != XML_SCHEMA_FACET_ENUMERATION)) { const xmlChar *fixed; fixed = xmlSchemaGetProp(ctxt, node, "fixed"); if (fixed != NULL) { if (xmlStrEqual(fixed, BAD_CAST "true")) facet->fixed = 1; } } child = node->children; if (IS_SCHEMA(child, "annotation")) { facet->annot = xmlSchemaParseAnnotation(ctxt, child, 1); child = child->next; } if (child != NULL) { xmlSchemaPErr2(ctxt, node, child, XML_SCHEMAP_UNKNOWN_FACET_CHILD, "Facet %s has unexpected child content\n", node->name, NULL); } return (facet); } /** * xmlSchemaParseWildcardNs: * @ctxt: a schema parser context * @wildc: the wildcard, already created * @node: a subtree containing XML Schema information * * Parses the attribute "processContents" and "namespace" * of a xsd:anyAttribute and xsd:any. * *WARNING* this interface is highly subject to change * * Returns 0 if everything goes fine, a positive error code * if something is not valid and -1 if an internal error occurs. */ static int xmlSchemaParseWildcardNs(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema ATTRIBUTE_UNUSED, xmlSchemaWildcardPtr wildc, xmlNodePtr node) { const xmlChar *pc, *ns, *dictnsItem; int ret = 0; xmlChar *nsItem; xmlSchemaWildcardNsPtr tmp, lastNs = NULL; xmlAttrPtr attr; pc = xmlSchemaGetProp(ctxt, node, "processContents"); if ((pc == NULL) || (xmlStrEqual(pc, (const xmlChar *) "strict"))) { wildc->processContents = XML_SCHEMAS_ANY_STRICT; } else if (xmlStrEqual(pc, (const xmlChar *) "skip")) { wildc->processContents = XML_SCHEMAS_ANY_SKIP; } else if (xmlStrEqual(pc, (const xmlChar *) "lax")) { wildc->processContents = XML_SCHEMAS_ANY_LAX; } else { xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, NULL, node, NULL, "(strict | skip | lax)", pc, NULL, NULL, NULL); wildc->processContents = XML_SCHEMAS_ANY_STRICT; ret = XML_SCHEMAP_S4S_ATTR_INVALID_VALUE; } /* * Build the namespace constraints. */ attr = xmlSchemaGetPropNode(node, "namespace"); ns = xmlSchemaGetNodeContent(ctxt, (xmlNodePtr) attr); if ((attr == NULL) || (xmlStrEqual(ns, BAD_CAST "##any"))) wildc->any = 1; else if (xmlStrEqual(ns, BAD_CAST "##other")) { wildc->negNsSet = xmlSchemaNewWildcardNsConstraint(ctxt); if (wildc->negNsSet == NULL) { return (-1); } wildc->negNsSet->value = ctxt->targetNamespace; } else { const xmlChar *end, *cur; cur = ns; do { while (IS_BLANK_CH(*cur)) cur++; end = cur; while ((*end != 0) && (!(IS_BLANK_CH(*end)))) end++; if (end == cur) break; nsItem = xmlStrndup(cur, end - cur); if ((xmlStrEqual(nsItem, BAD_CAST "##other")) || (xmlStrEqual(nsItem, BAD_CAST "##any"))) { xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_WILDCARD_INVALID_NS_MEMBER, NULL, (xmlNodePtr) attr, NULL, "((##any | ##other) | List of (xs:anyURI | " "(##targetNamespace | ##local)))", nsItem, NULL, NULL, NULL); ret = XML_SCHEMAP_WILDCARD_INVALID_NS_MEMBER; } else { if (xmlStrEqual(nsItem, BAD_CAST "##targetNamespace")) { dictnsItem = ctxt->targetNamespace; } else if (xmlStrEqual(nsItem, BAD_CAST "##local")) { dictnsItem = NULL; } else { /* * Validate the item (anyURI). */ xmlSchemaPValAttrNodeValue(ctxt, NULL, attr, nsItem, xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYURI)); dictnsItem = xmlDictLookup(ctxt->dict, nsItem, -1); } /* * Avoid duplicate namespaces. */ tmp = wildc->nsSet; while (tmp != NULL) { if (dictnsItem == tmp->value) break; tmp = tmp->next; } if (tmp == NULL) { tmp = xmlSchemaNewWildcardNsConstraint(ctxt); if (tmp == NULL) { xmlFree(nsItem); return (-1); } tmp->value = dictnsItem; tmp->next = NULL; if (wildc->nsSet == NULL) wildc->nsSet = tmp; else if (lastNs != NULL) lastNs->next = tmp; lastNs = tmp; } } xmlFree(nsItem); cur = end; } while (*cur != 0); } return (ret); } static int xmlSchemaPCheckParticleCorrect_2(xmlSchemaParserCtxtPtr ctxt, xmlSchemaParticlePtr item ATTRIBUTE_UNUSED, xmlNodePtr node, int minOccurs, int maxOccurs) { if ((maxOccurs == 0) && ( minOccurs == 0)) return (0); if (maxOccurs != UNBOUNDED) { /* * TODO: Maybe we should better not create the particle, * if min/max is invalid, since it could confuse the build of the * content model. */ /* * 3.9.6 Schema Component Constraint: Particle Correct * */ if (maxOccurs < 1) { /* * 2.2 {max occurs} must be greater than or equal to 1. */ xmlSchemaPCustomAttrErr(ctxt, XML_SCHEMAP_P_PROPS_CORRECT_2_2, NULL, NULL, xmlSchemaGetPropNode(node, "maxOccurs"), "The value must be greater than or equal to 1"); return (XML_SCHEMAP_P_PROPS_CORRECT_2_2); } else if (minOccurs > maxOccurs) { /* * 2.1 {min occurs} must not be greater than {max occurs}. */ xmlSchemaPCustomAttrErr(ctxt, XML_SCHEMAP_P_PROPS_CORRECT_2_1, NULL, NULL, xmlSchemaGetPropNode(node, "minOccurs"), "The value must not be greater than the value of 'maxOccurs'"); return (XML_SCHEMAP_P_PROPS_CORRECT_2_1); } } return (0); } /** * xmlSchemaParseAny: * @ctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * * Parsea a XML schema <any> element. A particle and wildcard * will be created (except if minOccurs==maxOccurs==0, in this case * nothing will be created). * *WARNING* this interface is highly subject to change * * Returns the particle or NULL in case of error or if minOccurs==maxOccurs==0 */ static xmlSchemaParticlePtr xmlSchemaParseAny(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node) { xmlSchemaParticlePtr particle; xmlNodePtr child = NULL; xmlSchemaWildcardPtr wild; int min, max; xmlAttrPtr attr; xmlSchemaAnnotPtr annot = NULL; if ((ctxt == NULL) || (schema == NULL) || (node == NULL)) return (NULL); /* * Check for illegal attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if ((!xmlStrEqual(attr->name, BAD_CAST "id")) && (!xmlStrEqual(attr->name, BAD_CAST "minOccurs")) && (!xmlStrEqual(attr->name, BAD_CAST "maxOccurs")) && (!xmlStrEqual(attr->name, BAD_CAST "namespace")) && (!xmlStrEqual(attr->name, BAD_CAST "processContents"))) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } xmlSchemaPValAttrID(ctxt, node, BAD_CAST "id"); /* * minOccurs/maxOccurs. */ max = xmlGetMaxOccurs(ctxt, node, 0, UNBOUNDED, 1, "(xs:nonNegativeInteger | unbounded)"); min = xmlGetMinOccurs(ctxt, node, 0, -1, 1, "xs:nonNegativeInteger"); xmlSchemaPCheckParticleCorrect_2(ctxt, NULL, node, min, max); /* * Create & parse the wildcard. */ wild = xmlSchemaAddWildcard(ctxt, schema, XML_SCHEMA_TYPE_ANY, node); if (wild == NULL) return (NULL); xmlSchemaParseWildcardNs(ctxt, schema, wild, node); /* * And now for the children... */ child = node->children; if (IS_SCHEMA(child, "annotation")) { annot = xmlSchemaParseAnnotation(ctxt, child, 1); child = child->next; } if (child != NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?)"); } /* * No component if minOccurs==maxOccurs==0. */ if ((min == 0) && (max == 0)) { /* Don't free the wildcard, since it's already on the list. */ return (NULL); } /* * Create the particle. */ particle = xmlSchemaAddParticle(ctxt, node, min, max); if (particle == NULL) return (NULL); particle->annot = annot; particle->children = (xmlSchemaTreeItemPtr) wild; return (particle); } /** * xmlSchemaParseNotation: * @ctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * * parse a XML schema Notation declaration * * Returns the new structure or NULL in case of error */ static xmlSchemaNotationPtr xmlSchemaParseNotation(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node) { const xmlChar *name; xmlSchemaNotationPtr ret; xmlNodePtr child = NULL; if ((ctxt == NULL) || (schema == NULL) || (node == NULL)) return (NULL); name = xmlSchemaGetProp(ctxt, node, "name"); if (name == NULL) { xmlSchemaPErr2(ctxt, node, child, XML_SCHEMAP_NOTATION_NO_NAME, "Notation has no name\n", NULL, NULL); return (NULL); } ret = xmlSchemaAddNotation(ctxt, schema, name, ctxt->targetNamespace, node); if (ret == NULL) return (NULL); xmlSchemaPValAttrID(ctxt, node, BAD_CAST "id"); child = node->children; if (IS_SCHEMA(child, "annotation")) { ret->annot = xmlSchemaParseAnnotation(ctxt, child, 1); child = child->next; } if (child != NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?)"); } return (ret); } /** * xmlSchemaParseAnyAttribute: * @ctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * * parse a XML schema AnyAttribute declaration * *WARNING* this interface is highly subject to change * * Returns a wildcard or NULL. */ static xmlSchemaWildcardPtr xmlSchemaParseAnyAttribute(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node) { xmlSchemaWildcardPtr ret; xmlNodePtr child = NULL; xmlAttrPtr attr; if ((ctxt == NULL) || (schema == NULL) || (node == NULL)) return (NULL); ret = xmlSchemaAddWildcard(ctxt, schema, XML_SCHEMA_TYPE_ANY_ATTRIBUTE, node); if (ret == NULL) { return (NULL); } /* * Check for illegal attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if ((!xmlStrEqual(attr->name, BAD_CAST "id")) && (!xmlStrEqual(attr->name, BAD_CAST "namespace")) && (!xmlStrEqual(attr->name, BAD_CAST "processContents"))) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } xmlSchemaPValAttrID(ctxt, node, BAD_CAST "id"); /* * Parse the namespace list. */ if (xmlSchemaParseWildcardNs(ctxt, schema, ret, node) != 0) return (NULL); /* * And now for the children... */ child = node->children; if (IS_SCHEMA(child, "annotation")) { ret->annot = xmlSchemaParseAnnotation(ctxt, child, 1); child = child->next; } if (child != NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?)"); } return (ret); } /** * xmlSchemaParseAttribute: * @ctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * * parse a XML schema Attribute declaration * *WARNING* this interface is highly subject to change * * Returns the attribute declaration. */ static xmlSchemaBasicItemPtr xmlSchemaParseLocalAttribute(xmlSchemaParserCtxtPtr pctxt, xmlSchemaPtr schema, xmlNodePtr node, xmlSchemaItemListPtr uses, int parentType) { const xmlChar *attrValue, *name = NULL, *ns = NULL; xmlSchemaAttributeUsePtr use = NULL; xmlNodePtr child = NULL; xmlAttrPtr attr; const xmlChar *tmpNs = NULL, *tmpName = NULL, *defValue = NULL; int isRef = 0, occurs = XML_SCHEMAS_ATTR_USE_OPTIONAL; int nberrors, hasForm = 0, defValueType = 0; #define WXS_ATTR_DEF_VAL_DEFAULT 1 #define WXS_ATTR_DEF_VAL_FIXED 2 /* * 3.2.3 Constraints on XML Representations of Attribute Declarations */ if ((pctxt == NULL) || (schema == NULL) || (node == NULL)) return (NULL); attr = xmlSchemaGetPropNode(node, "ref"); if (attr != NULL) { if (xmlSchemaPValAttrNodeQName(pctxt, schema, NULL, attr, &tmpNs, &tmpName) != 0) { return (NULL); } if (xmlSchemaCheckReference(pctxt, schema, node, attr, tmpNs) != 0) return(NULL); isRef = 1; } nberrors = pctxt->nberrors; /* * Check for illegal attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if (isRef) { if (xmlStrEqual(attr->name, BAD_CAST "id")) { xmlSchemaPValAttrNodeID(pctxt, attr); goto attr_next; } else if (xmlStrEqual(attr->name, BAD_CAST "ref")) { goto attr_next; } } else { if (xmlStrEqual(attr->name, BAD_CAST "name")) { goto attr_next; } else if (xmlStrEqual(attr->name, BAD_CAST "id")) { xmlSchemaPValAttrNodeID(pctxt, attr); goto attr_next; } else if (xmlStrEqual(attr->name, BAD_CAST "type")) { xmlSchemaPValAttrNodeQName(pctxt, schema, NULL, attr, &tmpNs, &tmpName); goto attr_next; } else if (xmlStrEqual(attr->name, BAD_CAST "form")) { /* * Evaluate the target namespace */ hasForm = 1; attrValue = xmlSchemaGetNodeContent(pctxt, (xmlNodePtr) attr); if (xmlStrEqual(attrValue, BAD_CAST "qualified")) { ns = pctxt->targetNamespace; } else if (!xmlStrEqual(attrValue, BAD_CAST "unqualified")) { xmlSchemaPSimpleTypeErr(pctxt, XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, NULL, (xmlNodePtr) attr, NULL, "(qualified | unqualified)", attrValue, NULL, NULL, NULL); } goto attr_next; } } if (xmlStrEqual(attr->name, BAD_CAST "use")) { attrValue = xmlSchemaGetNodeContent(pctxt, (xmlNodePtr) attr); /* TODO: Maybe we need to normalize the value beforehand. */ if (xmlStrEqual(attrValue, BAD_CAST "optional")) occurs = XML_SCHEMAS_ATTR_USE_OPTIONAL; else if (xmlStrEqual(attrValue, BAD_CAST "prohibited")) occurs = XML_SCHEMAS_ATTR_USE_PROHIBITED; else if (xmlStrEqual(attrValue, BAD_CAST "required")) occurs = XML_SCHEMAS_ATTR_USE_REQUIRED; else { xmlSchemaPSimpleTypeErr(pctxt, XML_SCHEMAP_INVALID_ATTR_USE, NULL, (xmlNodePtr) attr, NULL, "(optional | prohibited | required)", attrValue, NULL, NULL, NULL); } goto attr_next; } else if (xmlStrEqual(attr->name, BAD_CAST "default")) { /* * 3.2.3 : 1 * default and fixed must not both be present. */ if (defValue) { xmlSchemaPMutualExclAttrErr(pctxt, XML_SCHEMAP_SRC_ATTRIBUTE_1, NULL, attr, "default", "fixed"); } else { defValue = xmlSchemaGetNodeContent(pctxt, (xmlNodePtr) attr); defValueType = WXS_ATTR_DEF_VAL_DEFAULT; } goto attr_next; } else if (xmlStrEqual(attr->name, BAD_CAST "fixed")) { /* * 3.2.3 : 1 * default and fixed must not both be present. */ if (defValue) { xmlSchemaPMutualExclAttrErr(pctxt, XML_SCHEMAP_SRC_ATTRIBUTE_1, NULL, attr, "default", "fixed"); } else { defValue = xmlSchemaGetNodeContent(pctxt, (xmlNodePtr) attr); defValueType = WXS_ATTR_DEF_VAL_FIXED; } goto attr_next; } } else if (! xmlStrEqual(attr->ns->href, xmlSchemaNs)) goto attr_next; xmlSchemaPIllegalAttrErr(pctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); attr_next: attr = attr->next; } /* * 3.2.3 : 2 * If default and use are both present, use must have * the actual value optional. */ if ((defValueType == WXS_ATTR_DEF_VAL_DEFAULT) && (occurs != XML_SCHEMAS_ATTR_USE_OPTIONAL)) { xmlSchemaPSimpleTypeErr(pctxt, XML_SCHEMAP_SRC_ATTRIBUTE_2, NULL, node, NULL, "(optional | prohibited | required)", NULL, "The value of the attribute 'use' must be 'optional' " "if the attribute 'default' is present", NULL, NULL); } /* * We want correct attributes. */ if (nberrors != pctxt->nberrors) return(NULL); if (! isRef) { xmlSchemaAttributePtr attrDecl; /* TODO: move XML_SCHEMAS_QUALIF_ATTR to the parser. */ if ((! hasForm) && (schema->flags & XML_SCHEMAS_QUALIF_ATTR)) ns = pctxt->targetNamespace; /* * 3.2.6 Schema Component Constraint: xsi: Not Allowed * TODO: Move this to the component layer. */ if (xmlStrEqual(ns, xmlSchemaInstanceNs)) { xmlSchemaCustomErr(ACTXT_CAST pctxt, XML_SCHEMAP_NO_XSI, node, NULL, "The target namespace must not match '%s'", xmlSchemaInstanceNs, NULL); } attr = xmlSchemaGetPropNode(node, "name"); if (attr == NULL) { xmlSchemaPMissingAttrErr(pctxt, XML_SCHEMAP_S4S_ATTR_MISSING, NULL, node, "name", NULL); return (NULL); } if (xmlSchemaPValAttrNode(pctxt, NULL, attr, xmlSchemaGetBuiltInType(XML_SCHEMAS_NCNAME), &name) != 0) { return (NULL); } /* * 3.2.6 Schema Component Constraint: xmlns Not Allowed * TODO: Move this to the component layer. */ if (xmlStrEqual(name, BAD_CAST "xmlns")) { xmlSchemaPSimpleTypeErr(pctxt, XML_SCHEMAP_NO_XMLNS, NULL, (xmlNodePtr) attr, xmlSchemaGetBuiltInType(XML_SCHEMAS_NCNAME), NULL, NULL, "The value of the attribute must not match 'xmlns'", NULL, NULL); return (NULL); } if (occurs == XML_SCHEMAS_ATTR_USE_PROHIBITED) goto check_children; /* * Create the attribute use component. */ use = xmlSchemaAddAttributeUse(pctxt, node); if (use == NULL) return(NULL); use->occurs = occurs; /* * Create the attribute declaration. */ attrDecl = xmlSchemaAddAttribute(pctxt, schema, name, ns, node, 0); if (attrDecl == NULL) return (NULL); if (tmpName != NULL) { attrDecl->typeName = tmpName; attrDecl->typeNs = tmpNs; } use->attrDecl = attrDecl; /* * Value constraint. */ if (defValue != NULL) { attrDecl->defValue = defValue; if (defValueType == WXS_ATTR_DEF_VAL_FIXED) attrDecl->flags |= XML_SCHEMAS_ATTR_FIXED; } } else if (occurs != XML_SCHEMAS_ATTR_USE_PROHIBITED) { xmlSchemaQNameRefPtr ref; /* * Create the attribute use component. */ use = xmlSchemaAddAttributeUse(pctxt, node); if (use == NULL) return(NULL); /* * We need to resolve the reference at later stage. */ WXS_ADD_PENDING(pctxt, use); use->occurs = occurs; /* * Create a QName reference to the attribute declaration. */ ref = xmlSchemaNewQNameRef(pctxt, XML_SCHEMA_TYPE_ATTRIBUTE, tmpName, tmpNs); if (ref == NULL) return(NULL); /* * Assign the reference. This will be substituted for the * referenced attribute declaration when the QName is resolved. */ use->attrDecl = WXS_ATTR_CAST ref; /* * Value constraint. */ if (defValue != NULL) use->defValue = defValue; if (defValueType == WXS_ATTR_DEF_VAL_FIXED) use->flags |= XML_SCHEMA_ATTR_USE_FIXED; } check_children: /* * And now for the children... */ child = node->children; if (occurs == XML_SCHEMAS_ATTR_USE_PROHIBITED) { xmlSchemaAttributeUseProhibPtr prohib; if (IS_SCHEMA(child, "annotation")) { xmlSchemaParseAnnotation(pctxt, child, 0); child = child->next; } if (child != NULL) { xmlSchemaPContentErr(pctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?)"); } /* * Check for pointlessness of attribute prohibitions. */ if (parentType == XML_SCHEMA_TYPE_ATTRIBUTEGROUP) { xmlSchemaCustomWarning(ACTXT_CAST pctxt, XML_SCHEMAP_WARN_ATTR_POINTLESS_PROH, node, NULL, "Skipping attribute use prohibition, since it is " "pointless inside an <attributeGroup>", NULL, NULL, NULL); return(NULL); } else if (parentType == XML_SCHEMA_TYPE_EXTENSION) { xmlSchemaCustomWarning(ACTXT_CAST pctxt, XML_SCHEMAP_WARN_ATTR_POINTLESS_PROH, node, NULL, "Skipping attribute use prohibition, since it is " "pointless when extending a type", NULL, NULL, NULL); return(NULL); } if (! isRef) { tmpName = name; tmpNs = ns; } /* * Check for duplicate attribute prohibitions. */ if (uses) { int i; for (i = 0; i < uses->nbItems; i++) { use = uses->items[i]; if ((use->type == XML_SCHEMA_EXTRA_ATTR_USE_PROHIB) && (tmpName == (WXS_ATTR_PROHIB_CAST use)->name) && (tmpNs == (WXS_ATTR_PROHIB_CAST use)->targetNamespace)) { xmlChar *str = NULL; xmlSchemaCustomWarning(ACTXT_CAST pctxt, XML_SCHEMAP_WARN_ATTR_POINTLESS_PROH, node, NULL, "Skipping duplicate attribute use prohibition '%s'", xmlSchemaFormatQName(&str, tmpNs, tmpName), NULL, NULL); FREE_AND_NULL(str) return(NULL); } } } /* * Create the attribute prohibition helper component. */ prohib = xmlSchemaAddAttributeUseProhib(pctxt); if (prohib == NULL) return(NULL); prohib->node = node; prohib->name = tmpName; prohib->targetNamespace = tmpNs; if (isRef) { /* * We need at least to resolve to the attribute declaration. */ WXS_ADD_PENDING(pctxt, prohib); } return(WXS_BASIC_CAST prohib); } else { if (IS_SCHEMA(child, "annotation")) { /* * TODO: Should this go into the attr decl? */ use->annot = xmlSchemaParseAnnotation(pctxt, child, 1); child = child->next; } if (isRef) { if (child != NULL) { if (IS_SCHEMA(child, "simpleType")) /* * 3.2.3 : 3.2 * If ref is present, then all of <simpleType>, * form and type must be absent. */ xmlSchemaPContentErr(pctxt, XML_SCHEMAP_SRC_ATTRIBUTE_3_2, NULL, node, child, NULL, "(annotation?)"); else xmlSchemaPContentErr(pctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?)"); } } else { if (IS_SCHEMA(child, "simpleType")) { if (WXS_ATTRUSE_DECL(use)->typeName != NULL) { /* * 3.2.3 : 4 * type and <simpleType> must not both be present. */ xmlSchemaPContentErr(pctxt, XML_SCHEMAP_SRC_ATTRIBUTE_4, NULL, node, child, "The attribute 'type' and the <simpleType> child " "are mutually exclusive", NULL); } else WXS_ATTRUSE_TYPEDEF(use) = xmlSchemaParseSimpleType(pctxt, schema, child, 0); child = child->next; } if (child != NULL) xmlSchemaPContentErr(pctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?, simpleType?)"); } } return (WXS_BASIC_CAST use); } static xmlSchemaAttributePtr xmlSchemaParseGlobalAttribute(xmlSchemaParserCtxtPtr pctxt, xmlSchemaPtr schema, xmlNodePtr node) { const xmlChar *attrValue; xmlSchemaAttributePtr ret; xmlNodePtr child = NULL; xmlAttrPtr attr; /* * Note that the w3c spec assumes the schema to be validated with schema * for schemas beforehand. * * 3.2.3 Constraints on XML Representations of Attribute Declarations */ if ((pctxt == NULL) || (schema == NULL) || (node == NULL)) return (NULL); /* * 3.2.3 : 3.1 * One of ref or name must be present, but not both */ attr = xmlSchemaGetPropNode(node, "name"); if (attr == NULL) { xmlSchemaPMissingAttrErr(pctxt, XML_SCHEMAP_S4S_ATTR_MISSING, NULL, node, "name", NULL); return (NULL); } if (xmlSchemaPValAttrNode(pctxt, NULL, attr, xmlSchemaGetBuiltInType(XML_SCHEMAS_NCNAME), &attrValue) != 0) { return (NULL); } /* * 3.2.6 Schema Component Constraint: xmlns Not Allowed * TODO: Move this to the component layer. */ if (xmlStrEqual(attrValue, BAD_CAST "xmlns")) { xmlSchemaPSimpleTypeErr(pctxt, XML_SCHEMAP_NO_XMLNS, NULL, (xmlNodePtr) attr, xmlSchemaGetBuiltInType(XML_SCHEMAS_NCNAME), NULL, NULL, "The value of the attribute must not match 'xmlns'", NULL, NULL); return (NULL); } /* * 3.2.6 Schema Component Constraint: xsi: Not Allowed * TODO: Move this to the component layer. * Or better leave it here and add it to the component layer * if we have a schema construction API. */ if (xmlStrEqual(pctxt->targetNamespace, xmlSchemaInstanceNs)) { xmlSchemaCustomErr(ACTXT_CAST pctxt, XML_SCHEMAP_NO_XSI, node, NULL, "The target namespace must not match '%s'", xmlSchemaInstanceNs, NULL); } ret = xmlSchemaAddAttribute(pctxt, schema, attrValue, pctxt->targetNamespace, node, 1); if (ret == NULL) return (NULL); ret->flags |= XML_SCHEMAS_ATTR_GLOBAL; /* * Check for illegal attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if ((!xmlStrEqual(attr->name, BAD_CAST "id")) && (!xmlStrEqual(attr->name, BAD_CAST "default")) && (!xmlStrEqual(attr->name, BAD_CAST "fixed")) && (!xmlStrEqual(attr->name, BAD_CAST "name")) && (!xmlStrEqual(attr->name, BAD_CAST "type"))) { xmlSchemaPIllegalAttrErr(pctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(pctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } xmlSchemaPValAttrQName(pctxt, schema, NULL, node, "type", &ret->typeNs, &ret->typeName); xmlSchemaPValAttrID(pctxt, node, BAD_CAST "id"); /* * Attribute "fixed". */ ret->defValue = xmlSchemaGetProp(pctxt, node, "fixed"); if (ret->defValue != NULL) ret->flags |= XML_SCHEMAS_ATTR_FIXED; /* * Attribute "default". */ attr = xmlSchemaGetPropNode(node, "default"); if (attr != NULL) { /* * 3.2.3 : 1 * default and fixed must not both be present. */ if (ret->flags & XML_SCHEMAS_ATTR_FIXED) { xmlSchemaPMutualExclAttrErr(pctxt, XML_SCHEMAP_SRC_ATTRIBUTE_1, WXS_BASIC_CAST ret, attr, "default", "fixed"); } else ret->defValue = xmlSchemaGetNodeContent(pctxt, (xmlNodePtr) attr); } /* * And now for the children... */ child = node->children; if (IS_SCHEMA(child, "annotation")) { ret->annot = xmlSchemaParseAnnotation(pctxt, child, 1); child = child->next; } if (IS_SCHEMA(child, "simpleType")) { if (ret->typeName != NULL) { /* * 3.2.3 : 4 * type and <simpleType> must not both be present. */ xmlSchemaPContentErr(pctxt, XML_SCHEMAP_SRC_ATTRIBUTE_4, NULL, node, child, "The attribute 'type' and the <simpleType> child " "are mutually exclusive", NULL); } else ret->subtypes = xmlSchemaParseSimpleType(pctxt, schema, child, 0); child = child->next; } if (child != NULL) xmlSchemaPContentErr(pctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?, simpleType?)"); return (ret); } /** * xmlSchemaParseAttributeGroupRef: * @ctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * * Parse an attribute group definition reference. * Note that a reference to an attribute group does not * correspond to any component at all. * *WARNING* this interface is highly subject to change * * Returns the attribute group or NULL in case of error. */ static xmlSchemaQNameRefPtr xmlSchemaParseAttributeGroupRef(xmlSchemaParserCtxtPtr pctxt, xmlSchemaPtr schema, xmlNodePtr node) { xmlSchemaQNameRefPtr ret; xmlNodePtr child = NULL; xmlAttrPtr attr; const xmlChar *refNs = NULL, *ref = NULL; if ((pctxt == NULL) || (schema == NULL) || (node == NULL)) return (NULL); attr = xmlSchemaGetPropNode(node, "ref"); if (attr == NULL) { xmlSchemaPMissingAttrErr(pctxt, XML_SCHEMAP_S4S_ATTR_MISSING, NULL, node, "ref", NULL); return (NULL); } xmlSchemaPValAttrNodeQName(pctxt, schema, NULL, attr, &refNs, &ref); if (xmlSchemaCheckReference(pctxt, schema, node, attr, refNs) != 0) return(NULL); /* * Check for illegal attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if ((!xmlStrEqual(attr->name, BAD_CAST "ref")) && (!xmlStrEqual(attr->name, BAD_CAST "id"))) { xmlSchemaPIllegalAttrErr(pctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(pctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } /* Attribute ID */ xmlSchemaPValAttrID(pctxt, node, BAD_CAST "id"); /* * And now for the children... */ child = node->children; if (IS_SCHEMA(child, "annotation")) { /* * TODO: We do not have a place to store the annotation, do we? */ xmlSchemaParseAnnotation(pctxt, child, 0); child = child->next; } if (child != NULL) { xmlSchemaPContentErr(pctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?)"); } /* * Handle attribute group redefinitions. */ if (pctxt->isRedefine && pctxt->redef && (pctxt->redef->item->type == XML_SCHEMA_TYPE_ATTRIBUTEGROUP) && (ref == pctxt->redef->refName) && (refNs == pctxt->redef->refTargetNs)) { /* * SPEC src-redefine: * (7.1) "If it has an <attributeGroup> among its contents * the `actual value` of whose ref [attribute] is the same * as the `actual value` of its own name attribute plus * target namespace, then it must have exactly one such group." */ if (pctxt->redefCounter != 0) { xmlChar *str = NULL; xmlSchemaCustomErr(ACTXT_CAST pctxt, XML_SCHEMAP_SRC_REDEFINE, node, NULL, "The redefining attribute group definition " "'%s' must not contain more than one " "reference to the redefined definition", xmlSchemaFormatQName(&str, refNs, ref), NULL); FREE_AND_NULL(str); return(NULL); } pctxt->redefCounter++; /* * URGENT TODO: How to ensure that the reference will not be * handled by the normal component resolution mechanism? */ ret = xmlSchemaNewQNameRef(pctxt, XML_SCHEMA_TYPE_ATTRIBUTEGROUP, ref, refNs); if (ret == NULL) return(NULL); ret->node = node; pctxt->redef->reference = WXS_BASIC_CAST ret; } else { /* * Create a QName-reference helper component. We will substitute this * component for the attribute uses of the referenced attribute group * definition. */ ret = xmlSchemaNewQNameRef(pctxt, XML_SCHEMA_TYPE_ATTRIBUTEGROUP, ref, refNs); if (ret == NULL) return(NULL); ret->node = node; /* Add to pending items, to be able to resolve the reference. */ WXS_ADD_PENDING(pctxt, ret); } return (ret); } /** * xmlSchemaParseAttributeGroupDefinition: * @pctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * * parse a XML schema Attribute Group declaration * *WARNING* this interface is highly subject to change * * Returns the attribute group definition or NULL in case of error. */ static xmlSchemaAttributeGroupPtr xmlSchemaParseAttributeGroupDefinition(xmlSchemaParserCtxtPtr pctxt, xmlSchemaPtr schema, xmlNodePtr node) { const xmlChar *name; xmlSchemaAttributeGroupPtr ret; xmlNodePtr child = NULL; xmlAttrPtr attr; int hasRefs = 0; if ((pctxt == NULL) || (schema == NULL) || (node == NULL)) return (NULL); attr = xmlSchemaGetPropNode(node, "name"); if (attr == NULL) { xmlSchemaPMissingAttrErr(pctxt, XML_SCHEMAP_S4S_ATTR_MISSING, NULL, node, "name", NULL); return (NULL); } /* * The name is crucial, exit if invalid. */ if (xmlSchemaPValAttrNode(pctxt, NULL, attr, xmlSchemaGetBuiltInType(XML_SCHEMAS_NCNAME), &name) != 0) { return (NULL); } ret = xmlSchemaAddAttributeGroupDefinition(pctxt, schema, name, pctxt->targetNamespace, node); if (ret == NULL) return (NULL); /* * Check for illegal attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if ((!xmlStrEqual(attr->name, BAD_CAST "name")) && (!xmlStrEqual(attr->name, BAD_CAST "id"))) { xmlSchemaPIllegalAttrErr(pctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(pctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } /* Attribute ID */ xmlSchemaPValAttrID(pctxt, node, BAD_CAST "id"); /* * And now for the children... */ child = node->children; if (IS_SCHEMA(child, "annotation")) { ret->annot = xmlSchemaParseAnnotation(pctxt, child, 1); child = child->next; } /* * Parse contained attribute decls/refs. */ if (xmlSchemaParseLocalAttributes(pctxt, schema, &child, (xmlSchemaItemListPtr *) &(ret->attrUses), XML_SCHEMA_TYPE_ATTRIBUTEGROUP, &hasRefs) == -1) return(NULL); if (hasRefs) ret->flags |= XML_SCHEMAS_ATTRGROUP_HAS_REFS; /* * Parse the attribute wildcard. */ if (IS_SCHEMA(child, "anyAttribute")) { ret->attributeWildcard = xmlSchemaParseAnyAttribute(pctxt, schema, child); child = child->next; } if (child != NULL) { xmlSchemaPContentErr(pctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?, ((attribute | attributeGroup)*, anyAttribute?))"); } return (ret); } /** * xmlSchemaPValAttrFormDefault: * @value: the value * @flags: the flags to be modified * @flagQualified: the specific flag for "qualified" * * Returns 0 if the value is valid, 1 otherwise. */ static int xmlSchemaPValAttrFormDefault(const xmlChar *value, int *flags, int flagQualified) { if (xmlStrEqual(value, BAD_CAST "qualified")) { if ((*flags & flagQualified) == 0) *flags |= flagQualified; } else if (!xmlStrEqual(value, BAD_CAST "unqualified")) return (1); return (0); } /** * xmlSchemaPValAttrBlockFinal: * @value: the value * @flags: the flags to be modified * @flagAll: the specific flag for "#all" * @flagExtension: the specific flag for "extension" * @flagRestriction: the specific flag for "restriction" * @flagSubstitution: the specific flag for "substitution" * @flagList: the specific flag for "list" * @flagUnion: the specific flag for "union" * * Validates the value of the attribute "final" and "block". The value * is converted into the specified flag values and returned in @flags. * * Returns 0 if the value is valid, 1 otherwise. */ static int xmlSchemaPValAttrBlockFinal(const xmlChar *value, int *flags, int flagAll, int flagExtension, int flagRestriction, int flagSubstitution, int flagList, int flagUnion) { int ret = 0; /* * TODO: This does not check for duplicate entries. */ if ((flags == NULL) || (value == NULL)) return (-1); if (value[0] == 0) return (0); if (xmlStrEqual(value, BAD_CAST "#all")) { if (flagAll != -1) *flags |= flagAll; else { if (flagExtension != -1) *flags |= flagExtension; if (flagRestriction != -1) *flags |= flagRestriction; if (flagSubstitution != -1) *flags |= flagSubstitution; if (flagList != -1) *flags |= flagList; if (flagUnion != -1) *flags |= flagUnion; } } else { const xmlChar *end, *cur = value; xmlChar *item; do { while (IS_BLANK_CH(*cur)) cur++; end = cur; while ((*end != 0) && (!(IS_BLANK_CH(*end)))) end++; if (end == cur) break; item = xmlStrndup(cur, end - cur); if (xmlStrEqual(item, BAD_CAST "extension")) { if (flagExtension != -1) { if ((*flags & flagExtension) == 0) *flags |= flagExtension; } else ret = 1; } else if (xmlStrEqual(item, BAD_CAST "restriction")) { if (flagRestriction != -1) { if ((*flags & flagRestriction) == 0) *flags |= flagRestriction; } else ret = 1; } else if (xmlStrEqual(item, BAD_CAST "substitution")) { if (flagSubstitution != -1) { if ((*flags & flagSubstitution) == 0) *flags |= flagSubstitution; } else ret = 1; } else if (xmlStrEqual(item, BAD_CAST "list")) { if (flagList != -1) { if ((*flags & flagList) == 0) *flags |= flagList; } else ret = 1; } else if (xmlStrEqual(item, BAD_CAST "union")) { if (flagUnion != -1) { if ((*flags & flagUnion) == 0) *flags |= flagUnion; } else ret = 1; } else ret = 1; if (item != NULL) xmlFree(item); cur = end; } while ((ret == 0) && (*cur != 0)); } return (ret); } static int xmlSchemaCheckCSelectorXPath(xmlSchemaParserCtxtPtr ctxt, xmlSchemaIDCPtr idc, xmlSchemaIDCSelectPtr selector, xmlAttrPtr attr, int isField) { xmlNodePtr node; /* * c-selector-xpath: * Schema Component Constraint: Selector Value OK * * TODO: 1 The {selector} must be a valid XPath expression, as defined * in [XPath]. */ if (selector == NULL) { xmlSchemaPErr(ctxt, idc->node, XML_SCHEMAP_INTERNAL, "Internal error: xmlSchemaCheckCSelectorXPath, " "the selector is not specified.\n", NULL, NULL); return (-1); } if (attr == NULL) node = idc->node; else node = (xmlNodePtr) attr; if (selector->xpath == NULL) { xmlSchemaPCustomErr(ctxt, /* TODO: Adjust error code. */ XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, NULL, node, "The XPath expression of the selector is not valid", NULL); return (XML_SCHEMAP_S4S_ATTR_INVALID_VALUE); } else { const xmlChar **nsArray = NULL; xmlNsPtr *nsList = NULL; /* * Compile the XPath expression. */ /* * TODO: We need the array of in-scope namespaces for compilation. * TODO: Call xmlPatterncompile with different options for selector/ * field. */ if (attr == NULL) nsList = NULL; else nsList = xmlGetNsList(attr->doc, attr->parent); /* * Build an array of prefixes and namespaces. */ if (nsList != NULL) { int i, count = 0; for (i = 0; nsList[i] != NULL; i++) count++; nsArray = (const xmlChar **) xmlMalloc( (count * 2 + 1) * sizeof(const xmlChar *)); if (nsArray == NULL) { xmlSchemaPErrMemory(ctxt, "allocating a namespace array", NULL); xmlFree(nsList); return (-1); } for (i = 0; i < count; i++) { nsArray[2 * i] = nsList[i]->href; nsArray[2 * i + 1] = nsList[i]->prefix; } nsArray[count * 2] = NULL; xmlFree(nsList); } /* * TODO: Differentiate between "selector" and "field". */ if (isField) selector->xpathComp = (void *) xmlPatterncompile(selector->xpath, NULL, XML_PATTERN_XSFIELD, nsArray); else selector->xpathComp = (void *) xmlPatterncompile(selector->xpath, NULL, XML_PATTERN_XSSEL, nsArray); if (nsArray != NULL) xmlFree((xmlChar **) nsArray); if (selector->xpathComp == NULL) { xmlSchemaPCustomErr(ctxt, /* TODO: Adjust error code? */ XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, NULL, node, "The XPath expression '%s' could not be " "compiled", selector->xpath); return (XML_SCHEMAP_S4S_ATTR_INVALID_VALUE); } } return (0); } #define ADD_ANNOTATION(annot) \ xmlSchemaAnnotPtr cur = item->annot; \ if (item->annot == NULL) { \ item->annot = annot; \ return (annot); \ } \ cur = item->annot; \ if (cur->next != NULL) { \ cur = cur->next; \ } \ cur->next = annot; /** * xmlSchemaAssignAnnotation: * @item: the schema component * @annot: the annotation * * Adds the annotation to the given schema component. * * Returns the given annotation. */ static xmlSchemaAnnotPtr xmlSchemaAddAnnotation(xmlSchemaAnnotItemPtr annItem, xmlSchemaAnnotPtr annot) { if ((annItem == NULL) || (annot == NULL)) return (NULL); switch (annItem->type) { case XML_SCHEMA_TYPE_ELEMENT: { xmlSchemaElementPtr item = (xmlSchemaElementPtr) annItem; ADD_ANNOTATION(annot) } break; case XML_SCHEMA_TYPE_ATTRIBUTE: { xmlSchemaAttributePtr item = (xmlSchemaAttributePtr) annItem; ADD_ANNOTATION(annot) } break; case XML_SCHEMA_TYPE_ANY_ATTRIBUTE: case XML_SCHEMA_TYPE_ANY: { xmlSchemaWildcardPtr item = (xmlSchemaWildcardPtr) annItem; ADD_ANNOTATION(annot) } break; case XML_SCHEMA_TYPE_PARTICLE: case XML_SCHEMA_TYPE_IDC_KEY: case XML_SCHEMA_TYPE_IDC_KEYREF: case XML_SCHEMA_TYPE_IDC_UNIQUE: { xmlSchemaAnnotItemPtr item = (xmlSchemaAnnotItemPtr) annItem; ADD_ANNOTATION(annot) } break; case XML_SCHEMA_TYPE_ATTRIBUTEGROUP: { xmlSchemaAttributeGroupPtr item = (xmlSchemaAttributeGroupPtr) annItem; ADD_ANNOTATION(annot) } break; case XML_SCHEMA_TYPE_NOTATION: { xmlSchemaNotationPtr item = (xmlSchemaNotationPtr) annItem; ADD_ANNOTATION(annot) } break; case XML_SCHEMA_FACET_MININCLUSIVE: case XML_SCHEMA_FACET_MINEXCLUSIVE: case XML_SCHEMA_FACET_MAXINCLUSIVE: case XML_SCHEMA_FACET_MAXEXCLUSIVE: case XML_SCHEMA_FACET_TOTALDIGITS: case XML_SCHEMA_FACET_FRACTIONDIGITS: case XML_SCHEMA_FACET_PATTERN: case XML_SCHEMA_FACET_ENUMERATION: case XML_SCHEMA_FACET_WHITESPACE: case XML_SCHEMA_FACET_LENGTH: case XML_SCHEMA_FACET_MAXLENGTH: case XML_SCHEMA_FACET_MINLENGTH: { xmlSchemaFacetPtr item = (xmlSchemaFacetPtr) annItem; ADD_ANNOTATION(annot) } break; case XML_SCHEMA_TYPE_SIMPLE: case XML_SCHEMA_TYPE_COMPLEX: { xmlSchemaTypePtr item = (xmlSchemaTypePtr) annItem; ADD_ANNOTATION(annot) } break; case XML_SCHEMA_TYPE_GROUP: { xmlSchemaModelGroupDefPtr item = (xmlSchemaModelGroupDefPtr) annItem; ADD_ANNOTATION(annot) } break; case XML_SCHEMA_TYPE_SEQUENCE: case XML_SCHEMA_TYPE_CHOICE: case XML_SCHEMA_TYPE_ALL: { xmlSchemaModelGroupPtr item = (xmlSchemaModelGroupPtr) annItem; ADD_ANNOTATION(annot) } break; default: xmlSchemaPCustomErr(NULL, XML_SCHEMAP_INTERNAL, NULL, NULL, "Internal error: xmlSchemaAddAnnotation, " "The item is not a annotated schema component", NULL); break; } return (annot); } /** * xmlSchemaParseIDCSelectorAndField: * @ctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * * Parses a XML Schema identity-constraint definition's * <selector> and <field> elements. * * Returns the parsed identity-constraint definition. */ static xmlSchemaIDCSelectPtr xmlSchemaParseIDCSelectorAndField(xmlSchemaParserCtxtPtr ctxt, xmlSchemaIDCPtr idc, xmlNodePtr node, int isField) { xmlSchemaIDCSelectPtr item; xmlNodePtr child = NULL; xmlAttrPtr attr; /* * Check for illegal attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if ((!xmlStrEqual(attr->name, BAD_CAST "id")) && (!xmlStrEqual(attr->name, BAD_CAST "xpath"))) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } /* * Create the item. */ item = (xmlSchemaIDCSelectPtr) xmlMalloc(sizeof(xmlSchemaIDCSelect)); if (item == NULL) { xmlSchemaPErrMemory(ctxt, "allocating a 'selector' of an identity-constraint definition", NULL); return (NULL); } memset(item, 0, sizeof(xmlSchemaIDCSelect)); /* * Attribute "xpath" (mandatory). */ attr = xmlSchemaGetPropNode(node, "xpath"); if (attr == NULL) { xmlSchemaPMissingAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_MISSING, NULL, node, "name", NULL); } else { item->xpath = xmlSchemaGetNodeContent(ctxt, (xmlNodePtr) attr); /* * URGENT TODO: "field"s have an other syntax than "selector"s. */ if (xmlSchemaCheckCSelectorXPath(ctxt, idc, item, attr, isField) == -1) { xmlSchemaPErr(ctxt, (xmlNodePtr) attr, XML_SCHEMAP_INTERNAL, "Internal error: xmlSchemaParseIDCSelectorAndField, " "validating the XPath expression of a IDC selector.\n", NULL, NULL); } } xmlSchemaPValAttrID(ctxt, node, BAD_CAST "id"); /* * And now for the children... */ child = node->children; if (IS_SCHEMA(child, "annotation")) { /* * Add the annotation to the parent IDC. */ xmlSchemaAddAnnotation((xmlSchemaAnnotItemPtr) idc, xmlSchemaParseAnnotation(ctxt, child, 1)); child = child->next; } if (child != NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?)"); } return (item); } /** * xmlSchemaParseIDC: * @ctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * * Parses a XML Schema identity-constraint definition. * * Returns the parsed identity-constraint definition. */ static xmlSchemaIDCPtr xmlSchemaParseIDC(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node, xmlSchemaTypeType idcCategory, const xmlChar *targetNamespace) { xmlSchemaIDCPtr item = NULL; xmlNodePtr child = NULL; xmlAttrPtr attr; const xmlChar *name = NULL; xmlSchemaIDCSelectPtr field = NULL, lastField = NULL; /* * Check for illegal attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if ((!xmlStrEqual(attr->name, BAD_CAST "id")) && (!xmlStrEqual(attr->name, BAD_CAST "name")) && ((idcCategory != XML_SCHEMA_TYPE_IDC_KEYREF) || (!xmlStrEqual(attr->name, BAD_CAST "refer")))) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } /* * Attribute "name" (mandatory). */ attr = xmlSchemaGetPropNode(node, "name"); if (attr == NULL) { xmlSchemaPMissingAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_MISSING, NULL, node, "name", NULL); return (NULL); } else if (xmlSchemaPValAttrNode(ctxt, NULL, attr, xmlSchemaGetBuiltInType(XML_SCHEMAS_NCNAME), &name) != 0) { return (NULL); } /* Create the component. */ item = xmlSchemaAddIDC(ctxt, schema, name, targetNamespace, idcCategory, node); if (item == NULL) return(NULL); xmlSchemaPValAttrID(ctxt, node, BAD_CAST "id"); if (idcCategory == XML_SCHEMA_TYPE_IDC_KEYREF) { /* * Attribute "refer" (mandatory). */ attr = xmlSchemaGetPropNode(node, "refer"); if (attr == NULL) { xmlSchemaPMissingAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_MISSING, NULL, node, "refer", NULL); } else { /* * Create a reference item. */ item->ref = xmlSchemaNewQNameRef(ctxt, XML_SCHEMA_TYPE_IDC_KEY, NULL, NULL); if (item->ref == NULL) return (NULL); xmlSchemaPValAttrNodeQName(ctxt, schema, NULL, attr, &(item->ref->targetNamespace), &(item->ref->name)); xmlSchemaCheckReference(ctxt, schema, node, attr, item->ref->targetNamespace); } } /* * And now for the children... */ child = node->children; if (IS_SCHEMA(child, "annotation")) { item->annot = xmlSchemaParseAnnotation(ctxt, child, 1); child = child->next; } if (child == NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_MISSING, NULL, node, child, "A child element is missing", "(annotation?, (selector, field+))"); } /* * Child element <selector>. */ if (IS_SCHEMA(child, "selector")) { item->selector = xmlSchemaParseIDCSelectorAndField(ctxt, item, child, 0); child = child->next; /* * Child elements <field>. */ if (IS_SCHEMA(child, "field")) { do { field = xmlSchemaParseIDCSelectorAndField(ctxt, item, child, 1); if (field != NULL) { field->index = item->nbFields; item->nbFields++; if (lastField != NULL) lastField->next = field; else item->fields = field; lastField = field; } child = child->next; } while (IS_SCHEMA(child, "field")); } else { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?, (selector, field+))"); } } if (child != NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?, (selector, field+))"); } return (item); } /** * xmlSchemaParseElement: * @ctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * @topLevel: indicates if this is global declaration * * Parses a XML schema element declaration. * *WARNING* this interface is highly subject to change * * Returns the element declaration or a particle; NULL in case * of an error or if the particle has minOccurs==maxOccurs==0. */ static xmlSchemaBasicItemPtr xmlSchemaParseElement(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node, int *isElemRef, int topLevel) { xmlSchemaElementPtr decl = NULL; xmlSchemaParticlePtr particle = NULL; xmlSchemaAnnotPtr annot = NULL; xmlNodePtr child = NULL; xmlAttrPtr attr, nameAttr; int min, max, isRef = 0; xmlChar *des = NULL; /* 3.3.3 Constraints on XML Representations of Element Declarations */ /* TODO: Complete implementation of 3.3.6 */ if ((ctxt == NULL) || (schema == NULL) || (node == NULL)) return (NULL); if (isElemRef != NULL) *isElemRef = 0; /* * If we get a "ref" attribute on a local <element> we will assume it's * a reference - even if there's a "name" attribute; this seems to be more * robust. */ nameAttr = xmlSchemaGetPropNode(node, "name"); attr = xmlSchemaGetPropNode(node, "ref"); if ((topLevel) || (attr == NULL)) { if (nameAttr == NULL) { xmlSchemaPMissingAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_MISSING, NULL, node, "name", NULL); return (NULL); } } else isRef = 1; xmlSchemaPValAttrID(ctxt, node, BAD_CAST "id"); child = node->children; if (IS_SCHEMA(child, "annotation")) { annot = xmlSchemaParseAnnotation(ctxt, child, 1); child = child->next; } /* * Skip particle part if a global declaration. */ if (topLevel) goto declaration_part; /* * The particle part ================================================== */ min = xmlGetMinOccurs(ctxt, node, 0, -1, 1, "xs:nonNegativeInteger"); max = xmlGetMaxOccurs(ctxt, node, 0, UNBOUNDED, 1, "(xs:nonNegativeInteger | unbounded)"); xmlSchemaPCheckParticleCorrect_2(ctxt, NULL, node, min, max); particle = xmlSchemaAddParticle(ctxt, node, min, max); if (particle == NULL) goto return_null; /* ret->flags |= XML_SCHEMAS_ELEM_REF; */ if (isRef) { const xmlChar *refNs = NULL, *ref = NULL; xmlSchemaQNameRefPtr refer = NULL; /* * The reference part ============================================= */ if (isElemRef != NULL) *isElemRef = 1; xmlSchemaPValAttrNodeQName(ctxt, schema, NULL, attr, &refNs, &ref); xmlSchemaCheckReference(ctxt, schema, node, attr, refNs); /* * SPEC (3.3.3 : 2.1) "One of ref or name must be present, but not both" */ if (nameAttr != NULL) { xmlSchemaPMutualExclAttrErr(ctxt, XML_SCHEMAP_SRC_ELEMENT_2_1, NULL, nameAttr, "ref", "name"); } /* * Check for illegal attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if (xmlStrEqual(attr->name, BAD_CAST "ref") || xmlStrEqual(attr->name, BAD_CAST "name") || xmlStrEqual(attr->name, BAD_CAST "id") || xmlStrEqual(attr->name, BAD_CAST "maxOccurs") || xmlStrEqual(attr->name, BAD_CAST "minOccurs")) { attr = attr->next; continue; } else { /* SPEC (3.3.3 : 2.2) */ xmlSchemaPCustomAttrErr(ctxt, XML_SCHEMAP_SRC_ELEMENT_2_2, NULL, NULL, attr, "Only the attributes 'minOccurs', 'maxOccurs' and " "'id' are allowed in addition to 'ref'"); break; } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } /* * No children except <annotation> expected. */ if (child != NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?)"); } if ((min == 0) && (max == 0)) goto return_null; /* * Create the reference item and attach it to the particle. */ refer = xmlSchemaNewQNameRef(ctxt, XML_SCHEMA_TYPE_ELEMENT, ref, refNs); if (refer == NULL) goto return_null; particle->children = (xmlSchemaTreeItemPtr) refer; particle->annot = annot; /* * Add the particle to pending components, since the reference * need to be resolved. */ WXS_ADD_PENDING(ctxt, particle); return ((xmlSchemaBasicItemPtr) particle); } /* * The declaration part =============================================== */ declaration_part: { const xmlChar *ns = NULL, *fixed, *name, *attrValue; xmlSchemaIDCPtr curIDC = NULL, lastIDC = NULL; if (xmlSchemaPValAttrNode(ctxt, NULL, nameAttr, xmlSchemaGetBuiltInType(XML_SCHEMAS_NCNAME), &name) != 0) goto return_null; /* * Evaluate the target namespace. */ if (topLevel) { ns = ctxt->targetNamespace; } else { attr = xmlSchemaGetPropNode(node, "form"); if (attr != NULL) { attrValue = xmlSchemaGetNodeContent(ctxt, (xmlNodePtr) attr); if (xmlStrEqual(attrValue, BAD_CAST "qualified")) { ns = ctxt->targetNamespace; } else if (!xmlStrEqual(attrValue, BAD_CAST "unqualified")) { xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, NULL, (xmlNodePtr) attr, NULL, "(qualified | unqualified)", attrValue, NULL, NULL, NULL); } } else if (schema->flags & XML_SCHEMAS_QUALIF_ELEM) ns = ctxt->targetNamespace; } decl = xmlSchemaAddElement(ctxt, name, ns, node, topLevel); if (decl == NULL) { goto return_null; } /* * Check for illegal attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if ((!xmlStrEqual(attr->name, BAD_CAST "name")) && (!xmlStrEqual(attr->name, BAD_CAST "type")) && (!xmlStrEqual(attr->name, BAD_CAST "id")) && (!xmlStrEqual(attr->name, BAD_CAST "default")) && (!xmlStrEqual(attr->name, BAD_CAST "fixed")) && (!xmlStrEqual(attr->name, BAD_CAST "block")) && (!xmlStrEqual(attr->name, BAD_CAST "nillable"))) { if (topLevel == 0) { if ((!xmlStrEqual(attr->name, BAD_CAST "maxOccurs")) && (!xmlStrEqual(attr->name, BAD_CAST "minOccurs")) && (!xmlStrEqual(attr->name, BAD_CAST "form"))) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else if ((!xmlStrEqual(attr->name, BAD_CAST "final")) && (!xmlStrEqual(attr->name, BAD_CAST "abstract")) && (!xmlStrEqual(attr->name, BAD_CAST "substitutionGroup"))) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } /* * Extract/validate attributes. */ if (topLevel) { /* * Process top attributes of global element declarations here. */ decl->flags |= XML_SCHEMAS_ELEM_GLOBAL; decl->flags |= XML_SCHEMAS_ELEM_TOPLEVEL; xmlSchemaPValAttrQName(ctxt, schema, NULL, node, "substitutionGroup", &(decl->substGroupNs), &(decl->substGroup)); if (xmlGetBooleanProp(ctxt, node, "abstract", 0)) decl->flags |= XML_SCHEMAS_ELEM_ABSTRACT; /* * Attribute "final". */ attr = xmlSchemaGetPropNode(node, "final"); if (attr == NULL) { if (schema->flags & XML_SCHEMAS_FINAL_DEFAULT_EXTENSION) decl->flags |= XML_SCHEMAS_ELEM_FINAL_EXTENSION; if (schema->flags & XML_SCHEMAS_FINAL_DEFAULT_RESTRICTION) decl->flags |= XML_SCHEMAS_ELEM_FINAL_RESTRICTION; } else { attrValue = xmlSchemaGetNodeContent(ctxt, (xmlNodePtr) attr); if (xmlSchemaPValAttrBlockFinal(attrValue, &(decl->flags), -1, XML_SCHEMAS_ELEM_FINAL_EXTENSION, XML_SCHEMAS_ELEM_FINAL_RESTRICTION, -1, -1, -1) != 0) { xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, NULL, (xmlNodePtr) attr, NULL, "(#all | List of (extension | restriction))", attrValue, NULL, NULL, NULL); } } } /* * Attribute "block". */ attr = xmlSchemaGetPropNode(node, "block"); if (attr == NULL) { /* * Apply default "block" values. */ if (schema->flags & XML_SCHEMAS_BLOCK_DEFAULT_RESTRICTION) decl->flags |= XML_SCHEMAS_ELEM_BLOCK_RESTRICTION; if (schema->flags & XML_SCHEMAS_BLOCK_DEFAULT_EXTENSION) decl->flags |= XML_SCHEMAS_ELEM_BLOCK_EXTENSION; if (schema->flags & XML_SCHEMAS_BLOCK_DEFAULT_SUBSTITUTION) decl->flags |= XML_SCHEMAS_ELEM_BLOCK_SUBSTITUTION; } else { attrValue = xmlSchemaGetNodeContent(ctxt, (xmlNodePtr) attr); if (xmlSchemaPValAttrBlockFinal(attrValue, &(decl->flags), -1, XML_SCHEMAS_ELEM_BLOCK_EXTENSION, XML_SCHEMAS_ELEM_BLOCK_RESTRICTION, XML_SCHEMAS_ELEM_BLOCK_SUBSTITUTION, -1, -1) != 0) { xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, NULL, (xmlNodePtr) attr, NULL, "(#all | List of (extension | " "restriction | substitution))", attrValue, NULL, NULL, NULL); } } if (xmlGetBooleanProp(ctxt, node, "nillable", 0)) decl->flags |= XML_SCHEMAS_ELEM_NILLABLE; attr = xmlSchemaGetPropNode(node, "type"); if (attr != NULL) { xmlSchemaPValAttrNodeQName(ctxt, schema, NULL, attr, &(decl->namedTypeNs), &(decl->namedType)); xmlSchemaCheckReference(ctxt, schema, node, attr, decl->namedTypeNs); } decl->value = xmlSchemaGetProp(ctxt, node, "default"); attr = xmlSchemaGetPropNode(node, "fixed"); if (attr != NULL) { fixed = xmlSchemaGetNodeContent(ctxt, (xmlNodePtr) attr); if (decl->value != NULL) { /* * 3.3.3 : 1 * default and fixed must not both be present. */ xmlSchemaPMutualExclAttrErr(ctxt, XML_SCHEMAP_SRC_ELEMENT_1, NULL, attr, "default", "fixed"); } else { decl->flags |= XML_SCHEMAS_ELEM_FIXED; decl->value = fixed; } } /* * And now for the children... */ if (IS_SCHEMA(child, "complexType")) { /* * 3.3.3 : 3 * "type" and either <simpleType> or <complexType> are mutually * exclusive */ if (decl->namedType != NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_SRC_ELEMENT_3, NULL, node, child, "The attribute 'type' and the <complexType> child are " "mutually exclusive", NULL); } else WXS_ELEM_TYPEDEF(decl) = xmlSchemaParseComplexType(ctxt, schema, child, 0); child = child->next; } else if (IS_SCHEMA(child, "simpleType")) { /* * 3.3.3 : 3 * "type" and either <simpleType> or <complexType> are * mutually exclusive */ if (decl->namedType != NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_SRC_ELEMENT_3, NULL, node, child, "The attribute 'type' and the <simpleType> child are " "mutually exclusive", NULL); } else WXS_ELEM_TYPEDEF(decl) = xmlSchemaParseSimpleType(ctxt, schema, child, 0); child = child->next; } while ((IS_SCHEMA(child, "unique")) || (IS_SCHEMA(child, "key")) || (IS_SCHEMA(child, "keyref"))) { if (IS_SCHEMA(child, "unique")) { curIDC = xmlSchemaParseIDC(ctxt, schema, child, XML_SCHEMA_TYPE_IDC_UNIQUE, decl->targetNamespace); } else if (IS_SCHEMA(child, "key")) { curIDC = xmlSchemaParseIDC(ctxt, schema, child, XML_SCHEMA_TYPE_IDC_KEY, decl->targetNamespace); } else if (IS_SCHEMA(child, "keyref")) { curIDC = xmlSchemaParseIDC(ctxt, schema, child, XML_SCHEMA_TYPE_IDC_KEYREF, decl->targetNamespace); } if (lastIDC != NULL) lastIDC->next = curIDC; else decl->idcs = (void *) curIDC; lastIDC = curIDC; child = child->next; } if (child != NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?, ((simpleType | complexType)?, " "(unique | key | keyref)*))"); } decl->annot = annot; } /* * NOTE: Element Declaration Representation OK 4. will be checked at a * different layer. */ FREE_AND_NULL(des) if (topLevel) return ((xmlSchemaBasicItemPtr) decl); else { particle->children = (xmlSchemaTreeItemPtr) decl; return ((xmlSchemaBasicItemPtr) particle); } return_null: FREE_AND_NULL(des); if (annot != NULL) { if (particle != NULL) particle->annot = NULL; if (decl != NULL) decl->annot = NULL; xmlSchemaFreeAnnot(annot); } return (NULL); } /** * xmlSchemaParseUnion: * @ctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * * parse a XML schema Union definition * *WARNING* this interface is highly subject to change * * Returns -1 in case of internal error, 0 in case of success and a positive * error code otherwise. */ static int xmlSchemaParseUnion(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node) { xmlSchemaTypePtr type; xmlNodePtr child = NULL; xmlAttrPtr attr; const xmlChar *cur = NULL; if ((ctxt == NULL) || (schema == NULL) || (node == NULL)) return (-1); /* Not a component, don't create it. */ type = ctxt->ctxtType; /* * Mark the simple type as being of variety "union". */ type->flags |= XML_SCHEMAS_TYPE_VARIETY_UNION; /* * SPEC (Base type) (2) "If the <list> or <union> alternative is chosen, * then the `simple ur-type definition`." */ type->baseType = xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYSIMPLETYPE); /* * Check for illegal attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if ((!xmlStrEqual(attr->name, BAD_CAST "id")) && (!xmlStrEqual(attr->name, BAD_CAST "memberTypes"))) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } xmlSchemaPValAttrID(ctxt, node, BAD_CAST "id"); /* * Attribute "memberTypes". This is a list of QNames. * TODO: Check the value to contain anything. */ attr = xmlSchemaGetPropNode(node, "memberTypes"); if (attr != NULL) { const xmlChar *end; xmlChar *tmp; const xmlChar *localName, *nsName; xmlSchemaTypeLinkPtr link, lastLink = NULL; xmlSchemaQNameRefPtr ref; cur = xmlSchemaGetNodeContent(ctxt, (xmlNodePtr) attr); type->base = cur; do { while (IS_BLANK_CH(*cur)) cur++; end = cur; while ((*end != 0) && (!(IS_BLANK_CH(*end)))) end++; if (end == cur) break; tmp = xmlStrndup(cur, end - cur); if (xmlSchemaPValAttrNodeQNameValue(ctxt, schema, NULL, attr, BAD_CAST tmp, &nsName, &localName) == 0) { /* * Create the member type link. */ link = (xmlSchemaTypeLinkPtr) xmlMalloc(sizeof(xmlSchemaTypeLink)); if (link == NULL) { xmlSchemaPErrMemory(ctxt, "xmlSchemaParseUnion, " "allocating a type link", NULL); return (-1); } link->type = NULL; link->next = NULL; if (lastLink == NULL) type->memberTypes = link; else lastLink->next = link; lastLink = link; /* * Create a reference item. */ ref = xmlSchemaNewQNameRef(ctxt, XML_SCHEMA_TYPE_SIMPLE, localName, nsName); if (ref == NULL) { FREE_AND_NULL(tmp) return (-1); } /* * Assign the reference to the link, it will be resolved * later during fixup of the union simple type. */ link->type = (xmlSchemaTypePtr) ref; } FREE_AND_NULL(tmp) cur = end; } while (*cur != 0); } /* * And now for the children... */ child = node->children; if (IS_SCHEMA(child, "annotation")) { /* * Add the annotation to the simple type ancestor. */ xmlSchemaAddAnnotation((xmlSchemaAnnotItemPtr) type, xmlSchemaParseAnnotation(ctxt, child, 1)); child = child->next; } if (IS_SCHEMA(child, "simpleType")) { xmlSchemaTypePtr subtype, last = NULL; /* * Anchor the member types in the "subtypes" field of the * simple type. */ while (IS_SCHEMA(child, "simpleType")) { subtype = (xmlSchemaTypePtr) xmlSchemaParseSimpleType(ctxt, schema, child, 0); if (subtype != NULL) { if (last == NULL) { type->subtypes = subtype; last = subtype; } else { last->next = subtype; last = subtype; } last->next = NULL; } child = child->next; } } if (child != NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?, simpleType*)"); } if ((attr == NULL) && (type->subtypes == NULL)) { /* * src-union-memberTypes-or-simpleTypes * Either the memberTypes [attribute] of the <union> element must * be non-empty or there must be at least one simpleType [child]. */ xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_SRC_UNION_MEMBERTYPES_OR_SIMPLETYPES, NULL, node, "Either the attribute 'memberTypes' or " "at least one <simpleType> child must be present", NULL); } return (0); } /** * xmlSchemaParseList: * @ctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * * parse a XML schema List definition * *WARNING* this interface is highly subject to change * * Returns -1 in case of error, 0 if the declaration is improper and * 1 in case of success. */ static xmlSchemaTypePtr xmlSchemaParseList(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node) { xmlSchemaTypePtr type; xmlNodePtr child = NULL; xmlAttrPtr attr; if ((ctxt == NULL) || (schema == NULL) || (node == NULL)) return (NULL); /* Not a component, don't create it. */ type = ctxt->ctxtType; /* * Mark the type as being of variety "list". */ type->flags |= XML_SCHEMAS_TYPE_VARIETY_LIST; /* * SPEC (Base type) (2) "If the <list> or <union> alternative is chosen, * then the `simple ur-type definition`." */ type->baseType = xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYSIMPLETYPE); /* * Check for illegal attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if ((!xmlStrEqual(attr->name, BAD_CAST "id")) && (!xmlStrEqual(attr->name, BAD_CAST "itemType"))) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } xmlSchemaPValAttrID(ctxt, node, BAD_CAST "id"); /* * Attribute "itemType". NOTE that we will use the "ref" and "refNs" * fields for holding the reference to the itemType. * * REVAMP TODO: Use the "base" and "baseNs" fields, since we will remove * the "ref" fields. */ xmlSchemaPValAttrQName(ctxt, schema, NULL, node, "itemType", &(type->baseNs), &(type->base)); /* * And now for the children... */ child = node->children; if (IS_SCHEMA(child, "annotation")) { xmlSchemaAddAnnotation((xmlSchemaAnnotItemPtr) type, xmlSchemaParseAnnotation(ctxt, child, 1)); child = child->next; } if (IS_SCHEMA(child, "simpleType")) { /* * src-list-itemType-or-simpleType * Either the itemType [attribute] or the <simpleType> [child] of * the <list> element must be present, but not both. */ if (type->base != NULL) { xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_SRC_SIMPLE_TYPE_1, NULL, node, "The attribute 'itemType' and the <simpleType> child " "are mutually exclusive", NULL); } else { type->subtypes = xmlSchemaParseSimpleType(ctxt, schema, child, 0); } child = child->next; } else if (type->base == NULL) { xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_SRC_SIMPLE_TYPE_1, NULL, node, "Either the attribute 'itemType' or the <simpleType> child " "must be present", NULL); } if (child != NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?, simpleType?)"); } if ((type->base == NULL) && (type->subtypes == NULL) && (xmlSchemaGetPropNode(node, "itemType") == NULL)) { xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_SRC_SIMPLE_TYPE_1, NULL, node, "Either the attribute 'itemType' or the <simpleType> child " "must be present", NULL); } return (NULL); } /** * xmlSchemaParseSimpleType: * @ctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * * parse a XML schema Simple Type definition * *WARNING* this interface is highly subject to change * * Returns -1 in case of error, 0 if the declaration is improper and * 1 in case of success. */ static xmlSchemaTypePtr xmlSchemaParseSimpleType(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node, int topLevel) { xmlSchemaTypePtr type, oldCtxtType; xmlNodePtr child = NULL; const xmlChar *attrValue = NULL; xmlAttrPtr attr; int hasRestriction = 0; if ((ctxt == NULL) || (schema == NULL) || (node == NULL)) return (NULL); if (topLevel) { attr = xmlSchemaGetPropNode(node, "name"); if (attr == NULL) { xmlSchemaPMissingAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_MISSING, NULL, node, "name", NULL); return (NULL); } else { if (xmlSchemaPValAttrNode(ctxt, NULL, attr, xmlSchemaGetBuiltInType(XML_SCHEMAS_NCNAME), &attrValue) != 0) return (NULL); /* * Skip built-in types. */ if (ctxt->isS4S) { xmlSchemaTypePtr biType; if (ctxt->isRedefine) { /* * REDEFINE: Disallow redefinition of built-in-types. * TODO: It seems that the spec does not say anything * about this case. */ xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_SRC_REDEFINE, NULL, node, "Redefinition of built-in simple types is not " "supported", NULL); return(NULL); } biType = xmlSchemaGetPredefinedType(attrValue, xmlSchemaNs); if (biType != NULL) return (biType); } } } /* * TargetNamespace: * SPEC "The `actual value` of the targetNamespace [attribute] * of the <schema> ancestor element information item if present, * otherwise `absent`. */ if (topLevel == 0) { #ifdef ENABLE_NAMED_LOCALS char buf[40]; #endif /* * Parse as local simple type definition. */ #ifdef ENABLE_NAMED_LOCALS snprintf(buf, 39, "#ST%d", ctxt->counter++ + 1); type = xmlSchemaAddType(ctxt, schema, XML_SCHEMA_TYPE_SIMPLE, xmlDictLookup(ctxt->dict, (const xmlChar *)buf, -1), ctxt->targetNamespace, node, 0); #else type = xmlSchemaAddType(ctxt, schema, XML_SCHEMA_TYPE_SIMPLE, NULL, ctxt->targetNamespace, node, 0); #endif if (type == NULL) return (NULL); type->type = XML_SCHEMA_TYPE_SIMPLE; type->contentType = XML_SCHEMA_CONTENT_SIMPLE; /* * Check for illegal attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if (!xmlStrEqual(attr->name, BAD_CAST "id")) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } } else { /* * Parse as global simple type definition. * * Note that attrValue is the value of the attribute "name" here. */ type = xmlSchemaAddType(ctxt, schema, XML_SCHEMA_TYPE_SIMPLE, attrValue, ctxt->targetNamespace, node, 1); if (type == NULL) return (NULL); type->type = XML_SCHEMA_TYPE_SIMPLE; type->contentType = XML_SCHEMA_CONTENT_SIMPLE; type->flags |= XML_SCHEMAS_TYPE_GLOBAL; /* * Check for illegal attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if ((!xmlStrEqual(attr->name, BAD_CAST "id")) && (!xmlStrEqual(attr->name, BAD_CAST "name")) && (!xmlStrEqual(attr->name, BAD_CAST "final"))) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } /* * Attribute "final". */ attr = xmlSchemaGetPropNode(node, "final"); if (attr == NULL) { if (schema->flags & XML_SCHEMAS_FINAL_DEFAULT_RESTRICTION) type->flags |= XML_SCHEMAS_TYPE_FINAL_RESTRICTION; if (schema->flags & XML_SCHEMAS_FINAL_DEFAULT_LIST) type->flags |= XML_SCHEMAS_TYPE_FINAL_LIST; if (schema->flags & XML_SCHEMAS_FINAL_DEFAULT_UNION) type->flags |= XML_SCHEMAS_TYPE_FINAL_UNION; } else { attrValue = xmlSchemaGetProp(ctxt, node, "final"); if (xmlSchemaPValAttrBlockFinal(attrValue, &(type->flags), -1, -1, XML_SCHEMAS_TYPE_FINAL_RESTRICTION, -1, XML_SCHEMAS_TYPE_FINAL_LIST, XML_SCHEMAS_TYPE_FINAL_UNION) != 0) { xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, WXS_BASIC_CAST type, (xmlNodePtr) attr, NULL, "(#all | List of (list | union | restriction)", attrValue, NULL, NULL, NULL); } } } type->targetNamespace = ctxt->targetNamespace; xmlSchemaPValAttrID(ctxt, node, BAD_CAST "id"); /* * And now for the children... */ oldCtxtType = ctxt->ctxtType; ctxt->ctxtType = type; child = node->children; if (IS_SCHEMA(child, "annotation")) { type->annot = xmlSchemaParseAnnotation(ctxt, child, 1); child = child->next; } if (child == NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_MISSING, NULL, node, child, NULL, "(annotation?, (restriction | list | union))"); } else if (IS_SCHEMA(child, "restriction")) { xmlSchemaParseRestriction(ctxt, schema, child, XML_SCHEMA_TYPE_SIMPLE); hasRestriction = 1; child = child->next; } else if (IS_SCHEMA(child, "list")) { xmlSchemaParseList(ctxt, schema, child); child = child->next; } else if (IS_SCHEMA(child, "union")) { xmlSchemaParseUnion(ctxt, schema, child); child = child->next; } if (child != NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?, (restriction | list | union))"); } /* * REDEFINE: SPEC src-redefine (5) * "Within the [children], each <simpleType> must have a * <restriction> among its [children] ... the `actual value` of whose * base [attribute] must be the same as the `actual value` of its own * name attribute plus target namespace;" */ if (topLevel && ctxt->isRedefine && (! hasRestriction)) { xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_SRC_REDEFINE, NULL, node, "This is a redefinition, thus the " "<simpleType> must have a <restriction> child", NULL); } ctxt->ctxtType = oldCtxtType; return (type); } /** * xmlSchemaParseModelGroupDefRef: * @ctxt: the parser context * @schema: the schema being built * @node: the node * * Parses a reference to a model group definition. * * We will return a particle component with a qname-component or * NULL in case of an error. */ static xmlSchemaTreeItemPtr xmlSchemaParseModelGroupDefRef(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node) { xmlSchemaParticlePtr item; xmlNodePtr child = NULL; xmlAttrPtr attr; const xmlChar *ref = NULL, *refNs = NULL; int min, max; if ((ctxt == NULL) || (schema == NULL) || (node == NULL)) return (NULL); attr = xmlSchemaGetPropNode(node, "ref"); if (attr == NULL) { xmlSchemaPMissingAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_MISSING, NULL, node, "ref", NULL); return (NULL); } else if (xmlSchemaPValAttrNodeQName(ctxt, schema, NULL, attr, &refNs, &ref) != 0) { return (NULL); } xmlSchemaCheckReference(ctxt, schema, node, attr, refNs); min = xmlGetMinOccurs(ctxt, node, 0, -1, 1, "xs:nonNegativeInteger"); max = xmlGetMaxOccurs(ctxt, node, 0, UNBOUNDED, 1, "(xs:nonNegativeInteger | unbounded)"); /* * Check for illegal attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if ((!xmlStrEqual(attr->name, BAD_CAST "ref")) && (!xmlStrEqual(attr->name, BAD_CAST "id")) && (!xmlStrEqual(attr->name, BAD_CAST "minOccurs")) && (!xmlStrEqual(attr->name, BAD_CAST "maxOccurs"))) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } xmlSchemaPValAttrID(ctxt, node, BAD_CAST "id"); item = xmlSchemaAddParticle(ctxt, node, min, max); if (item == NULL) return (NULL); /* * Create a qname-reference and set as the term; it will be substituted * for the model group after the reference has been resolved. */ item->children = (xmlSchemaTreeItemPtr) xmlSchemaNewQNameRef(ctxt, XML_SCHEMA_TYPE_GROUP, ref, refNs); xmlSchemaPCheckParticleCorrect_2(ctxt, item, node, min, max); /* * And now for the children... */ child = node->children; /* TODO: Is annotation even allowed for a model group reference? */ if (IS_SCHEMA(child, "annotation")) { /* * TODO: What to do exactly with the annotation? */ item->annot = xmlSchemaParseAnnotation(ctxt, child, 1); child = child->next; } if (child != NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?)"); } /* * Corresponds to no component at all if minOccurs==maxOccurs==0. */ if ((min == 0) && (max == 0)) return (NULL); return ((xmlSchemaTreeItemPtr) item); } /** * xmlSchemaParseModelGroupDefinition: * @ctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * * Parses a XML schema model group definition. * * Note that the constraint src-redefine (6.2) can't be applied until * references have been resolved. So we will do this at the * component fixup level. * * *WARNING* this interface is highly subject to change * * Returns -1 in case of error, 0 if the declaration is improper and * 1 in case of success. */ static xmlSchemaModelGroupDefPtr xmlSchemaParseModelGroupDefinition(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node) { xmlSchemaModelGroupDefPtr item; xmlNodePtr child = NULL; xmlAttrPtr attr; const xmlChar *name; if ((ctxt == NULL) || (schema == NULL) || (node == NULL)) return (NULL); attr = xmlSchemaGetPropNode(node, "name"); if (attr == NULL) { xmlSchemaPMissingAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_MISSING, NULL, node, "name", NULL); return (NULL); } else if (xmlSchemaPValAttrNode(ctxt, NULL, attr, xmlSchemaGetBuiltInType(XML_SCHEMAS_NCNAME), &name) != 0) { return (NULL); } item = xmlSchemaAddModelGroupDefinition(ctxt, schema, name, ctxt->targetNamespace, node); if (item == NULL) return (NULL); /* * Check for illegal attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if ((!xmlStrEqual(attr->name, BAD_CAST "name")) && (!xmlStrEqual(attr->name, BAD_CAST "id"))) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } xmlSchemaPValAttrID(ctxt, node, BAD_CAST "id"); /* * And now for the children... */ child = node->children; if (IS_SCHEMA(child, "annotation")) { item->annot = xmlSchemaParseAnnotation(ctxt, child, 1); child = child->next; } if (IS_SCHEMA(child, "all")) { item->children = xmlSchemaParseModelGroup(ctxt, schema, child, XML_SCHEMA_TYPE_ALL, 0); child = child->next; } else if (IS_SCHEMA(child, "choice")) { item->children = xmlSchemaParseModelGroup(ctxt, schema, child, XML_SCHEMA_TYPE_CHOICE, 0); child = child->next; } else if (IS_SCHEMA(child, "sequence")) { item->children = xmlSchemaParseModelGroup(ctxt, schema, child, XML_SCHEMA_TYPE_SEQUENCE, 0); child = child->next; } if (child != NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?, (all | choice | sequence)?)"); } return (item); } /** * xmlSchemaCleanupDoc: * @ctxt: a schema validation context * @node: the root of the document. * * removes unwanted nodes in a schemas document tree */ static void xmlSchemaCleanupDoc(xmlSchemaParserCtxtPtr ctxt, xmlNodePtr root) { xmlNodePtr delete, cur; if ((ctxt == NULL) || (root == NULL)) return; /* * Remove all the blank text nodes */ delete = NULL; cur = root; while (cur != NULL) { if (delete != NULL) { xmlUnlinkNode(delete); xmlFreeNode(delete); delete = NULL; } if (cur->type == XML_TEXT_NODE) { if (IS_BLANK_NODE(cur)) { if (xmlNodeGetSpacePreserve(cur) != 1) { delete = cur; } } } else if ((cur->type != XML_ELEMENT_NODE) && (cur->type != XML_CDATA_SECTION_NODE)) { delete = cur; goto skip_children; } /* * Skip to next node */ if (cur->children != NULL) { if ((cur->children->type != XML_ENTITY_DECL) && (cur->children->type != XML_ENTITY_REF_NODE) && (cur->children->type != XML_ENTITY_NODE)) { cur = cur->children; continue; } } skip_children: if (cur->next != NULL) { cur = cur->next; continue; } do { cur = cur->parent; if (cur == NULL) break; if (cur == root) { cur = NULL; break; } if (cur->next != NULL) { cur = cur->next; break; } } while (cur != NULL); } if (delete != NULL) { xmlUnlinkNode(delete); xmlFreeNode(delete); delete = NULL; } } static void xmlSchemaClearSchemaDefaults(xmlSchemaPtr schema) { if (schema->flags & XML_SCHEMAS_QUALIF_ELEM) schema->flags ^= XML_SCHEMAS_QUALIF_ELEM; if (schema->flags & XML_SCHEMAS_QUALIF_ATTR) schema->flags ^= XML_SCHEMAS_QUALIF_ATTR; if (schema->flags & XML_SCHEMAS_FINAL_DEFAULT_EXTENSION) schema->flags ^= XML_SCHEMAS_FINAL_DEFAULT_EXTENSION; if (schema->flags & XML_SCHEMAS_FINAL_DEFAULT_RESTRICTION) schema->flags ^= XML_SCHEMAS_FINAL_DEFAULT_RESTRICTION; if (schema->flags & XML_SCHEMAS_FINAL_DEFAULT_LIST) schema->flags ^= XML_SCHEMAS_FINAL_DEFAULT_LIST; if (schema->flags & XML_SCHEMAS_FINAL_DEFAULT_UNION) schema->flags ^= XML_SCHEMAS_FINAL_DEFAULT_UNION; if (schema->flags & XML_SCHEMAS_BLOCK_DEFAULT_EXTENSION) schema->flags ^= XML_SCHEMAS_BLOCK_DEFAULT_EXTENSION; if (schema->flags & XML_SCHEMAS_BLOCK_DEFAULT_RESTRICTION) schema->flags ^= XML_SCHEMAS_BLOCK_DEFAULT_RESTRICTION; if (schema->flags & XML_SCHEMAS_BLOCK_DEFAULT_SUBSTITUTION) schema->flags ^= XML_SCHEMAS_BLOCK_DEFAULT_SUBSTITUTION; } static int xmlSchemaParseSchemaElement(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node) { xmlAttrPtr attr; const xmlChar *val; int res = 0, oldErrs = ctxt->nberrors; /* * Those flags should be moved to the parser context flags, * since they are not visible at the component level. I.e. * they are used if processing schema *documents* only. */ res = xmlSchemaPValAttrID(ctxt, node, BAD_CAST "id"); HFAILURE; /* * Since the version is of type xs:token, we won't bother to * check it. */ /* REMOVED: attr = xmlSchemaGetPropNode(node, "version"); if (attr != NULL) { res = xmlSchemaPValAttrNode(ctxt, NULL, NULL, attr, xmlSchemaGetBuiltInType(XML_SCHEMAS_TOKEN), &val); HFAILURE; } */ attr = xmlSchemaGetPropNode(node, "targetNamespace"); if (attr != NULL) { res = xmlSchemaPValAttrNode(ctxt, NULL, attr, xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYURI), NULL); HFAILURE; if (res != 0) { ctxt->stop = XML_SCHEMAP_S4S_ATTR_INVALID_VALUE; goto exit; } } attr = xmlSchemaGetPropNode(node, "elementFormDefault"); if (attr != NULL) { val = xmlSchemaGetNodeContent(ctxt, (xmlNodePtr) attr); res = xmlSchemaPValAttrFormDefault(val, &schema->flags, XML_SCHEMAS_QUALIF_ELEM); HFAILURE; if (res != 0) { xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_ELEMFORMDEFAULT_VALUE, NULL, (xmlNodePtr) attr, NULL, "(qualified | unqualified)", val, NULL, NULL, NULL); } } attr = xmlSchemaGetPropNode(node, "attributeFormDefault"); if (attr != NULL) { val = xmlSchemaGetNodeContent(ctxt, (xmlNodePtr) attr); res = xmlSchemaPValAttrFormDefault(val, &schema->flags, XML_SCHEMAS_QUALIF_ATTR); HFAILURE; if (res != 0) { xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_ATTRFORMDEFAULT_VALUE, NULL, (xmlNodePtr) attr, NULL, "(qualified | unqualified)", val, NULL, NULL, NULL); } } attr = xmlSchemaGetPropNode(node, "finalDefault"); if (attr != NULL) { val = xmlSchemaGetNodeContent(ctxt, (xmlNodePtr) attr); res = xmlSchemaPValAttrBlockFinal(val, &(schema->flags), -1, XML_SCHEMAS_FINAL_DEFAULT_EXTENSION, XML_SCHEMAS_FINAL_DEFAULT_RESTRICTION, -1, XML_SCHEMAS_FINAL_DEFAULT_LIST, XML_SCHEMAS_FINAL_DEFAULT_UNION); HFAILURE; if (res != 0) { xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, NULL, (xmlNodePtr) attr, NULL, "(#all | List of (extension | restriction | list | union))", val, NULL, NULL, NULL); } } attr = xmlSchemaGetPropNode(node, "blockDefault"); if (attr != NULL) { val = xmlSchemaGetNodeContent(ctxt, (xmlNodePtr) attr); res = xmlSchemaPValAttrBlockFinal(val, &(schema->flags), -1, XML_SCHEMAS_BLOCK_DEFAULT_EXTENSION, XML_SCHEMAS_BLOCK_DEFAULT_RESTRICTION, XML_SCHEMAS_BLOCK_DEFAULT_SUBSTITUTION, -1, -1); HFAILURE; if (res != 0) { xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, NULL, (xmlNodePtr) attr, NULL, "(#all | List of (extension | restriction | substitution))", val, NULL, NULL, NULL); } } exit: if (oldErrs != ctxt->nberrors) res = ctxt->err; return(res); exit_failure: return(-1); } /** * xmlSchemaParseSchemaTopLevel: * @ctxt: a schema validation context * @schema: the schemas * @nodes: the list of top level nodes * * Returns the internal XML Schema structure built from the resource or * NULL in case of error */ static int xmlSchemaParseSchemaTopLevel(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr nodes) { xmlNodePtr child; xmlSchemaAnnotPtr annot; int res = 0, oldErrs, tmpOldErrs; if ((ctxt == NULL) || (schema == NULL) || (nodes == NULL)) return(-1); oldErrs = ctxt->nberrors; child = nodes; while ((IS_SCHEMA(child, "include")) || (IS_SCHEMA(child, "import")) || (IS_SCHEMA(child, "redefine")) || (IS_SCHEMA(child, "annotation"))) { if (IS_SCHEMA(child, "annotation")) { annot = xmlSchemaParseAnnotation(ctxt, child, 1); if (schema->annot == NULL) schema->annot = annot; else xmlSchemaFreeAnnot(annot); } else if (IS_SCHEMA(child, "import")) { tmpOldErrs = ctxt->nberrors; res = xmlSchemaParseImport(ctxt, schema, child); HFAILURE; HSTOP(ctxt); if (tmpOldErrs != ctxt->nberrors) goto exit; } else if (IS_SCHEMA(child, "include")) { tmpOldErrs = ctxt->nberrors; res = xmlSchemaParseInclude(ctxt, schema, child); HFAILURE; HSTOP(ctxt); if (tmpOldErrs != ctxt->nberrors) goto exit; } else if (IS_SCHEMA(child, "redefine")) { tmpOldErrs = ctxt->nberrors; res = xmlSchemaParseRedefine(ctxt, schema, child); HFAILURE; HSTOP(ctxt); if (tmpOldErrs != ctxt->nberrors) goto exit; } child = child->next; } /* * URGENT TODO: Change the functions to return int results. * We need especially to catch internal errors. */ while (child != NULL) { if (IS_SCHEMA(child, "complexType")) { xmlSchemaParseComplexType(ctxt, schema, child, 1); child = child->next; } else if (IS_SCHEMA(child, "simpleType")) { xmlSchemaParseSimpleType(ctxt, schema, child, 1); child = child->next; } else if (IS_SCHEMA(child, "element")) { xmlSchemaParseElement(ctxt, schema, child, NULL, 1); child = child->next; } else if (IS_SCHEMA(child, "attribute")) { xmlSchemaParseGlobalAttribute(ctxt, schema, child); child = child->next; } else if (IS_SCHEMA(child, "attributeGroup")) { xmlSchemaParseAttributeGroupDefinition(ctxt, schema, child); child = child->next; } else if (IS_SCHEMA(child, "group")) { xmlSchemaParseModelGroupDefinition(ctxt, schema, child); child = child->next; } else if (IS_SCHEMA(child, "notation")) { xmlSchemaParseNotation(ctxt, schema, child); child = child->next; } else { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, child->parent, child, NULL, "((include | import | redefine | annotation)*, " "(((simpleType | complexType | group | attributeGroup) " "| element | attribute | notation), annotation*)*)"); child = child->next; } while (IS_SCHEMA(child, "annotation")) { /* * TODO: We should add all annotations. */ annot = xmlSchemaParseAnnotation(ctxt, child, 1); if (schema->annot == NULL) schema->annot = annot; else xmlSchemaFreeAnnot(annot); child = child->next; } } exit: ctxt->ctxtType = NULL; if (oldErrs != ctxt->nberrors) res = ctxt->err; return(res); exit_failure: return(-1); } static xmlSchemaSchemaRelationPtr xmlSchemaSchemaRelationCreate(void) { xmlSchemaSchemaRelationPtr ret; ret = (xmlSchemaSchemaRelationPtr) xmlMalloc(sizeof(xmlSchemaSchemaRelation)); if (ret == NULL) { xmlSchemaPErrMemory(NULL, "allocating schema relation", NULL); return(NULL); } memset(ret, 0, sizeof(xmlSchemaSchemaRelation)); return(ret); } #if 0 static void xmlSchemaSchemaRelationFree(xmlSchemaSchemaRelationPtr rel) { xmlFree(rel); } #endif static void xmlSchemaRedefListFree(xmlSchemaRedefPtr redef) { xmlSchemaRedefPtr prev; while (redef != NULL) { prev = redef; redef = redef->next; xmlFree(prev); } } static void xmlSchemaConstructionCtxtFree(xmlSchemaConstructionCtxtPtr con) { /* * After the construction context has been freed, there will be * no schema graph available any more. Only the schema buckets * will stay alive, which are put into the "schemasImports" and * "includes" slots of the xmlSchema. */ if (con->buckets != NULL) xmlSchemaItemListFree(con->buckets); if (con->pending != NULL) xmlSchemaItemListFree(con->pending); if (con->substGroups != NULL) xmlHashFree(con->substGroups, xmlSchemaSubstGroupFreeEntry); if (con->redefs != NULL) xmlSchemaRedefListFree(con->redefs); if (con->dict != NULL) xmlDictFree(con->dict); xmlFree(con); } static xmlSchemaConstructionCtxtPtr xmlSchemaConstructionCtxtCreate(xmlDictPtr dict) { xmlSchemaConstructionCtxtPtr ret; ret = (xmlSchemaConstructionCtxtPtr) xmlMalloc(sizeof(xmlSchemaConstructionCtxt)); if (ret == NULL) { xmlSchemaPErrMemory(NULL, "allocating schema construction context", NULL); return (NULL); } memset(ret, 0, sizeof(xmlSchemaConstructionCtxt)); ret->buckets = xmlSchemaItemListCreate(); if (ret->buckets == NULL) { xmlSchemaPErrMemory(NULL, "allocating list of schema buckets", NULL); xmlFree(ret); return (NULL); } ret->pending = xmlSchemaItemListCreate(); if (ret->pending == NULL) { xmlSchemaPErrMemory(NULL, "allocating list of pending global components", NULL); xmlSchemaConstructionCtxtFree(ret); return (NULL); } ret->dict = dict; xmlDictReference(dict); return(ret); } static xmlSchemaParserCtxtPtr xmlSchemaParserCtxtCreate(void) { xmlSchemaParserCtxtPtr ret; ret = (xmlSchemaParserCtxtPtr) xmlMalloc(sizeof(xmlSchemaParserCtxt)); if (ret == NULL) { xmlSchemaPErrMemory(NULL, "allocating schema parser context", NULL); return (NULL); } memset(ret, 0, sizeof(xmlSchemaParserCtxt)); ret->type = XML_SCHEMA_CTXT_PARSER; ret->attrProhibs = xmlSchemaItemListCreate(); if (ret->attrProhibs == NULL) { xmlFree(ret); return(NULL); } return(ret); } /** * xmlSchemaNewParserCtxtUseDict: * @URL: the location of the schema * @dict: the dictionary to be used * * Create an XML Schemas parse context for that file/resource expected * to contain an XML Schemas file. * * Returns the parser context or NULL in case of error */ static xmlSchemaParserCtxtPtr xmlSchemaNewParserCtxtUseDict(const char *URL, xmlDictPtr dict) { xmlSchemaParserCtxtPtr ret; ret = xmlSchemaParserCtxtCreate(); if (ret == NULL) return (NULL); ret->dict = dict; xmlDictReference(dict); if (URL != NULL) ret->URL = xmlDictLookup(dict, (const xmlChar *) URL, -1); return (ret); } static int xmlSchemaCreatePCtxtOnVCtxt(xmlSchemaValidCtxtPtr vctxt) { if (vctxt->pctxt == NULL) { if (vctxt->schema != NULL) vctxt->pctxt = xmlSchemaNewParserCtxtUseDict("*", vctxt->schema->dict); else vctxt->pctxt = xmlSchemaNewParserCtxt("*"); if (vctxt->pctxt == NULL) { VERROR_INT("xmlSchemaCreatePCtxtOnVCtxt", "failed to create a temp. parser context"); return (-1); } /* TODO: Pass user data. */ xmlSchemaSetParserErrors(vctxt->pctxt, vctxt->error, vctxt->warning, vctxt->errCtxt); xmlSchemaSetParserStructuredErrors(vctxt->pctxt, vctxt->serror, vctxt->errCtxt); } return (0); } /** * xmlSchemaGetSchemaBucket: * @pctxt: the schema parser context * @schemaLocation: the URI of the schema document * * Returns a schema bucket if it was already parsed. * * Returns a schema bucket if it was already parsed from * @schemaLocation, NULL otherwise. */ static xmlSchemaBucketPtr xmlSchemaGetSchemaBucket(xmlSchemaParserCtxtPtr pctxt, const xmlChar *schemaLocation) { xmlSchemaBucketPtr cur; xmlSchemaItemListPtr list; list = pctxt->constructor->buckets; if (list->nbItems == 0) return(NULL); else { int i; for (i = 0; i < list->nbItems; i++) { cur = (xmlSchemaBucketPtr) list->items[i]; /* Pointer comparison! */ if (cur->schemaLocation == schemaLocation) return(cur); } } return(NULL); } static xmlSchemaBucketPtr xmlSchemaGetChameleonSchemaBucket(xmlSchemaParserCtxtPtr pctxt, const xmlChar *schemaLocation, const xmlChar *targetNamespace) { xmlSchemaBucketPtr cur; xmlSchemaItemListPtr list; list = pctxt->constructor->buckets; if (list->nbItems == 0) return(NULL); else { int i; for (i = 0; i < list->nbItems; i++) { cur = (xmlSchemaBucketPtr) list->items[i]; /* Pointer comparison! */ if ((cur->origTargetNamespace == NULL) && (cur->schemaLocation == schemaLocation) && (cur->targetNamespace == targetNamespace)) return(cur); } } return(NULL); } #define IS_BAD_SCHEMA_DOC(b) \ (((b)->doc == NULL) && ((b)->schemaLocation != NULL)) static xmlSchemaBucketPtr xmlSchemaGetSchemaBucketByTNS(xmlSchemaParserCtxtPtr pctxt, const xmlChar *targetNamespace, int imported) { xmlSchemaBucketPtr cur; xmlSchemaItemListPtr list; list = pctxt->constructor->buckets; if (list->nbItems == 0) return(NULL); else { int i; for (i = 0; i < list->nbItems; i++) { cur = (xmlSchemaBucketPtr) list->items[i]; if ((! IS_BAD_SCHEMA_DOC(cur)) && (cur->origTargetNamespace == targetNamespace) && ((imported && cur->imported) || ((!imported) && (!cur->imported)))) return(cur); } } return(NULL); } static int xmlSchemaParseNewDocWithContext(xmlSchemaParserCtxtPtr pctxt, xmlSchemaPtr schema, xmlSchemaBucketPtr bucket) { int oldFlags; xmlDocPtr oldDoc; xmlNodePtr node; int ret, oldErrs; xmlSchemaBucketPtr oldbucket = pctxt->constructor->bucket; /* * Save old values; reset the *main* schema. * URGENT TODO: This is not good; move the per-document information * to the parser. Get rid of passing the main schema to the * parsing functions. */ oldFlags = schema->flags; oldDoc = schema->doc; if (schema->flags != 0) xmlSchemaClearSchemaDefaults(schema); schema->doc = bucket->doc; pctxt->schema = schema; /* * Keep the current target namespace on the parser *not* on the * main schema. */ pctxt->targetNamespace = bucket->targetNamespace; WXS_CONSTRUCTOR(pctxt)->bucket = bucket; if ((bucket->targetNamespace != NULL) && xmlStrEqual(bucket->targetNamespace, xmlSchemaNs)) { /* * We are parsing the schema for schemas! */ pctxt->isS4S = 1; } /* Mark it as parsed, even if parsing fails. */ bucket->parsed++; /* Compile the schema doc. */ node = xmlDocGetRootElement(bucket->doc); ret = xmlSchemaParseSchemaElement(pctxt, schema, node); if (ret != 0) goto exit; /* An empty schema; just get out. */ if (node->children == NULL) goto exit; oldErrs = pctxt->nberrors; ret = xmlSchemaParseSchemaTopLevel(pctxt, schema, node->children); if (ret != 0) goto exit; /* * TODO: Not nice, but I'm not 100% sure we will get always an error * as a result of the above functions; so better rely on pctxt->err * as well. */ if ((ret == 0) && (oldErrs != pctxt->nberrors)) { ret = pctxt->err; goto exit; } exit: WXS_CONSTRUCTOR(pctxt)->bucket = oldbucket; /* Restore schema values. */ schema->doc = oldDoc; schema->flags = oldFlags; return(ret); } static int xmlSchemaParseNewDoc(xmlSchemaParserCtxtPtr pctxt, xmlSchemaPtr schema, xmlSchemaBucketPtr bucket) { xmlSchemaParserCtxtPtr newpctxt; int res = 0; if (bucket == NULL) return(0); if (bucket->parsed) { PERROR_INT("xmlSchemaParseNewDoc", "reparsing a schema doc"); return(-1); } if (bucket->doc == NULL) { PERROR_INT("xmlSchemaParseNewDoc", "parsing a schema doc, but there's no doc"); return(-1); } if (pctxt->constructor == NULL) { PERROR_INT("xmlSchemaParseNewDoc", "no constructor"); return(-1); } /* Create and init the temporary parser context. */ newpctxt = xmlSchemaNewParserCtxtUseDict( (const char *) bucket->schemaLocation, pctxt->dict); if (newpctxt == NULL) return(-1); newpctxt->constructor = pctxt->constructor; /* * TODO: Can we avoid that the parser knows about the main schema? * It would be better if he knows about the current schema bucket * only. */ newpctxt->schema = schema; xmlSchemaSetParserErrors(newpctxt, pctxt->error, pctxt->warning, pctxt->errCtxt); xmlSchemaSetParserStructuredErrors(newpctxt, pctxt->serror, pctxt->errCtxt); newpctxt->counter = pctxt->counter; res = xmlSchemaParseNewDocWithContext(newpctxt, schema, bucket); /* Channel back errors and cleanup the temporary parser context. */ if (res != 0) pctxt->err = res; pctxt->nberrors += newpctxt->nberrors; pctxt->counter = newpctxt->counter; newpctxt->constructor = NULL; /* Free the parser context. */ xmlSchemaFreeParserCtxt(newpctxt); return(res); } static void xmlSchemaSchemaRelationAddChild(xmlSchemaBucketPtr bucket, xmlSchemaSchemaRelationPtr rel) { xmlSchemaSchemaRelationPtr cur = bucket->relations; if (cur == NULL) { bucket->relations = rel; return; } while (cur->next != NULL) cur = cur->next; cur->next = rel; } static const xmlChar * xmlSchemaBuildAbsoluteURI(xmlDictPtr dict, const xmlChar* location, xmlNodePtr ctxtNode) { /* * Build an absolute location URI. */ if (location != NULL) { if (ctxtNode == NULL) return(location); else { xmlChar *base, *URI; const xmlChar *ret = NULL; base = xmlNodeGetBase(ctxtNode->doc, ctxtNode); if (base == NULL) { URI = xmlBuildURI(location, ctxtNode->doc->URL); } else { URI = xmlBuildURI(location, base); xmlFree(base); } if (URI != NULL) { ret = xmlDictLookup(dict, URI, -1); xmlFree(URI); return(ret); } } } return(NULL); } /** * xmlSchemaAddSchemaDoc: * @pctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * * Parse an included (and to-be-redefined) XML schema document. * * Returns 0 on success, a positive error code on errors and * -1 in case of an internal or API error. */ static int xmlSchemaAddSchemaDoc(xmlSchemaParserCtxtPtr pctxt, int type, /* import or include or redefine */ const xmlChar *schemaLocation, xmlDocPtr schemaDoc, const char *schemaBuffer, int schemaBufferLen, xmlNodePtr invokingNode, const xmlChar *sourceTargetNamespace, const xmlChar *importNamespace, xmlSchemaBucketPtr *bucket) { const xmlChar *targetNamespace = NULL; xmlSchemaSchemaRelationPtr relation = NULL; xmlDocPtr doc = NULL; int res = 0, err = 0, located = 0, preserveDoc = 0; xmlSchemaBucketPtr bkt = NULL; if (bucket != NULL) *bucket = NULL; switch (type) { case XML_SCHEMA_SCHEMA_IMPORT: case XML_SCHEMA_SCHEMA_MAIN: err = XML_SCHEMAP_SRC_IMPORT; break; case XML_SCHEMA_SCHEMA_INCLUDE: err = XML_SCHEMAP_SRC_INCLUDE; break; case XML_SCHEMA_SCHEMA_REDEFINE: err = XML_SCHEMAP_SRC_REDEFINE; break; } /* Special handling for the main schema: * skip the location and relation logic and just parse the doc. * We need just a bucket to be returned in this case. */ if ((type == XML_SCHEMA_SCHEMA_MAIN) || (! WXS_HAS_BUCKETS(pctxt))) goto doc_load; /* Note that we expect the location to be an absolute URI. */ if (schemaLocation != NULL) { bkt = xmlSchemaGetSchemaBucket(pctxt, schemaLocation); if ((bkt != NULL) && (pctxt->constructor->bucket == bkt)) { /* Report self-imports/inclusions/redefinitions. */ xmlSchemaCustomErr(ACTXT_CAST pctxt, err, invokingNode, NULL, "The schema must not import/include/redefine itself", NULL, NULL); goto exit; } } /* * Create a relation for the graph of schemas. */ relation = xmlSchemaSchemaRelationCreate(); if (relation == NULL) return(-1); xmlSchemaSchemaRelationAddChild(pctxt->constructor->bucket, relation); relation->type = type; /* * Save the namespace import information. */ if (WXS_IS_BUCKET_IMPMAIN(type)) { relation->importNamespace = importNamespace; if (schemaLocation == NULL) { /* * No location; this is just an import of the namespace. * Note that we don't assign a bucket to the relation * in this case. */ goto exit; } targetNamespace = importNamespace; } /* Did we already fetch the doc? */ if (bkt != NULL) { if ((WXS_IS_BUCKET_IMPMAIN(type)) && (! bkt->imported)) { /* * We included/redefined and then try to import a schema, * but the new location provided for import was different. */ if (schemaLocation == NULL) schemaLocation = BAD_CAST "in_memory_buffer"; if (!xmlStrEqual(schemaLocation, bkt->schemaLocation)) { xmlSchemaCustomErr(ACTXT_CAST pctxt, err, invokingNode, NULL, "The schema document '%s' cannot be imported, since " "it was already included or redefined", schemaLocation, NULL); goto exit; } } else if ((! WXS_IS_BUCKET_IMPMAIN(type)) && (bkt->imported)) { /* * We imported and then try to include/redefine a schema, * but the new location provided for the include/redefine * was different. */ if (schemaLocation == NULL) schemaLocation = BAD_CAST "in_memory_buffer"; if (!xmlStrEqual(schemaLocation, bkt->schemaLocation)) { xmlSchemaCustomErr(ACTXT_CAST pctxt, err, invokingNode, NULL, "The schema document '%s' cannot be included or " "redefined, since it was already imported", schemaLocation, NULL); goto exit; } } } if (WXS_IS_BUCKET_IMPMAIN(type)) { /* * Given that the schemaLocation [attribute] is only a hint, it is open * to applications to ignore all but the first <import> for a given * namespace, regardless of the `actual value` of schemaLocation, but * such a strategy risks missing useful information when new * schemaLocations are offered. * * We will use the first <import> that comes with a location. * Further <import>s *with* a location, will result in an error. * TODO: Better would be to just report a warning here, but * we'll try it this way until someone complains. * * Schema Document Location Strategy: * 3 Based on the namespace name, identify an existing schema document, * either as a resource which is an XML document or a <schema> element * information item, in some local schema repository; * 5 Attempt to resolve the namespace name to locate such a resource. * * NOTE: (3) and (5) are not supported. */ if (bkt != NULL) { relation->bucket = bkt; goto exit; } bkt = xmlSchemaGetSchemaBucketByTNS(pctxt, importNamespace, 1); if (bkt != NULL) { relation->bucket = bkt; if (bkt->schemaLocation == NULL) { /* First given location of the schema; load the doc. */ bkt->schemaLocation = schemaLocation; } else { if (!xmlStrEqual(schemaLocation, bkt->schemaLocation)) { /* * Additional location given; just skip it. * URGENT TODO: We should report a warning here. * res = XML_SCHEMAP_SRC_IMPORT; */ if (schemaLocation == NULL) schemaLocation = BAD_CAST "in_memory_buffer"; xmlSchemaCustomWarning(ACTXT_CAST pctxt, XML_SCHEMAP_WARN_SKIP_SCHEMA, invokingNode, NULL, "Skipping import of schema located at '%s' for the " "namespace '%s', since this namespace was already " "imported with the schema located at '%s'", schemaLocation, importNamespace, bkt->schemaLocation); } goto exit; } } /* * No bucket + first location: load the doc and create a * bucket. */ } else { /* <include> and <redefine> */ if (bkt != NULL) { if ((bkt->origTargetNamespace == NULL) && (bkt->targetNamespace != sourceTargetNamespace)) { xmlSchemaBucketPtr chamel; /* * Chameleon include/redefine: skip loading only if it was * already build for the targetNamespace of the including * schema. */ /* * URGENT TODO: If the schema is a chameleon-include then copy * the components into the including schema and modify the * targetNamespace of those components, do nothing otherwise. * NOTE: This is currently worked-around by compiling the * chameleon for every distinct including targetNamespace; thus * not performant at the moment. * TODO: Check when the namespace in wildcards for chameleons * needs to be converted: before we built wildcard intersections * or after. * Answer: after! */ chamel = xmlSchemaGetChameleonSchemaBucket(pctxt, schemaLocation, sourceTargetNamespace); if (chamel != NULL) { /* A fitting chameleon was already parsed; NOP. */ relation->bucket = chamel; goto exit; } /* * We need to parse the chameleon again for a different * targetNamespace. * CHAMELEON TODO: Optimize this by only parsing the * chameleon once, and then copying the components to * the new targetNamespace. */ bkt = NULL; } else { relation->bucket = bkt; goto exit; } } } if ((bkt != NULL) && (bkt->doc != NULL)) { PERROR_INT("xmlSchemaAddSchemaDoc", "trying to load a schema doc, but a doc is already " "assigned to the schema bucket"); goto exit_failure; } doc_load: /* * Load the document. */ if (schemaDoc != NULL) { doc = schemaDoc; /* Don' free this one, since it was provided by the caller. */ preserveDoc = 1; /* TODO: Does the context or the doc hold the location? */ if (schemaDoc->URL != NULL) schemaLocation = xmlDictLookup(pctxt->dict, schemaDoc->URL, -1); else schemaLocation = BAD_CAST "in_memory_buffer"; } else if ((schemaLocation != NULL) || (schemaBuffer != NULL)) { xmlParserCtxtPtr parserCtxt; parserCtxt = xmlNewParserCtxt(); if (parserCtxt == NULL) { xmlSchemaPErrMemory(NULL, "xmlSchemaGetDoc, " "allocating a parser context", NULL); goto exit_failure; } if ((pctxt->dict != NULL) && (parserCtxt->dict != NULL)) { /* * TODO: Do we have to burden the schema parser dict with all * the content of the schema doc? */ xmlDictFree(parserCtxt->dict); parserCtxt->dict = pctxt->dict; xmlDictReference(parserCtxt->dict); } if (schemaLocation != NULL) { /* Parse from file. */ doc = xmlCtxtReadFile(parserCtxt, (const char *) schemaLocation, NULL, SCHEMAS_PARSE_OPTIONS); } else if (schemaBuffer != NULL) { /* Parse from memory buffer. */ doc = xmlCtxtReadMemory(parserCtxt, schemaBuffer, schemaBufferLen, NULL, NULL, SCHEMAS_PARSE_OPTIONS); schemaLocation = BAD_CAST "in_memory_buffer"; if (doc != NULL) doc->URL = xmlStrdup(schemaLocation); } /* * For <import>: * 2.1 The referent is (a fragment of) a resource which is an * XML document (see clause 1.1), which in turn corresponds to * a <schema> element information item in a well-formed information * set, which in turn corresponds to a valid schema. * TODO: (2.1) fragments of XML documents are not supported. * * 2.2 The referent is a <schema> element information item in * a well-formed information set, which in turn corresponds * to a valid schema. * TODO: (2.2) is not supported. */ if (doc == NULL) { xmlErrorPtr lerr; lerr = xmlGetLastError(); /* * Check if this a parser error, or if the document could * just not be located. * TODO: Try to find specific error codes to react only on * localisation failures. */ if ((lerr == NULL) || (lerr->domain != XML_FROM_IO)) { /* * We assume a parser error here. */ located = 1; /* TODO: Error code ?? */ res = XML_SCHEMAP_SRC_IMPORT_2_1; xmlSchemaCustomErr(ACTXT_CAST pctxt, res, invokingNode, NULL, "Failed to parse the XML resource '%s'", schemaLocation, NULL); } } xmlFreeParserCtxt(parserCtxt); if ((doc == NULL) && located) goto exit_error; } else { xmlSchemaPErr(pctxt, NULL, XML_SCHEMAP_NOTHING_TO_PARSE, "No information for parsing was provided with the " "given schema parser context.\n", NULL, NULL); goto exit_failure; } /* * Preprocess the document. */ if (doc != NULL) { xmlNodePtr docElem = NULL; located = 1; docElem = xmlDocGetRootElement(doc); if (docElem == NULL) { xmlSchemaCustomErr(ACTXT_CAST pctxt, XML_SCHEMAP_NOROOT, invokingNode, NULL, "The document '%s' has no document element", schemaLocation, NULL); goto exit_error; } /* * Remove all the blank text nodes. */ xmlSchemaCleanupDoc(pctxt, docElem); /* * Check the schema's top level element. */ if (!IS_SCHEMA(docElem, "schema")) { xmlSchemaCustomErr(ACTXT_CAST pctxt, XML_SCHEMAP_NOT_SCHEMA, invokingNode, NULL, "The XML document '%s' is not a schema document", schemaLocation, NULL); goto exit_error; } /* * Note that we don't apply a type check for the * targetNamespace value here. */ targetNamespace = xmlSchemaGetProp(pctxt, docElem, "targetNamespace"); } /* after_doc_loading: */ if ((bkt == NULL) && located) { /* Only create a bucket if the schema was located. */ bkt = xmlSchemaBucketCreate(pctxt, type, targetNamespace); if (bkt == NULL) goto exit_failure; } if (bkt != NULL) { bkt->schemaLocation = schemaLocation; bkt->located = located; if (doc != NULL) { bkt->doc = doc; bkt->targetNamespace = targetNamespace; bkt->origTargetNamespace = targetNamespace; if (preserveDoc) bkt->preserveDoc = 1; } if (WXS_IS_BUCKET_IMPMAIN(type)) bkt->imported++; /* * Add it to the graph of schemas. */ if (relation != NULL) relation->bucket = bkt; } exit: /* * Return the bucket explicitly; this is needed for the * main schema. */ if (bucket != NULL) *bucket = bkt; return (0); exit_error: if ((doc != NULL) && (! preserveDoc)) { xmlFreeDoc(doc); if (bkt != NULL) bkt->doc = NULL; } return(pctxt->err); exit_failure: if ((doc != NULL) && (! preserveDoc)) { xmlFreeDoc(doc); if (bkt != NULL) bkt->doc = NULL; } return (-1); } /** * xmlSchemaParseImport: * @ctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * * parse a XML schema Import definition * *WARNING* this interface is highly subject to change * * Returns 0 in case of success, a positive error code if * not valid and -1 in case of an internal error. */ static int xmlSchemaParseImport(xmlSchemaParserCtxtPtr pctxt, xmlSchemaPtr schema, xmlNodePtr node) { xmlNodePtr child; const xmlChar *namespaceName = NULL, *schemaLocation = NULL; const xmlChar *thisTargetNamespace; xmlAttrPtr attr; int ret = 0; xmlSchemaBucketPtr bucket = NULL; if ((pctxt == NULL) || (schema == NULL) || (node == NULL)) return (-1); /* * Check for illegal attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if ((!xmlStrEqual(attr->name, BAD_CAST "id")) && (!xmlStrEqual(attr->name, BAD_CAST "namespace")) && (!xmlStrEqual(attr->name, BAD_CAST "schemaLocation"))) { xmlSchemaPIllegalAttrErr(pctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(pctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } /* * Extract and validate attributes. */ if (xmlSchemaPValAttr(pctxt, NULL, node, "namespace", xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYURI), &namespaceName) != 0) { xmlSchemaPSimpleTypeErr(pctxt, XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, NULL, node, xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYURI), NULL, namespaceName, NULL, NULL, NULL); return (pctxt->err); } if (xmlSchemaPValAttr(pctxt, NULL, node, "schemaLocation", xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYURI), &schemaLocation) != 0) { xmlSchemaPSimpleTypeErr(pctxt, XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, NULL, node, xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYURI), NULL, schemaLocation, NULL, NULL, NULL); return (pctxt->err); } /* * And now for the children... */ child = node->children; if (IS_SCHEMA(child, "annotation")) { /* * the annotation here is simply discarded ... * TODO: really? */ child = child->next; } if (child != NULL) { xmlSchemaPContentErr(pctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?)"); } /* * Apply additional constraints. * * Note that it is important to use the original @targetNamespace * (or none at all), to rule out imports of schemas _with_ a * @targetNamespace if the importing schema is a chameleon schema * (with no @targetNamespace). */ thisTargetNamespace = WXS_BUCKET(pctxt)->origTargetNamespace; if (namespaceName != NULL) { /* * 1.1 If the namespace [attribute] is present, then its `actual value` * must not match the `actual value` of the enclosing <schema>'s * targetNamespace [attribute]. */ if (xmlStrEqual(thisTargetNamespace, namespaceName)) { xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_SRC_IMPORT_1_1, NULL, node, "The value of the attribute 'namespace' must not match " "the target namespace '%s' of the importing schema", thisTargetNamespace); return (pctxt->err); } } else { /* * 1.2 If the namespace [attribute] is not present, then the enclosing * <schema> must have a targetNamespace [attribute]. */ if (thisTargetNamespace == NULL) { xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_SRC_IMPORT_1_2, NULL, node, "The attribute 'namespace' must be existent if " "the importing schema has no target namespace", NULL); return (pctxt->err); } } /* * Locate and acquire the schema document. */ if (schemaLocation != NULL) schemaLocation = xmlSchemaBuildAbsoluteURI(pctxt->dict, schemaLocation, node); ret = xmlSchemaAddSchemaDoc(pctxt, XML_SCHEMA_SCHEMA_IMPORT, schemaLocation, NULL, NULL, 0, node, thisTargetNamespace, namespaceName, &bucket); if (ret != 0) return(ret); /* * For <import>: "It is *not* an error for the application * schema reference strategy to fail." * So just don't parse if no schema document was found. * Note that we will get no bucket if the schema could not be * located or if there was no schemaLocation. */ if ((bucket == NULL) && (schemaLocation != NULL)) { xmlSchemaCustomWarning(ACTXT_CAST pctxt, XML_SCHEMAP_WARN_UNLOCATED_SCHEMA, node, NULL, "Failed to locate a schema at location '%s'. " "Skipping the import", schemaLocation, NULL, NULL); } if ((bucket != NULL) && CAN_PARSE_SCHEMA(bucket)) { ret = xmlSchemaParseNewDoc(pctxt, schema, bucket); } return (ret); } static int xmlSchemaParseIncludeOrRedefineAttrs(xmlSchemaParserCtxtPtr pctxt, xmlSchemaPtr schema, xmlNodePtr node, xmlChar **schemaLocation, int type) { xmlAttrPtr attr; if ((pctxt == NULL) || (schema == NULL) || (node == NULL) || (schemaLocation == NULL)) return (-1); *schemaLocation = NULL; /* * Check for illegal attributes. * Applies for both <include> and <redefine>. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if ((!xmlStrEqual(attr->name, BAD_CAST "id")) && (!xmlStrEqual(attr->name, BAD_CAST "schemaLocation"))) { xmlSchemaPIllegalAttrErr(pctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(pctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } xmlSchemaPValAttrID(pctxt, node, BAD_CAST "id"); /* * Preliminary step, extract the URI-Reference and make an URI * from the base. */ /* * Attribute "schemaLocation" is mandatory. */ attr = xmlSchemaGetPropNode(node, "schemaLocation"); if (attr != NULL) { xmlChar *base = NULL; xmlChar *uri = NULL; if (xmlSchemaPValAttrNode(pctxt, NULL, attr, xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYURI), (const xmlChar **) schemaLocation) != 0) goto exit_error; base = xmlNodeGetBase(node->doc, node); if (base == NULL) { uri = xmlBuildURI(*schemaLocation, node->doc->URL); } else { uri = xmlBuildURI(*schemaLocation, base); xmlFree(base); } if (uri == NULL) { PERROR_INT("xmlSchemaParseIncludeOrRedefine", "could not build an URI from the schemaLocation") goto exit_failure; } (*schemaLocation) = (xmlChar *) xmlDictLookup(pctxt->dict, uri, -1); xmlFree(uri); } else { xmlSchemaPMissingAttrErr(pctxt, XML_SCHEMAP_S4S_ATTR_MISSING, NULL, node, "schemaLocation", NULL); goto exit_error; } /* * Report self-inclusion and self-redefinition. */ if (xmlStrEqual(*schemaLocation, pctxt->URL)) { if (type == XML_SCHEMA_SCHEMA_REDEFINE) { xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_SRC_REDEFINE, NULL, node, "The schema document '%s' cannot redefine itself.", *schemaLocation); } else { xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_SRC_INCLUDE, NULL, node, "The schema document '%s' cannot include itself.", *schemaLocation); } goto exit_error; } return(0); exit_error: return(pctxt->err); exit_failure: return(-1); } static int xmlSchemaParseIncludeOrRedefine(xmlSchemaParserCtxtPtr pctxt, xmlSchemaPtr schema, xmlNodePtr node, int type) { xmlNodePtr child = NULL; const xmlChar *schemaLocation = NULL; int res = 0; /* hasRedefinitions = 0 */ int isChameleon = 0, wasChameleon = 0; xmlSchemaBucketPtr bucket = NULL; if ((pctxt == NULL) || (schema == NULL) || (node == NULL)) return (-1); /* * Parse attributes. Note that the returned schemaLocation will * be already converted to an absolute URI. */ res = xmlSchemaParseIncludeOrRedefineAttrs(pctxt, schema, node, (xmlChar **) (&schemaLocation), type); if (res != 0) return(res); /* * Load and add the schema document. */ res = xmlSchemaAddSchemaDoc(pctxt, type, schemaLocation, NULL, NULL, 0, node, pctxt->targetNamespace, NULL, &bucket); if (res != 0) return(res); /* * If we get no schema bucket back, then this means that the schema * document could not be located or was broken XML or was not * a schema document. */ if ((bucket == NULL) || (bucket->doc == NULL)) { if (type == XML_SCHEMA_SCHEMA_INCLUDE) { /* * WARNING for <include>: * We will raise an error if the schema cannot be located * for inclusions, since the that was the feedback from the * schema people. I.e. the following spec piece will *not* be * satisfied: * SPEC src-include: "It is not an error for the `actual value` of the * schemaLocation [attribute] to fail to resolve it all, in which * case no corresponding inclusion is performed. * So do we need a warning report here?" */ res = XML_SCHEMAP_SRC_INCLUDE; xmlSchemaCustomErr(ACTXT_CAST pctxt, res, node, NULL, "Failed to load the document '%s' for inclusion", schemaLocation, NULL); } else { /* * NOTE: This was changed to raise an error even if no redefinitions * are specified. * * SPEC src-redefine (1) * "If there are any element information items among the [children] * other than <annotation> then the `actual value` of the * schemaLocation [attribute] must successfully resolve." * TODO: Ask the WG if a the location has always to resolve * here as well! */ res = XML_SCHEMAP_SRC_REDEFINE; xmlSchemaCustomErr(ACTXT_CAST pctxt, res, node, NULL, "Failed to load the document '%s' for redefinition", schemaLocation, NULL); } } else { /* * Check targetNamespace sanity before parsing the new schema. * TODO: Note that we won't check further content if the * targetNamespace was bad. */ if (bucket->origTargetNamespace != NULL) { /* * SPEC src-include (2.1) * "SII has a targetNamespace [attribute], and its `actual * value` is identical to the `actual value` of the targetNamespace * [attribute] of SII' (which must have such an [attribute])." */ if (pctxt->targetNamespace == NULL) { xmlSchemaCustomErr(ACTXT_CAST pctxt, XML_SCHEMAP_SRC_INCLUDE, node, NULL, "The target namespace of the included/redefined schema " "'%s' has to be absent, since the including/redefining " "schema has no target namespace", schemaLocation, NULL); goto exit_error; } else if (!xmlStrEqual(bucket->origTargetNamespace, pctxt->targetNamespace)) { /* TODO: Change error function. */ xmlSchemaPCustomErrExt(pctxt, XML_SCHEMAP_SRC_INCLUDE, NULL, node, "The target namespace '%s' of the included/redefined " "schema '%s' differs from '%s' of the " "including/redefining schema", bucket->origTargetNamespace, schemaLocation, pctxt->targetNamespace); goto exit_error; } } else if (pctxt->targetNamespace != NULL) { /* * Chameleons: the original target namespace will * differ from the resulting namespace. */ isChameleon = 1; if (bucket->parsed && bucket->origTargetNamespace != NULL) { xmlSchemaCustomErr(ACTXT_CAST pctxt, XML_SCHEMAP_SRC_INCLUDE, node, NULL, "The target namespace of the included/redefined schema " "'%s' has to be absent or the same as the " "including/redefining schema's target namespace", schemaLocation, NULL); goto exit_error; } bucket->targetNamespace = pctxt->targetNamespace; } } /* * Parse the schema. */ if (bucket && (!bucket->parsed) && (bucket->doc != NULL)) { if (isChameleon) { /* TODO: Get rid of this flag on the schema itself. */ if ((schema->flags & XML_SCHEMAS_INCLUDING_CONVERT_NS) == 0) { schema->flags |= XML_SCHEMAS_INCLUDING_CONVERT_NS; } else wasChameleon = 1; } xmlSchemaParseNewDoc(pctxt, schema, bucket); /* Restore chameleon flag. */ if (isChameleon && (!wasChameleon)) schema->flags ^= XML_SCHEMAS_INCLUDING_CONVERT_NS; } /* * And now for the children... */ child = node->children; if (type == XML_SCHEMA_SCHEMA_REDEFINE) { /* * Parse (simpleType | complexType | group | attributeGroup))* */ pctxt->redefined = bucket; /* * How to proceed if the redefined schema was not located? */ pctxt->isRedefine = 1; while (IS_SCHEMA(child, "annotation") || IS_SCHEMA(child, "simpleType") || IS_SCHEMA(child, "complexType") || IS_SCHEMA(child, "group") || IS_SCHEMA(child, "attributeGroup")) { if (IS_SCHEMA(child, "annotation")) { /* * TODO: discard or not? */ } else if (IS_SCHEMA(child, "simpleType")) { xmlSchemaParseSimpleType(pctxt, schema, child, 1); } else if (IS_SCHEMA(child, "complexType")) { xmlSchemaParseComplexType(pctxt, schema, child, 1); /* hasRedefinitions = 1; */ } else if (IS_SCHEMA(child, "group")) { /* hasRedefinitions = 1; */ xmlSchemaParseModelGroupDefinition(pctxt, schema, child); } else if (IS_SCHEMA(child, "attributeGroup")) { /* hasRedefinitions = 1; */ xmlSchemaParseAttributeGroupDefinition(pctxt, schema, child); } child = child->next; } pctxt->redefined = NULL; pctxt->isRedefine = 0; } else { if (IS_SCHEMA(child, "annotation")) { /* * TODO: discard or not? */ child = child->next; } } if (child != NULL) { res = XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED; if (type == XML_SCHEMA_SCHEMA_REDEFINE) { xmlSchemaPContentErr(pctxt, res, NULL, node, child, NULL, "(annotation | (simpleType | complexType | group | attributeGroup))*"); } else { xmlSchemaPContentErr(pctxt, res, NULL, node, child, NULL, "(annotation?)"); } } return(res); exit_error: return(pctxt->err); } static int xmlSchemaParseRedefine(xmlSchemaParserCtxtPtr pctxt, xmlSchemaPtr schema, xmlNodePtr node) { int res; #ifndef ENABLE_REDEFINE TODO return(0); #endif res = xmlSchemaParseIncludeOrRedefine(pctxt, schema, node, XML_SCHEMA_SCHEMA_REDEFINE); if (res != 0) return(res); return(0); } static int xmlSchemaParseInclude(xmlSchemaParserCtxtPtr pctxt, xmlSchemaPtr schema, xmlNodePtr node) { int res; res = xmlSchemaParseIncludeOrRedefine(pctxt, schema, node, XML_SCHEMA_SCHEMA_INCLUDE); if (res != 0) return(res); return(0); } /** * xmlSchemaParseModelGroup: * @ctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * @type: the "compositor" type * @particleNeeded: if a a model group with a particle * * parse a XML schema Sequence definition. * Applies parts of: * Schema Representation Constraint: * Redefinition Constraints and Semantics (src-redefine) * (6.1), (6.1.1), (6.1.2) * * Schema Component Constraint: * All Group Limited (cos-all-limited) (2) * TODO: Actually this should go to component-level checks, * but is done here due to performance. Move it to an other layer * is schema construction via an API is implemented. * * *WARNING* this interface is highly subject to change * * Returns -1 in case of error, 0 if the declaration is improper and * 1 in case of success. */ static xmlSchemaTreeItemPtr xmlSchemaParseModelGroup(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node, xmlSchemaTypeType type, int withParticle) { xmlSchemaModelGroupPtr item; xmlSchemaParticlePtr particle = NULL; xmlNodePtr child = NULL; xmlAttrPtr attr; int min = 1, max = 1, isElemRef, hasRefs = 0; if ((ctxt == NULL) || (schema == NULL) || (node == NULL)) return (NULL); /* * Create a model group with the given compositor. */ item = xmlSchemaAddModelGroup(ctxt, schema, type, node); if (item == NULL) return (NULL); if (withParticle) { if (type == XML_SCHEMA_TYPE_ALL) { min = xmlGetMinOccurs(ctxt, node, 0, 1, 1, "(0 | 1)"); max = xmlGetMaxOccurs(ctxt, node, 1, 1, 1, "1"); } else { /* choice + sequence */ min = xmlGetMinOccurs(ctxt, node, 0, -1, 1, "xs:nonNegativeInteger"); max = xmlGetMaxOccurs(ctxt, node, 0, UNBOUNDED, 1, "(xs:nonNegativeInteger | unbounded)"); } xmlSchemaPCheckParticleCorrect_2(ctxt, NULL, node, min, max); /* * Create a particle */ particle = xmlSchemaAddParticle(ctxt, node, min, max); if (particle == NULL) return (NULL); particle->children = (xmlSchemaTreeItemPtr) item; /* * Check for illegal attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if ((!xmlStrEqual(attr->name, BAD_CAST "id")) && (!xmlStrEqual(attr->name, BAD_CAST "maxOccurs")) && (!xmlStrEqual(attr->name, BAD_CAST "minOccurs"))) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } } else { /* * Check for illegal attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if (!xmlStrEqual(attr->name, BAD_CAST "id")) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } } /* * Extract and validate attributes. */ xmlSchemaPValAttrID(ctxt, node, BAD_CAST "id"); /* * And now for the children... */ child = node->children; if (IS_SCHEMA(child, "annotation")) { item->annot = xmlSchemaParseAnnotation(ctxt, child, 1); child = child->next; } if (type == XML_SCHEMA_TYPE_ALL) { xmlSchemaParticlePtr part, last = NULL; while (IS_SCHEMA(child, "element")) { part = (xmlSchemaParticlePtr) xmlSchemaParseElement(ctxt, schema, child, &isElemRef, 0); /* * SPEC cos-all-limited (2) * "The {max occurs} of all the particles in the {particles} * of the ('all') group must be 0 or 1. */ if (part != NULL) { if (isElemRef) hasRefs++; if (part->minOccurs > 1) { xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_COS_ALL_LIMITED, NULL, child, "Invalid value for minOccurs (must be 0 or 1)", NULL); /* Reset to 1. */ part->minOccurs = 1; } if (part->maxOccurs > 1) { xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_COS_ALL_LIMITED, NULL, child, "Invalid value for maxOccurs (must be 0 or 1)", NULL); /* Reset to 1. */ part->maxOccurs = 1; } if (last == NULL) item->children = (xmlSchemaTreeItemPtr) part; else last->next = (xmlSchemaTreeItemPtr) part; last = part; } child = child->next; } if (child != NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?, (annotation?, element*)"); } } else { /* choice + sequence */ xmlSchemaTreeItemPtr part = NULL, last = NULL; while ((IS_SCHEMA(child, "element")) || (IS_SCHEMA(child, "group")) || (IS_SCHEMA(child, "any")) || (IS_SCHEMA(child, "choice")) || (IS_SCHEMA(child, "sequence"))) { if (IS_SCHEMA(child, "element")) { part = (xmlSchemaTreeItemPtr) xmlSchemaParseElement(ctxt, schema, child, &isElemRef, 0); if (part && isElemRef) hasRefs++; } else if (IS_SCHEMA(child, "group")) { part = xmlSchemaParseModelGroupDefRef(ctxt, schema, child); if (part != NULL) hasRefs++; /* * Handle redefinitions. */ if (ctxt->isRedefine && ctxt->redef && (ctxt->redef->item->type == XML_SCHEMA_TYPE_GROUP) && part && part->children) { if ((xmlSchemaGetQNameRefName(part->children) == ctxt->redef->refName) && (xmlSchemaGetQNameRefTargetNs(part->children) == ctxt->redef->refTargetNs)) { /* * SPEC src-redefine: * (6.1) "If it has a <group> among its contents at * some level the `actual value` of whose ref * [attribute] is the same as the `actual value` of * its own name attribute plus target namespace, then * all of the following must be true:" * (6.1.1) "It must have exactly one such group." */ if (ctxt->redefCounter != 0) { xmlChar *str = NULL; xmlSchemaCustomErr(ACTXT_CAST ctxt, XML_SCHEMAP_SRC_REDEFINE, child, NULL, "The redefining model group definition " "'%s' must not contain more than one " "reference to the redefined definition", xmlSchemaFormatQName(&str, ctxt->redef->refTargetNs, ctxt->redef->refName), NULL); FREE_AND_NULL(str) part = NULL; } else if (((WXS_PARTICLE(part))->minOccurs != 1) || ((WXS_PARTICLE(part))->maxOccurs != 1)) { xmlChar *str = NULL; /* * SPEC src-redefine: * (6.1.2) "The `actual value` of both that * group's minOccurs and maxOccurs [attribute] * must be 1 (or `absent`). */ xmlSchemaCustomErr(ACTXT_CAST ctxt, XML_SCHEMAP_SRC_REDEFINE, child, NULL, "The redefining model group definition " "'%s' must not contain a reference to the " "redefined definition with a " "maxOccurs/minOccurs other than 1", xmlSchemaFormatQName(&str, ctxt->redef->refTargetNs, ctxt->redef->refName), NULL); FREE_AND_NULL(str) part = NULL; } ctxt->redef->reference = WXS_BASIC_CAST part; ctxt->redefCounter++; } } } else if (IS_SCHEMA(child, "any")) { part = (xmlSchemaTreeItemPtr) xmlSchemaParseAny(ctxt, schema, child); } else if (IS_SCHEMA(child, "choice")) { part = xmlSchemaParseModelGroup(ctxt, schema, child, XML_SCHEMA_TYPE_CHOICE, 1); } else if (IS_SCHEMA(child, "sequence")) { part = xmlSchemaParseModelGroup(ctxt, schema, child, XML_SCHEMA_TYPE_SEQUENCE, 1); } if (part != NULL) { if (last == NULL) item->children = part; else last->next = part; last = part; } child = child->next; } if (child != NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?, (element | group | choice | sequence | any)*)"); } } if ((max == 0) && (min == 0)) return (NULL); if (hasRefs) { /* * We need to resolve references. */ WXS_ADD_PENDING(ctxt, item); } if (withParticle) return ((xmlSchemaTreeItemPtr) particle); else return ((xmlSchemaTreeItemPtr) item); } /** * xmlSchemaParseRestriction: * @ctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * * parse a XML schema Restriction definition * *WARNING* this interface is highly subject to change * * Returns the type definition or NULL in case of error */ static xmlSchemaTypePtr xmlSchemaParseRestriction(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node, xmlSchemaTypeType parentType) { xmlSchemaTypePtr type; xmlNodePtr child = NULL; xmlAttrPtr attr; if ((ctxt == NULL) || (schema == NULL) || (node == NULL)) return (NULL); /* Not a component, don't create it. */ type = ctxt->ctxtType; type->flags |= XML_SCHEMAS_TYPE_DERIVATION_METHOD_RESTRICTION; /* * Check for illegal attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if ((!xmlStrEqual(attr->name, BAD_CAST "id")) && (!xmlStrEqual(attr->name, BAD_CAST "base"))) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } /* * Extract and validate attributes. */ xmlSchemaPValAttrID(ctxt, node, BAD_CAST "id"); /* * Attribute */ /* * Extract the base type. The "base" attribute is mandatory if inside * a complex type or if redefining. * * SPEC (1.2) "...otherwise (<restriction> has no <simpleType> " * among its [children]), the simple type definition which is * the {content type} of the type definition `resolved` to by * the `actual value` of the base [attribute]" */ if (xmlSchemaPValAttrQName(ctxt, schema, NULL, node, "base", &(type->baseNs), &(type->base)) == 0) { if ((type->base == NULL) && (type->type == XML_SCHEMA_TYPE_COMPLEX)) { xmlSchemaPMissingAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_MISSING, NULL, node, "base", NULL); } else if ((ctxt->isRedefine) && (type->flags & XML_SCHEMAS_TYPE_GLOBAL)) { if (type->base == NULL) { xmlSchemaPMissingAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_MISSING, NULL, node, "base", NULL); } else if ((! xmlStrEqual(type->base, type->name)) || (! xmlStrEqual(type->baseNs, type->targetNamespace))) { xmlChar *str1 = NULL, *str2 = NULL; /* * REDEFINE: SPEC src-redefine (5) * "Within the [children], each <simpleType> must have a * <restriction> among its [children] ... the `actual value` of * whose base [attribute] must be the same as the `actual value` * of its own name attribute plus target namespace;" */ xmlSchemaPCustomErrExt(ctxt, XML_SCHEMAP_SRC_REDEFINE, NULL, node, "This is a redefinition, but the QName " "value '%s' of the 'base' attribute does not match the " "type's designation '%s'", xmlSchemaFormatQName(&str1, type->baseNs, type->base), xmlSchemaFormatQName(&str2, type->targetNamespace, type->name), NULL); FREE_AND_NULL(str1); FREE_AND_NULL(str2); /* Avoid confusion and erase the values. */ type->base = NULL; type->baseNs = NULL; } } } /* * And now for the children... */ child = node->children; if (IS_SCHEMA(child, "annotation")) { /* * Add the annotation to the simple type ancestor. */ xmlSchemaAddAnnotation((xmlSchemaAnnotItemPtr) type, xmlSchemaParseAnnotation(ctxt, child, 1)); child = child->next; } if (parentType == XML_SCHEMA_TYPE_SIMPLE) { /* * Corresponds to <simpleType><restriction><simpleType>. */ if (IS_SCHEMA(child, "simpleType")) { if (type->base != NULL) { /* * src-restriction-base-or-simpleType * Either the base [attribute] or the simpleType [child] of the * <restriction> element must be present, but not both. */ xmlSchemaPContentErr(ctxt, XML_SCHEMAP_SRC_RESTRICTION_BASE_OR_SIMPLETYPE, NULL, node, child, "The attribute 'base' and the <simpleType> child are " "mutually exclusive", NULL); } else { type->baseType = (xmlSchemaTypePtr) xmlSchemaParseSimpleType(ctxt, schema, child, 0); } child = child->next; } else if (type->base == NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_SRC_RESTRICTION_BASE_OR_SIMPLETYPE, NULL, node, child, "Either the attribute 'base' or a <simpleType> child " "must be present", NULL); } } else if (parentType == XML_SCHEMA_TYPE_COMPLEX_CONTENT) { /* * Corresponds to <complexType><complexContent><restriction>... * followed by: * * Model groups <all>, <choice> and <sequence>. */ if (IS_SCHEMA(child, "all")) { type->subtypes = (xmlSchemaTypePtr) xmlSchemaParseModelGroup(ctxt, schema, child, XML_SCHEMA_TYPE_ALL, 1); child = child->next; } else if (IS_SCHEMA(child, "choice")) { type->subtypes = (xmlSchemaTypePtr) xmlSchemaParseModelGroup(ctxt, schema, child, XML_SCHEMA_TYPE_CHOICE, 1); child = child->next; } else if (IS_SCHEMA(child, "sequence")) { type->subtypes = (xmlSchemaTypePtr) xmlSchemaParseModelGroup(ctxt, schema, child, XML_SCHEMA_TYPE_SEQUENCE, 1); child = child->next; /* * Model group reference <group>. */ } else if (IS_SCHEMA(child, "group")) { type->subtypes = (xmlSchemaTypePtr) xmlSchemaParseModelGroupDefRef(ctxt, schema, child); /* * Note that the reference will be resolved in * xmlSchemaResolveTypeReferences(); */ child = child->next; } } else if (parentType == XML_SCHEMA_TYPE_SIMPLE_CONTENT) { /* * Corresponds to <complexType><simpleContent><restriction>... * * "1.1 the simple type definition corresponding to the <simpleType> * among the [children] of <restriction> if there is one;" */ if (IS_SCHEMA(child, "simpleType")) { /* * We will store the to-be-restricted simple type in * type->contentTypeDef *temporarily*. */ type->contentTypeDef = (xmlSchemaTypePtr) xmlSchemaParseSimpleType(ctxt, schema, child, 0); if ( type->contentTypeDef == NULL) return (NULL); child = child->next; } } if ((parentType == XML_SCHEMA_TYPE_SIMPLE) || (parentType == XML_SCHEMA_TYPE_SIMPLE_CONTENT)) { xmlSchemaFacetPtr facet, lastfacet = NULL; /* * Corresponds to <complexType><simpleContent><restriction>... * <simpleType><restriction>... */ /* * Add the facets to the simple type ancestor. */ /* * TODO: Datatypes: 4.1.3 Constraints on XML Representation of * Simple Type Definition Schema Representation Constraint: * *Single Facet Value* */ while ((IS_SCHEMA(child, "minInclusive")) || (IS_SCHEMA(child, "minExclusive")) || (IS_SCHEMA(child, "maxInclusive")) || (IS_SCHEMA(child, "maxExclusive")) || (IS_SCHEMA(child, "totalDigits")) || (IS_SCHEMA(child, "fractionDigits")) || (IS_SCHEMA(child, "pattern")) || (IS_SCHEMA(child, "enumeration")) || (IS_SCHEMA(child, "whiteSpace")) || (IS_SCHEMA(child, "length")) || (IS_SCHEMA(child, "maxLength")) || (IS_SCHEMA(child, "minLength"))) { facet = xmlSchemaParseFacet(ctxt, schema, child); if (facet != NULL) { if (lastfacet == NULL) type->facets = facet; else lastfacet->next = facet; lastfacet = facet; lastfacet->next = NULL; } child = child->next; } /* * Create links for derivation and validation. */ if (type->facets != NULL) { xmlSchemaFacetLinkPtr facetLink, lastFacetLink = NULL; facet = type->facets; do { facetLink = (xmlSchemaFacetLinkPtr) xmlMalloc(sizeof(xmlSchemaFacetLink)); if (facetLink == NULL) { xmlSchemaPErrMemory(ctxt, "allocating a facet link", NULL); xmlFree(facetLink); return (NULL); } facetLink->facet = facet; facetLink->next = NULL; if (lastFacetLink == NULL) type->facetSet = facetLink; else lastFacetLink->next = facetLink; lastFacetLink = facetLink; facet = facet->next; } while (facet != NULL); } } if (type->type == XML_SCHEMA_TYPE_COMPLEX) { /* * Attribute uses/declarations. */ if (xmlSchemaParseLocalAttributes(ctxt, schema, &child, (xmlSchemaItemListPtr *) &(type->attrUses), XML_SCHEMA_TYPE_RESTRICTION, NULL) == -1) return(NULL); /* * Attribute wildcard. */ if (IS_SCHEMA(child, "anyAttribute")) { type->attributeWildcard = xmlSchemaParseAnyAttribute(ctxt, schema, child); child = child->next; } } if (child != NULL) { if (parentType == XML_SCHEMA_TYPE_COMPLEX_CONTENT) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "annotation?, (group | all | choice | sequence)?, " "((attribute | attributeGroup)*, anyAttribute?))"); } else if (parentType == XML_SCHEMA_TYPE_SIMPLE_CONTENT) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?, (simpleType?, (minExclusive | minInclusive | " "maxExclusive | maxInclusive | totalDigits | fractionDigits | " "length | minLength | maxLength | enumeration | whiteSpace | " "pattern)*)?, ((attribute | attributeGroup)*, anyAttribute?))"); } else { /* Simple type */ xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?, (simpleType?, (minExclusive | minInclusive | " "maxExclusive | maxInclusive | totalDigits | fractionDigits | " "length | minLength | maxLength | enumeration | whiteSpace | " "pattern)*))"); } } return (NULL); } /** * xmlSchemaParseExtension: * @ctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * * Parses an <extension>, which is found inside a * <simpleContent> or <complexContent>. * *WARNING* this interface is highly subject to change. * * TODO: Returns the type definition or NULL in case of error */ static xmlSchemaTypePtr xmlSchemaParseExtension(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node, xmlSchemaTypeType parentType) { xmlSchemaTypePtr type; xmlNodePtr child = NULL; xmlAttrPtr attr; if ((ctxt == NULL) || (schema == NULL) || (node == NULL)) return (NULL); /* Not a component, don't create it. */ type = ctxt->ctxtType; type->flags |= XML_SCHEMAS_TYPE_DERIVATION_METHOD_EXTENSION; /* * Check for illegal attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if ((!xmlStrEqual(attr->name, BAD_CAST "id")) && (!xmlStrEqual(attr->name, BAD_CAST "base"))) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } xmlSchemaPValAttrID(ctxt, node, BAD_CAST "id"); /* * Attribute "base" - mandatory. */ if ((xmlSchemaPValAttrQName(ctxt, schema, NULL, node, "base", &(type->baseNs), &(type->base)) == 0) && (type->base == NULL)) { xmlSchemaPMissingAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_MISSING, NULL, node, "base", NULL); } /* * And now for the children... */ child = node->children; if (IS_SCHEMA(child, "annotation")) { /* * Add the annotation to the type ancestor. */ xmlSchemaAddAnnotation((xmlSchemaAnnotItemPtr) type, xmlSchemaParseAnnotation(ctxt, child, 1)); child = child->next; } if (parentType == XML_SCHEMA_TYPE_COMPLEX_CONTENT) { /* * Corresponds to <complexType><complexContent><extension>... and: * * Model groups <all>, <choice>, <sequence> and <group>. */ if (IS_SCHEMA(child, "all")) { type->subtypes = (xmlSchemaTypePtr) xmlSchemaParseModelGroup(ctxt, schema, child, XML_SCHEMA_TYPE_ALL, 1); child = child->next; } else if (IS_SCHEMA(child, "choice")) { type->subtypes = (xmlSchemaTypePtr) xmlSchemaParseModelGroup(ctxt, schema, child, XML_SCHEMA_TYPE_CHOICE, 1); child = child->next; } else if (IS_SCHEMA(child, "sequence")) { type->subtypes = (xmlSchemaTypePtr) xmlSchemaParseModelGroup(ctxt, schema, child, XML_SCHEMA_TYPE_SEQUENCE, 1); child = child->next; } else if (IS_SCHEMA(child, "group")) { type->subtypes = (xmlSchemaTypePtr) xmlSchemaParseModelGroupDefRef(ctxt, schema, child); /* * Note that the reference will be resolved in * xmlSchemaResolveTypeReferences(); */ child = child->next; } } if (child != NULL) { /* * Attribute uses/declarations. */ if (xmlSchemaParseLocalAttributes(ctxt, schema, &child, (xmlSchemaItemListPtr *) &(type->attrUses), XML_SCHEMA_TYPE_EXTENSION, NULL) == -1) return(NULL); /* * Attribute wildcard. */ if (IS_SCHEMA(child, "anyAttribute")) { ctxt->ctxtType->attributeWildcard = xmlSchemaParseAnyAttribute(ctxt, schema, child); child = child->next; } } if (child != NULL) { if (parentType == XML_SCHEMA_TYPE_COMPLEX_CONTENT) { /* Complex content extension. */ xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?, ((group | all | choice | sequence)?, " "((attribute | attributeGroup)*, anyAttribute?)))"); } else { /* Simple content extension. */ xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?, ((attribute | attributeGroup)*, " "anyAttribute?))"); } } return (NULL); } /** * xmlSchemaParseSimpleContent: * @ctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * * parse a XML schema SimpleContent definition * *WARNING* this interface is highly subject to change * * Returns the type definition or NULL in case of error */ static int xmlSchemaParseSimpleContent(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node, int *hasRestrictionOrExtension) { xmlSchemaTypePtr type; xmlNodePtr child = NULL; xmlAttrPtr attr; if ((ctxt == NULL) || (schema == NULL) || (node == NULL) || (hasRestrictionOrExtension == NULL)) return (-1); *hasRestrictionOrExtension = 0; /* Not a component, don't create it. */ type = ctxt->ctxtType; type->contentType = XML_SCHEMA_CONTENT_SIMPLE; /* * Check for illegal attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if ((!xmlStrEqual(attr->name, BAD_CAST "id"))) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } xmlSchemaPValAttrID(ctxt, node, BAD_CAST "id"); /* * And now for the children... */ child = node->children; if (IS_SCHEMA(child, "annotation")) { /* * Add the annotation to the complex type ancestor. */ xmlSchemaAddAnnotation((xmlSchemaAnnotItemPtr) type, xmlSchemaParseAnnotation(ctxt, child, 1)); child = child->next; } if (child == NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_MISSING, NULL, node, NULL, NULL, "(annotation?, (restriction | extension))"); } if (child == NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_MISSING, NULL, node, NULL, NULL, "(annotation?, (restriction | extension))"); } if (IS_SCHEMA(child, "restriction")) { xmlSchemaParseRestriction(ctxt, schema, child, XML_SCHEMA_TYPE_SIMPLE_CONTENT); (*hasRestrictionOrExtension) = 1; child = child->next; } else if (IS_SCHEMA(child, "extension")) { xmlSchemaParseExtension(ctxt, schema, child, XML_SCHEMA_TYPE_SIMPLE_CONTENT); (*hasRestrictionOrExtension) = 1; child = child->next; } if (child != NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?, (restriction | extension))"); } return (0); } /** * xmlSchemaParseComplexContent: * @ctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * * parse a XML schema ComplexContent definition * *WARNING* this interface is highly subject to change * * Returns the type definition or NULL in case of error */ static int xmlSchemaParseComplexContent(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node, int *hasRestrictionOrExtension) { xmlSchemaTypePtr type; xmlNodePtr child = NULL; xmlAttrPtr attr; if ((ctxt == NULL) || (schema == NULL) || (node == NULL) || (hasRestrictionOrExtension == NULL)) return (-1); *hasRestrictionOrExtension = 0; /* Not a component, don't create it. */ type = ctxt->ctxtType; /* * Check for illegal attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if ((!xmlStrEqual(attr->name, BAD_CAST "id")) && (!xmlStrEqual(attr->name, BAD_CAST "mixed"))) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } xmlSchemaPValAttrID(ctxt, node, BAD_CAST "id"); /* * Set the 'mixed' on the complex type ancestor. */ if (xmlGetBooleanProp(ctxt, node, "mixed", 0)) { if ((type->flags & XML_SCHEMAS_TYPE_MIXED) == 0) type->flags |= XML_SCHEMAS_TYPE_MIXED; } child = node->children; if (IS_SCHEMA(child, "annotation")) { /* * Add the annotation to the complex type ancestor. */ xmlSchemaAddAnnotation((xmlSchemaAnnotItemPtr) type, xmlSchemaParseAnnotation(ctxt, child, 1)); child = child->next; } if (child == NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_MISSING, NULL, node, NULL, NULL, "(annotation?, (restriction | extension))"); } if (child == NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_MISSING, NULL, node, NULL, NULL, "(annotation?, (restriction | extension))"); } if (IS_SCHEMA(child, "restriction")) { xmlSchemaParseRestriction(ctxt, schema, child, XML_SCHEMA_TYPE_COMPLEX_CONTENT); (*hasRestrictionOrExtension) = 1; child = child->next; } else if (IS_SCHEMA(child, "extension")) { xmlSchemaParseExtension(ctxt, schema, child, XML_SCHEMA_TYPE_COMPLEX_CONTENT); (*hasRestrictionOrExtension) = 1; child = child->next; } if (child != NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?, (restriction | extension))"); } return (0); } /** * xmlSchemaParseComplexType: * @ctxt: a schema validation context * @schema: the schema being built * @node: a subtree containing XML Schema information * * parse a XML schema Complex Type definition * *WARNING* this interface is highly subject to change * * Returns the type definition or NULL in case of error */ static xmlSchemaTypePtr xmlSchemaParseComplexType(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema, xmlNodePtr node, int topLevel) { xmlSchemaTypePtr type, ctxtType; xmlNodePtr child = NULL; const xmlChar *name = NULL; xmlAttrPtr attr; const xmlChar *attrValue; #ifdef ENABLE_NAMED_LOCALS char buf[40]; #endif int final = 0, block = 0, hasRestrictionOrExtension = 0; if ((ctxt == NULL) || (schema == NULL) || (node == NULL)) return (NULL); ctxtType = ctxt->ctxtType; if (topLevel) { attr = xmlSchemaGetPropNode(node, "name"); if (attr == NULL) { xmlSchemaPMissingAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_MISSING, NULL, node, "name", NULL); return (NULL); } else if (xmlSchemaPValAttrNode(ctxt, NULL, attr, xmlSchemaGetBuiltInType(XML_SCHEMAS_NCNAME), &name) != 0) { return (NULL); } } if (topLevel == 0) { /* * Parse as local complex type definition. */ #ifdef ENABLE_NAMED_LOCALS snprintf(buf, 39, "#CT%d", ctxt->counter++ + 1); type = xmlSchemaAddType(ctxt, schema, XML_SCHEMA_TYPE_COMPLEX, xmlDictLookup(ctxt->dict, (const xmlChar *)buf, -1), ctxt->targetNamespace, node, 0); #else type = xmlSchemaAddType(ctxt, schema, XML_SCHEMA_TYPE_COMPLEX, NULL, ctxt->targetNamespace, node, 0); #endif if (type == NULL) return (NULL); name = type->name; type->node = node; type->type = XML_SCHEMA_TYPE_COMPLEX; /* * TODO: We need the target namespace. */ } else { /* * Parse as global complex type definition. */ type = xmlSchemaAddType(ctxt, schema, XML_SCHEMA_TYPE_COMPLEX, name, ctxt->targetNamespace, node, 1); if (type == NULL) return (NULL); type->node = node; type->type = XML_SCHEMA_TYPE_COMPLEX; type->flags |= XML_SCHEMAS_TYPE_GLOBAL; } type->targetNamespace = ctxt->targetNamespace; /* * Handle attributes. */ attr = node->properties; while (attr != NULL) { if (attr->ns == NULL) { if (xmlStrEqual(attr->name, BAD_CAST "id")) { /* * Attribute "id". */ xmlSchemaPValAttrID(ctxt, node, BAD_CAST "id"); } else if (xmlStrEqual(attr->name, BAD_CAST "mixed")) { /* * Attribute "mixed". */ if (xmlSchemaPGetBoolNodeValue(ctxt, NULL, (xmlNodePtr) attr)) type->flags |= XML_SCHEMAS_TYPE_MIXED; } else if (topLevel) { /* * Attributes of global complex type definitions. */ if (xmlStrEqual(attr->name, BAD_CAST "name")) { /* Pass. */ } else if (xmlStrEqual(attr->name, BAD_CAST "abstract")) { /* * Attribute "abstract". */ if (xmlSchemaPGetBoolNodeValue(ctxt, NULL, (xmlNodePtr) attr)) type->flags |= XML_SCHEMAS_TYPE_ABSTRACT; } else if (xmlStrEqual(attr->name, BAD_CAST "final")) { /* * Attribute "final". */ attrValue = xmlSchemaGetNodeContent(ctxt, (xmlNodePtr) attr); if (xmlSchemaPValAttrBlockFinal(attrValue, &(type->flags), -1, XML_SCHEMAS_TYPE_FINAL_EXTENSION, XML_SCHEMAS_TYPE_FINAL_RESTRICTION, -1, -1, -1) != 0) { xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, NULL, (xmlNodePtr) attr, NULL, "(#all | List of (extension | restriction))", attrValue, NULL, NULL, NULL); } else final = 1; } else if (xmlStrEqual(attr->name, BAD_CAST "block")) { /* * Attribute "block". */ attrValue = xmlSchemaGetNodeContent(ctxt, (xmlNodePtr) attr); if (xmlSchemaPValAttrBlockFinal(attrValue, &(type->flags), -1, XML_SCHEMAS_TYPE_BLOCK_EXTENSION, XML_SCHEMAS_TYPE_BLOCK_RESTRICTION, -1, -1, -1) != 0) { xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, NULL, (xmlNodePtr) attr, NULL, "(#all | List of (extension | restriction)) ", attrValue, NULL, NULL, NULL); } else block = 1; } else { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) { xmlSchemaPIllegalAttrErr(ctxt, XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); } attr = attr->next; } if (! block) { /* * Apply default "block" values. */ if (schema->flags & XML_SCHEMAS_BLOCK_DEFAULT_RESTRICTION) type->flags |= XML_SCHEMAS_TYPE_BLOCK_RESTRICTION; if (schema->flags & XML_SCHEMAS_BLOCK_DEFAULT_EXTENSION) type->flags |= XML_SCHEMAS_TYPE_BLOCK_EXTENSION; } if (! final) { /* * Apply default "block" values. */ if (schema->flags & XML_SCHEMAS_FINAL_DEFAULT_RESTRICTION) type->flags |= XML_SCHEMAS_TYPE_FINAL_RESTRICTION; if (schema->flags & XML_SCHEMAS_FINAL_DEFAULT_EXTENSION) type->flags |= XML_SCHEMAS_TYPE_FINAL_EXTENSION; } /* * And now for the children... */ child = node->children; if (IS_SCHEMA(child, "annotation")) { type->annot = xmlSchemaParseAnnotation(ctxt, child, 1); child = child->next; } ctxt->ctxtType = type; if (IS_SCHEMA(child, "simpleContent")) { /* * <complexType><simpleContent>... * 3.4.3 : 2.2 * Specifying mixed='true' when the <simpleContent> * alternative is chosen has no effect */ if (type->flags & XML_SCHEMAS_TYPE_MIXED) type->flags ^= XML_SCHEMAS_TYPE_MIXED; xmlSchemaParseSimpleContent(ctxt, schema, child, &hasRestrictionOrExtension); child = child->next; } else if (IS_SCHEMA(child, "complexContent")) { /* * <complexType><complexContent>... */ type->contentType = XML_SCHEMA_CONTENT_EMPTY; xmlSchemaParseComplexContent(ctxt, schema, child, &hasRestrictionOrExtension); child = child->next; } else { /* * E.g <complexType><sequence>... or <complexType><attribute>... etc. * * SPEC * "...the third alternative (neither <simpleContent> nor * <complexContent>) is chosen. This case is understood as shorthand * for complex content restricting the `ur-type definition`, and the * details of the mappings should be modified as necessary. */ type->baseType = xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYTYPE); type->flags |= XML_SCHEMAS_TYPE_DERIVATION_METHOD_RESTRICTION; /* * Parse model groups. */ if (IS_SCHEMA(child, "all")) { type->subtypes = (xmlSchemaTypePtr) xmlSchemaParseModelGroup(ctxt, schema, child, XML_SCHEMA_TYPE_ALL, 1); child = child->next; } else if (IS_SCHEMA(child, "choice")) { type->subtypes = (xmlSchemaTypePtr) xmlSchemaParseModelGroup(ctxt, schema, child, XML_SCHEMA_TYPE_CHOICE, 1); child = child->next; } else if (IS_SCHEMA(child, "sequence")) { type->subtypes = (xmlSchemaTypePtr) xmlSchemaParseModelGroup(ctxt, schema, child, XML_SCHEMA_TYPE_SEQUENCE, 1); child = child->next; } else if (IS_SCHEMA(child, "group")) { type->subtypes = (xmlSchemaTypePtr) xmlSchemaParseModelGroupDefRef(ctxt, schema, child); /* * Note that the reference will be resolved in * xmlSchemaResolveTypeReferences(); */ child = child->next; } /* * Parse attribute decls/refs. */ if (xmlSchemaParseLocalAttributes(ctxt, schema, &child, (xmlSchemaItemListPtr *) &(type->attrUses), XML_SCHEMA_TYPE_RESTRICTION, NULL) == -1) return(NULL); /* * Parse attribute wildcard. */ if (IS_SCHEMA(child, "anyAttribute")) { type->attributeWildcard = xmlSchemaParseAnyAttribute(ctxt, schema, child); child = child->next; } } if (child != NULL) { xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, NULL, node, child, NULL, "(annotation?, (simpleContent | complexContent | " "((group | all | choice | sequence)?, ((attribute | " "attributeGroup)*, anyAttribute?))))"); } /* * REDEFINE: SPEC src-redefine (5) */ if (topLevel && ctxt->isRedefine && (! hasRestrictionOrExtension)) { xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_SRC_REDEFINE, NULL, node, "This is a redefinition, thus the " "<complexType> must have a <restriction> or <extension> " "grand-child", NULL); } ctxt->ctxtType = ctxtType; return (type); } /************************************************************************ * * * Validating using Schemas * * * ************************************************************************/ /************************************************************************ * * * Reading/Writing Schemas * * * ************************************************************************/ #if 0 /* Will be enabled if it is clear what options are needed. */ /** * xmlSchemaParserCtxtSetOptions: * @ctxt: a schema parser context * @options: a combination of xmlSchemaParserOption * * Sets the options to be used during the parse. * * Returns 0 in case of success, -1 in case of an * API error. */ static int xmlSchemaParserCtxtSetOptions(xmlSchemaParserCtxtPtr ctxt, int options) { int i; if (ctxt == NULL) return (-1); /* * WARNING: Change the start value if adding to the * xmlSchemaParseOption. */ for (i = 1; i < (int) sizeof(int) * 8; i++) { if (options & 1<<i) { return (-1); } } ctxt->options = options; return (0); } /** * xmlSchemaValidCtxtGetOptions: * @ctxt: a schema parser context * * Returns the option combination of the parser context. */ static int xmlSchemaParserCtxtGetOptions(xmlSchemaParserCtxtPtr ctxt) { if (ctxt == NULL) return (-1); else return (ctxt->options); } #endif /** * xmlSchemaNewParserCtxt: * @URL: the location of the schema * * Create an XML Schemas parse context for that file/resource expected * to contain an XML Schemas file. * * Returns the parser context or NULL in case of error */ xmlSchemaParserCtxtPtr xmlSchemaNewParserCtxt(const char *URL) { xmlSchemaParserCtxtPtr ret; if (URL == NULL) return (NULL); ret = xmlSchemaParserCtxtCreate(); if (ret == NULL) return(NULL); ret->dict = xmlDictCreate(); ret->URL = xmlDictLookup(ret->dict, (const xmlChar *) URL, -1); return (ret); } /** * xmlSchemaNewMemParserCtxt: * @buffer: a pointer to a char array containing the schemas * @size: the size of the array * * Create an XML Schemas parse context for that memory buffer expected * to contain an XML Schemas file. * * Returns the parser context or NULL in case of error */ xmlSchemaParserCtxtPtr xmlSchemaNewMemParserCtxt(const char *buffer, int size) { xmlSchemaParserCtxtPtr ret; if ((buffer == NULL) || (size <= 0)) return (NULL); ret = xmlSchemaParserCtxtCreate(); if (ret == NULL) return(NULL); ret->buffer = buffer; ret->size = size; ret->dict = xmlDictCreate(); return (ret); } /** * xmlSchemaNewDocParserCtxt: * @doc: a preparsed document tree * * Create an XML Schemas parse context for that document. * NB. The document may be modified during the parsing process. * * Returns the parser context or NULL in case of error */ xmlSchemaParserCtxtPtr xmlSchemaNewDocParserCtxt(xmlDocPtr doc) { xmlSchemaParserCtxtPtr ret; if (doc == NULL) return (NULL); ret = xmlSchemaParserCtxtCreate(); if (ret == NULL) return(NULL); ret->doc = doc; ret->dict = xmlDictCreate(); /* The application has responsibility for the document */ ret->preserve = 1; return (ret); } /** * xmlSchemaFreeParserCtxt: * @ctxt: the schema parser context * * Free the resources associated to the schema parser context */ void xmlSchemaFreeParserCtxt(xmlSchemaParserCtxtPtr ctxt) { if (ctxt == NULL) return; if (ctxt->doc != NULL && !ctxt->preserve) xmlFreeDoc(ctxt->doc); if (ctxt->vctxt != NULL) { xmlSchemaFreeValidCtxt(ctxt->vctxt); } if (ctxt->ownsConstructor && (ctxt->constructor != NULL)) { xmlSchemaConstructionCtxtFree(ctxt->constructor); ctxt->constructor = NULL; ctxt->ownsConstructor = 0; } if (ctxt->attrProhibs != NULL) xmlSchemaItemListFree(ctxt->attrProhibs); xmlDictFree(ctxt->dict); xmlFree(ctxt); } /************************************************************************ * * * Building the content models * * * ************************************************************************/ /** * xmlSchemaBuildContentModelForSubstGroup: * * Returns 1 if nillable, 0 otherwise */ static int xmlSchemaBuildContentModelForSubstGroup(xmlSchemaParserCtxtPtr pctxt, xmlSchemaParticlePtr particle, int counter, xmlAutomataStatePtr end) { xmlAutomataStatePtr start, tmp; xmlSchemaElementPtr elemDecl, member; xmlSchemaSubstGroupPtr substGroup; int i; int ret = 0; elemDecl = (xmlSchemaElementPtr) particle->children; /* * Wrap the substitution group with a CHOICE. */ start = pctxt->state; if (end == NULL) end = xmlAutomataNewState(pctxt->am); substGroup = xmlSchemaSubstGroupGet(pctxt, elemDecl); if (substGroup == NULL) { xmlSchemaPErr(pctxt, WXS_ITEM_NODE(particle), XML_SCHEMAP_INTERNAL, "Internal error: xmlSchemaBuildContentModelForSubstGroup, " "declaration is marked having a subst. group but none " "available.\n", elemDecl->name, NULL); return(0); } if (counter >= 0) { /* * NOTE that we put the declaration in, even if it's abstract. * However, an error will be raised during *validation* if an element * information item shall be validated against an abstract element * declaration. */ tmp = xmlAutomataNewCountedTrans(pctxt->am, start, NULL, counter); xmlAutomataNewTransition2(pctxt->am, tmp, end, elemDecl->name, elemDecl->targetNamespace, elemDecl); /* * Add subst. group members. */ for (i = 0; i < substGroup->members->nbItems; i++) { member = (xmlSchemaElementPtr) substGroup->members->items[i]; xmlAutomataNewTransition2(pctxt->am, tmp, end, member->name, member->targetNamespace, member); } } else if (particle->maxOccurs == 1) { /* * NOTE that we put the declaration in, even if it's abstract, */ xmlAutomataNewEpsilon(pctxt->am, xmlAutomataNewTransition2(pctxt->am, start, NULL, elemDecl->name, elemDecl->targetNamespace, elemDecl), end); /* * Add subst. group members. */ for (i = 0; i < substGroup->members->nbItems; i++) { member = (xmlSchemaElementPtr) substGroup->members->items[i]; /* * NOTE: This fixes bug #341150. xmlAutomataNewOnceTrans2() * was incorrectly used instead of xmlAutomataNewTransition2() * (seems like a copy&paste bug from the XML_SCHEMA_TYPE_ALL * section in xmlSchemaBuildAContentModel() ). * TODO: Check if xmlAutomataNewOnceTrans2() was instead * intended for the above "counter" section originally. I.e., * check xs:all with subst-groups. * * tmp = xmlAutomataNewOnceTrans2(pctxt->am, start, NULL, * member->name, member->targetNamespace, * 1, 1, member); */ tmp = xmlAutomataNewTransition2(pctxt->am, start, NULL, member->name, member->targetNamespace, member); xmlAutomataNewEpsilon(pctxt->am, tmp, end); } } else { xmlAutomataStatePtr hop; int maxOccurs = particle->maxOccurs == UNBOUNDED ? UNBOUNDED : particle->maxOccurs - 1; int minOccurs = particle->minOccurs < 1 ? 0 : particle->minOccurs - 1; counter = xmlAutomataNewCounter(pctxt->am, minOccurs, maxOccurs); hop = xmlAutomataNewState(pctxt->am); xmlAutomataNewEpsilon(pctxt->am, xmlAutomataNewTransition2(pctxt->am, start, NULL, elemDecl->name, elemDecl->targetNamespace, elemDecl), hop); /* * Add subst. group members. */ for (i = 0; i < substGroup->members->nbItems; i++) { member = (xmlSchemaElementPtr) substGroup->members->items[i]; xmlAutomataNewEpsilon(pctxt->am, xmlAutomataNewTransition2(pctxt->am, start, NULL, member->name, member->targetNamespace, member), hop); } xmlAutomataNewCountedTrans(pctxt->am, hop, start, counter); xmlAutomataNewCounterTrans(pctxt->am, hop, end, counter); } if (particle->minOccurs == 0) { xmlAutomataNewEpsilon(pctxt->am, start, end); ret = 1; } pctxt->state = end; return(ret); } /** * xmlSchemaBuildContentModelForElement: * * Returns 1 if nillable, 0 otherwise */ static int xmlSchemaBuildContentModelForElement(xmlSchemaParserCtxtPtr ctxt, xmlSchemaParticlePtr particle) { int ret = 0; if (((xmlSchemaElementPtr) particle->children)->flags & XML_SCHEMAS_ELEM_SUBST_GROUP_HEAD) { /* * Substitution groups. */ ret = xmlSchemaBuildContentModelForSubstGroup(ctxt, particle, -1, NULL); } else { xmlSchemaElementPtr elemDecl; xmlAutomataStatePtr start; elemDecl = (xmlSchemaElementPtr) particle->children; if (elemDecl->flags & XML_SCHEMAS_ELEM_ABSTRACT) return(0); if (particle->maxOccurs == 1) { start = ctxt->state; ctxt->state = xmlAutomataNewTransition2(ctxt->am, start, NULL, elemDecl->name, elemDecl->targetNamespace, elemDecl); } else if ((particle->maxOccurs >= UNBOUNDED) && (particle->minOccurs < 2)) { /* Special case. */ start = ctxt->state; ctxt->state = xmlAutomataNewTransition2(ctxt->am, start, NULL, elemDecl->name, elemDecl->targetNamespace, elemDecl); ctxt->state = xmlAutomataNewTransition2(ctxt->am, ctxt->state, ctxt->state, elemDecl->name, elemDecl->targetNamespace, elemDecl); } else { int counter; int maxOccurs = particle->maxOccurs == UNBOUNDED ? UNBOUNDED : particle->maxOccurs - 1; int minOccurs = particle->minOccurs < 1 ? 0 : particle->minOccurs - 1; start = xmlAutomataNewEpsilon(ctxt->am, ctxt->state, NULL); counter = xmlAutomataNewCounter(ctxt->am, minOccurs, maxOccurs); ctxt->state = xmlAutomataNewTransition2(ctxt->am, start, NULL, elemDecl->name, elemDecl->targetNamespace, elemDecl); xmlAutomataNewCountedTrans(ctxt->am, ctxt->state, start, counter); ctxt->state = xmlAutomataNewCounterTrans(ctxt->am, ctxt->state, NULL, counter); } if (particle->minOccurs == 0) { xmlAutomataNewEpsilon(ctxt->am, start, ctxt->state); ret = 1; } } return(ret); } /** * xmlSchemaBuildAContentModel: * @ctxt: the schema parser context * @particle: the particle component * @name: the complex type's name whose content is being built * * Create the automaton for the {content type} of a complex type. * * Returns 1 if the content is nillable, 0 otherwise */ static int xmlSchemaBuildAContentModel(xmlSchemaParserCtxtPtr pctxt, xmlSchemaParticlePtr particle) { int ret = 0, tmp2; if (particle == NULL) { PERROR_INT("xmlSchemaBuildAContentModel", "particle is NULL"); return(1); } if (particle->children == NULL) { /* * Just return in this case. A missing "term" of the particle * might arise due to an invalid "term" component. */ return(1); } switch (particle->children->type) { case XML_SCHEMA_TYPE_ANY: { xmlAutomataStatePtr start, end; xmlSchemaWildcardPtr wild; xmlSchemaWildcardNsPtr ns; wild = (xmlSchemaWildcardPtr) particle->children; start = pctxt->state; end = xmlAutomataNewState(pctxt->am); if (particle->maxOccurs == 1) { if (wild->any == 1) { /* * We need to add both transitions: * * 1. the {"*", "*"} for elements in a namespace. */ pctxt->state = xmlAutomataNewTransition2(pctxt->am, start, NULL, BAD_CAST "*", BAD_CAST "*", wild); xmlAutomataNewEpsilon(pctxt->am, pctxt->state, end); /* * 2. the {"*"} for elements in no namespace. */ pctxt->state = xmlAutomataNewTransition2(pctxt->am, start, NULL, BAD_CAST "*", NULL, wild); xmlAutomataNewEpsilon(pctxt->am, pctxt->state, end); } else if (wild->nsSet != NULL) { ns = wild->nsSet; do { pctxt->state = start; pctxt->state = xmlAutomataNewTransition2(pctxt->am, pctxt->state, NULL, BAD_CAST "*", ns->value, wild); xmlAutomataNewEpsilon(pctxt->am, pctxt->state, end); ns = ns->next; } while (ns != NULL); } else if (wild->negNsSet != NULL) { pctxt->state = xmlAutomataNewNegTrans(pctxt->am, start, end, BAD_CAST "*", wild->negNsSet->value, wild); } } else { int counter; xmlAutomataStatePtr hop; int maxOccurs = particle->maxOccurs == UNBOUNDED ? UNBOUNDED : particle->maxOccurs - 1; int minOccurs = particle->minOccurs < 1 ? 0 : particle->minOccurs - 1; counter = xmlAutomataNewCounter(pctxt->am, minOccurs, maxOccurs); hop = xmlAutomataNewState(pctxt->am); if (wild->any == 1) { pctxt->state = xmlAutomataNewTransition2(pctxt->am, start, NULL, BAD_CAST "*", BAD_CAST "*", wild); xmlAutomataNewEpsilon(pctxt->am, pctxt->state, hop); pctxt->state = xmlAutomataNewTransition2(pctxt->am, start, NULL, BAD_CAST "*", NULL, wild); xmlAutomataNewEpsilon(pctxt->am, pctxt->state, hop); } else if (wild->nsSet != NULL) { ns = wild->nsSet; do { pctxt->state = xmlAutomataNewTransition2(pctxt->am, start, NULL, BAD_CAST "*", ns->value, wild); xmlAutomataNewEpsilon(pctxt->am, pctxt->state, hop); ns = ns->next; } while (ns != NULL); } else if (wild->negNsSet != NULL) { pctxt->state = xmlAutomataNewNegTrans(pctxt->am, start, hop, BAD_CAST "*", wild->negNsSet->value, wild); } xmlAutomataNewCountedTrans(pctxt->am, hop, start, counter); xmlAutomataNewCounterTrans(pctxt->am, hop, end, counter); } if (particle->minOccurs == 0) { xmlAutomataNewEpsilon(pctxt->am, start, end); ret = 1; } pctxt->state = end; break; } case XML_SCHEMA_TYPE_ELEMENT: ret = xmlSchemaBuildContentModelForElement(pctxt, particle); break; case XML_SCHEMA_TYPE_SEQUENCE:{ xmlSchemaTreeItemPtr sub; ret = 1; /* * If max and min occurrences are default (1) then * simply iterate over the particles of the <sequence>. */ if ((particle->minOccurs == 1) && (particle->maxOccurs == 1)) { sub = particle->children->children; while (sub != NULL) { tmp2 = xmlSchemaBuildAContentModel(pctxt, (xmlSchemaParticlePtr) sub); if (tmp2 != 1) ret = 0; sub = sub->next; } } else { xmlAutomataStatePtr oldstate = pctxt->state; if (particle->maxOccurs >= UNBOUNDED) { if (particle->minOccurs > 1) { xmlAutomataStatePtr tmp; int counter; pctxt->state = xmlAutomataNewEpsilon(pctxt->am, oldstate, NULL); oldstate = pctxt->state; counter = xmlAutomataNewCounter(pctxt->am, particle->minOccurs - 1, UNBOUNDED); sub = particle->children->children; while (sub != NULL) { tmp2 = xmlSchemaBuildAContentModel(pctxt, (xmlSchemaParticlePtr) sub); if (tmp2 != 1) ret = 0; sub = sub->next; } tmp = pctxt->state; xmlAutomataNewCountedTrans(pctxt->am, tmp, oldstate, counter); pctxt->state = xmlAutomataNewCounterTrans(pctxt->am, tmp, NULL, counter); if (ret == 1) xmlAutomataNewEpsilon(pctxt->am, oldstate, pctxt->state); } else { pctxt->state = xmlAutomataNewEpsilon(pctxt->am, oldstate, NULL); oldstate = pctxt->state; sub = particle->children->children; while (sub != NULL) { tmp2 = xmlSchemaBuildAContentModel(pctxt, (xmlSchemaParticlePtr) sub); if (tmp2 != 1) ret = 0; sub = sub->next; } xmlAutomataNewEpsilon(pctxt->am, pctxt->state, oldstate); /* * epsilon needed to block previous trans from * being allowed to enter back from another * construct */ pctxt->state = xmlAutomataNewEpsilon(pctxt->am, pctxt->state, NULL); if (particle->minOccurs == 0) { xmlAutomataNewEpsilon(pctxt->am, oldstate, pctxt->state); ret = 1; } } } else if ((particle->maxOccurs > 1) || (particle->minOccurs > 1)) { xmlAutomataStatePtr tmp; int counter; pctxt->state = xmlAutomataNewEpsilon(pctxt->am, oldstate, NULL); oldstate = pctxt->state; counter = xmlAutomataNewCounter(pctxt->am, particle->minOccurs - 1, particle->maxOccurs - 1); sub = particle->children->children; while (sub != NULL) { tmp2 = xmlSchemaBuildAContentModel(pctxt, (xmlSchemaParticlePtr) sub); if (tmp2 != 1) ret = 0; sub = sub->next; } tmp = pctxt->state; xmlAutomataNewCountedTrans(pctxt->am, tmp, oldstate, counter); pctxt->state = xmlAutomataNewCounterTrans(pctxt->am, tmp, NULL, counter); if ((particle->minOccurs == 0) || (ret == 1)) { xmlAutomataNewEpsilon(pctxt->am, oldstate, pctxt->state); ret = 1; } } else { sub = particle->children->children; while (sub != NULL) { tmp2 = xmlSchemaBuildAContentModel(pctxt, (xmlSchemaParticlePtr) sub); if (tmp2 != 1) ret = 0; sub = sub->next; } /* * epsilon needed to block previous trans from * being allowed to enter back from another * construct */ pctxt->state = xmlAutomataNewEpsilon(pctxt->am, pctxt->state, NULL); if (particle->minOccurs == 0) { xmlAutomataNewEpsilon(pctxt->am, oldstate, pctxt->state); ret = 1; } } } break; } case XML_SCHEMA_TYPE_CHOICE:{ xmlSchemaTreeItemPtr sub; xmlAutomataStatePtr start, end; ret = 0; start = pctxt->state; end = xmlAutomataNewState(pctxt->am); /* * iterate over the subtypes and remerge the end with an * epsilon transition */ if (particle->maxOccurs == 1) { sub = particle->children->children; while (sub != NULL) { pctxt->state = start; tmp2 = xmlSchemaBuildAContentModel(pctxt, (xmlSchemaParticlePtr) sub); if (tmp2 == 1) ret = 1; xmlAutomataNewEpsilon(pctxt->am, pctxt->state, end); sub = sub->next; } } else { int counter; xmlAutomataStatePtr hop, base; int maxOccurs = particle->maxOccurs == UNBOUNDED ? UNBOUNDED : particle->maxOccurs - 1; int minOccurs = particle->minOccurs < 1 ? 0 : particle->minOccurs - 1; /* * use a counter to keep track of the number of transitions * which went through the choice. */ counter = xmlAutomataNewCounter(pctxt->am, minOccurs, maxOccurs); hop = xmlAutomataNewState(pctxt->am); base = xmlAutomataNewState(pctxt->am); sub = particle->children->children; while (sub != NULL) { pctxt->state = base; tmp2 = xmlSchemaBuildAContentModel(pctxt, (xmlSchemaParticlePtr) sub); if (tmp2 == 1) ret = 1; xmlAutomataNewEpsilon(pctxt->am, pctxt->state, hop); sub = sub->next; } xmlAutomataNewEpsilon(pctxt->am, start, base); xmlAutomataNewCountedTrans(pctxt->am, hop, base, counter); xmlAutomataNewCounterTrans(pctxt->am, hop, end, counter); if (ret == 1) xmlAutomataNewEpsilon(pctxt->am, base, end); } if (particle->minOccurs == 0) { xmlAutomataNewEpsilon(pctxt->am, start, end); ret = 1; } pctxt->state = end; break; } case XML_SCHEMA_TYPE_ALL:{ xmlAutomataStatePtr start, tmp; xmlSchemaParticlePtr sub; xmlSchemaElementPtr elemDecl; ret = 1; sub = (xmlSchemaParticlePtr) particle->children->children; if (sub == NULL) break; ret = 0; start = pctxt->state; tmp = xmlAutomataNewState(pctxt->am); xmlAutomataNewEpsilon(pctxt->am, pctxt->state, tmp); pctxt->state = tmp; while (sub != NULL) { pctxt->state = tmp; elemDecl = (xmlSchemaElementPtr) sub->children; if (elemDecl == NULL) { PERROR_INT("xmlSchemaBuildAContentModel", "<element> particle has no term"); return(ret); }; /* * NOTE: The {max occurs} of all the particles in the * {particles} of the group must be 0 or 1; this is * already ensured during the parse of the content of * <all>. */ if (elemDecl->flags & XML_SCHEMAS_ELEM_SUBST_GROUP_HEAD) { int counter; /* * This is an abstract group, we need to share * the same counter for all the element transitions * derived from the group */ counter = xmlAutomataNewCounter(pctxt->am, sub->minOccurs, sub->maxOccurs); xmlSchemaBuildContentModelForSubstGroup(pctxt, sub, counter, pctxt->state); } else { if ((sub->minOccurs == 1) && (sub->maxOccurs == 1)) { xmlAutomataNewOnceTrans2(pctxt->am, pctxt->state, pctxt->state, elemDecl->name, elemDecl->targetNamespace, 1, 1, elemDecl); } else if ((sub->minOccurs == 0) && (sub->maxOccurs == 1)) { xmlAutomataNewCountTrans2(pctxt->am, pctxt->state, pctxt->state, elemDecl->name, elemDecl->targetNamespace, 0, 1, elemDecl); } } sub = (xmlSchemaParticlePtr) sub->next; } pctxt->state = xmlAutomataNewAllTrans(pctxt->am, pctxt->state, NULL, 0); if (particle->minOccurs == 0) { xmlAutomataNewEpsilon(pctxt->am, start, pctxt->state); ret = 1; } break; } case XML_SCHEMA_TYPE_GROUP: /* * If we hit a model group definition, then this means that * it was empty, thus was not substituted for the containing * model group. Just do nothing in this case. * TODO: But the group should be substituted and not occur at * all in the content model at this point. Fix this. */ ret = 1; break; default: xmlSchemaInternalErr2(ACTXT_CAST pctxt, "xmlSchemaBuildAContentModel", "found unexpected term of type '%s' in content model", WXS_ITEM_TYPE_NAME(particle->children), NULL); return(ret); } return(ret); } /** * xmlSchemaBuildContentModel: * @ctxt: the schema parser context * @type: the complex type definition * @name: the element name * * Builds the content model of the complex type. */ static void xmlSchemaBuildContentModel(xmlSchemaTypePtr type, xmlSchemaParserCtxtPtr ctxt) { if ((type->type != XML_SCHEMA_TYPE_COMPLEX) || (type->contModel != NULL) || ((type->contentType != XML_SCHEMA_CONTENT_ELEMENTS) && (type->contentType != XML_SCHEMA_CONTENT_MIXED))) return; #ifdef DEBUG_CONTENT xmlGenericError(xmlGenericErrorContext, "Building content model for %s\n", name); #endif ctxt->am = NULL; ctxt->am = xmlNewAutomata(); if (ctxt->am == NULL) { xmlGenericError(xmlGenericErrorContext, "Cannot create automata for complex type %s\n", type->name); return; } ctxt->state = xmlAutomataGetInitState(ctxt->am); /* * Build the automaton. */ xmlSchemaBuildAContentModel(ctxt, WXS_TYPE_PARTICLE(type)); xmlAutomataSetFinalState(ctxt->am, ctxt->state); type->contModel = xmlAutomataCompile(ctxt->am); if (type->contModel == NULL) { xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_INTERNAL, WXS_BASIC_CAST type, type->node, "Failed to compile the content model", NULL); } else if (xmlRegexpIsDeterminist(type->contModel) != 1) { xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_NOT_DETERMINISTIC, /* XML_SCHEMAS_ERR_NOTDETERMINIST, */ WXS_BASIC_CAST type, type->node, "The content model is not determinist", NULL); } else { #ifdef DEBUG_CONTENT_REGEXP xmlGenericError(xmlGenericErrorContext, "Content model of %s:\n", type->name); xmlRegexpPrint(stderr, type->contModel); #endif } ctxt->state = NULL; xmlFreeAutomata(ctxt->am); ctxt->am = NULL; } /** * xmlSchemaResolveElementReferences: * @elem: the schema element context * @ctxt: the schema parser context * * Resolves the references of an element declaration * or particle, which has an element declaration as it's * term. */ static void xmlSchemaResolveElementReferences(xmlSchemaElementPtr elemDecl, xmlSchemaParserCtxtPtr ctxt) { if ((ctxt == NULL) || (elemDecl == NULL) || ((elemDecl != NULL) && (elemDecl->flags & XML_SCHEMAS_ELEM_INTERNAL_RESOLVED))) return; elemDecl->flags |= XML_SCHEMAS_ELEM_INTERNAL_RESOLVED; if ((elemDecl->subtypes == NULL) && (elemDecl->namedType != NULL)) { xmlSchemaTypePtr type; /* (type definition) ... otherwise the type definition `resolved` * to by the `actual value` of the type [attribute] ... */ type = xmlSchemaGetType(ctxt->schema, elemDecl->namedType, elemDecl->namedTypeNs); if (type == NULL) { xmlSchemaPResCompAttrErr(ctxt, XML_SCHEMAP_SRC_RESOLVE, WXS_BASIC_CAST elemDecl, elemDecl->node, "type", elemDecl->namedType, elemDecl->namedTypeNs, XML_SCHEMA_TYPE_BASIC, "type definition"); } else elemDecl->subtypes = type; } if (elemDecl->substGroup != NULL) { xmlSchemaElementPtr substHead; /* * FIXME TODO: Do we need a new field in _xmlSchemaElement for * substitutionGroup? */ substHead = xmlSchemaGetElem(ctxt->schema, elemDecl->substGroup, elemDecl->substGroupNs); if (substHead == NULL) { xmlSchemaPResCompAttrErr(ctxt, XML_SCHEMAP_SRC_RESOLVE, WXS_BASIC_CAST elemDecl, NULL, "substitutionGroup", elemDecl->substGroup, elemDecl->substGroupNs, XML_SCHEMA_TYPE_ELEMENT, NULL); } else { xmlSchemaResolveElementReferences(substHead, ctxt); /* * Set the "substitution group affiliation". * NOTE that now we use the "refDecl" field for this. */ WXS_SUBST_HEAD(elemDecl) = substHead; /* * The type definitions is set to: * SPEC "...the {type definition} of the element * declaration `resolved` to by the `actual value` * of the substitutionGroup [attribute], if present" */ if (elemDecl->subtypes == NULL) elemDecl->subtypes = substHead->subtypes; } } /* * SPEC "The definition of anyType serves as the default type definition * for element declarations whose XML representation does not specify one." */ if ((elemDecl->subtypes == NULL) && (elemDecl->namedType == NULL) && (elemDecl->substGroup == NULL)) elemDecl->subtypes = xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYTYPE); } /** * xmlSchemaResolveUnionMemberTypes: * @ctxt: the schema parser context * @type: the schema simple type definition * * Checks and builds the "member type definitions" property of the union * simple type. This handles part (1), part (2) is done in * xmlSchemaFinishMemberTypeDefinitionsProperty() * * Returns -1 in case of an internal error, 0 otherwise. */ static int xmlSchemaResolveUnionMemberTypes(xmlSchemaParserCtxtPtr ctxt, xmlSchemaTypePtr type) { xmlSchemaTypeLinkPtr link, lastLink, newLink; xmlSchemaTypePtr memberType; /* * SPEC (1) "If the <union> alternative is chosen, then [Definition:] * define the explicit members as the type definitions `resolved` * to by the items in the `actual value` of the memberTypes [attribute], * if any, followed by the type definitions corresponding to the * <simpleType>s among the [children] of <union>, if any." */ /* * Resolve references. */ link = type->memberTypes; lastLink = NULL; while (link != NULL) { const xmlChar *name, *nsName; name = ((xmlSchemaQNameRefPtr) link->type)->name; nsName = ((xmlSchemaQNameRefPtr) link->type)->targetNamespace; memberType = xmlSchemaGetType(ctxt->schema, name, nsName); if ((memberType == NULL) || (! WXS_IS_SIMPLE(memberType))) { xmlSchemaPResCompAttrErr(ctxt, XML_SCHEMAP_SRC_RESOLVE, WXS_BASIC_CAST type, type->node, "memberTypes", name, nsName, XML_SCHEMA_TYPE_SIMPLE, NULL); /* * Remove the member type link. */ if (lastLink == NULL) type->memberTypes = link->next; else lastLink->next = link->next; newLink = link; link = link->next; xmlFree(newLink); } else { link->type = memberType; lastLink = link; link = link->next; } } /* * Add local simple types, */ memberType = type->subtypes; while (memberType != NULL) { link = (xmlSchemaTypeLinkPtr) xmlMalloc(sizeof(xmlSchemaTypeLink)); if (link == NULL) { xmlSchemaPErrMemory(ctxt, "allocating a type link", NULL); return (-1); } link->type = memberType; link->next = NULL; if (lastLink == NULL) type->memberTypes = link; else lastLink->next = link; lastLink = link; memberType = memberType->next; } return (0); } /** * xmlSchemaIsDerivedFromBuiltInType: * @ctxt: the schema parser context * @type: the type definition * @valType: the value type * * * Returns 1 if the type has the given value type, or * is derived from such a type. */ static int xmlSchemaIsDerivedFromBuiltInType(xmlSchemaTypePtr type, int valType) { if (type == NULL) return (0); if (WXS_IS_COMPLEX(type)) return (0); if (type->type == XML_SCHEMA_TYPE_BASIC) { if (type->builtInType == valType) return(1); if ((type->builtInType == XML_SCHEMAS_ANYSIMPLETYPE) || (type->builtInType == XML_SCHEMAS_ANYTYPE)) return (0); return(xmlSchemaIsDerivedFromBuiltInType(type->subtypes, valType)); } return(xmlSchemaIsDerivedFromBuiltInType(type->subtypes, valType)); } #if 0 /** * xmlSchemaIsDerivedFromBuiltInType: * @ctxt: the schema parser context * @type: the type definition * @valType: the value type * * * Returns 1 if the type has the given value type, or * is derived from such a type. */ static int xmlSchemaIsUserDerivedFromBuiltInType(xmlSchemaTypePtr type, int valType) { if (type == NULL) return (0); if (WXS_IS_COMPLEX(type)) return (0); if (type->type == XML_SCHEMA_TYPE_BASIC) { if (type->builtInType == valType) return(1); return (0); } else return(xmlSchemaIsDerivedFromBuiltInType(type->subtypes, valType)); return (0); } static xmlSchemaTypePtr xmlSchemaQueryBuiltInType(xmlSchemaTypePtr type) { if (type == NULL) return (NULL); if (WXS_IS_COMPLEX(type)) return (NULL); if (type->type == XML_SCHEMA_TYPE_BASIC) return(type); return(xmlSchemaQueryBuiltInType(type->subtypes)); } #endif /** * xmlSchemaGetPrimitiveType: * @type: the simpleType definition * * Returns the primitive type of the given type or * NULL in case of error. */ static xmlSchemaTypePtr xmlSchemaGetPrimitiveType(xmlSchemaTypePtr type) { while (type != NULL) { /* * Note that anySimpleType is actually not a primitive type * but we need that here. */ if ((type->builtInType == XML_SCHEMAS_ANYSIMPLETYPE) || (type->flags & XML_SCHEMAS_TYPE_BUILTIN_PRIMITIVE)) return (type); type = type->baseType; } return (NULL); } #if 0 /** * xmlSchemaGetBuiltInTypeAncestor: * @type: the simpleType definition * * Returns the primitive type of the given type or * NULL in case of error. */ static xmlSchemaTypePtr xmlSchemaGetBuiltInTypeAncestor(xmlSchemaTypePtr type) { if (WXS_IS_LIST(type) || WXS_IS_UNION(type)) return (0); while (type != NULL) { if (type->type == XML_SCHEMA_TYPE_BASIC) return (type); type = type->baseType; } return (NULL); } #endif /** * xmlSchemaCloneWildcardNsConstraints: * @ctxt: the schema parser context * @dest: the destination wildcard * @source: the source wildcard * * Clones the namespace constraints of source * and assigns them to dest. * Returns -1 on internal error, 0 otherwise. */ static int xmlSchemaCloneWildcardNsConstraints(xmlSchemaParserCtxtPtr ctxt, xmlSchemaWildcardPtr dest, xmlSchemaWildcardPtr source) { xmlSchemaWildcardNsPtr cur, tmp, last; if ((source == NULL) || (dest == NULL)) return(-1); dest->any = source->any; cur = source->nsSet; last = NULL; while (cur != NULL) { tmp = xmlSchemaNewWildcardNsConstraint(ctxt); if (tmp == NULL) return(-1); tmp->value = cur->value; if (last == NULL) dest->nsSet = tmp; else last->next = tmp; last = tmp; cur = cur->next; } if (dest->negNsSet != NULL) xmlSchemaFreeWildcardNsSet(dest->negNsSet); if (source->negNsSet != NULL) { dest->negNsSet = xmlSchemaNewWildcardNsConstraint(ctxt); if (dest->negNsSet == NULL) return(-1); dest->negNsSet->value = source->negNsSet->value; } else dest->negNsSet = NULL; return(0); } /** * xmlSchemaUnionWildcards: * @ctxt: the schema parser context * @completeWild: the first wildcard * @curWild: the second wildcard * * Unions the namespace constraints of the given wildcards. * @completeWild will hold the resulting union. * Returns a positive error code on failure, -1 in case of an * internal error, 0 otherwise. */ static int xmlSchemaUnionWildcards(xmlSchemaParserCtxtPtr ctxt, xmlSchemaWildcardPtr completeWild, xmlSchemaWildcardPtr curWild) { xmlSchemaWildcardNsPtr cur, curB, tmp; /* * 1 If O1 and O2 are the same value, then that value must be the * value. */ if ((completeWild->any == curWild->any) && ((completeWild->nsSet == NULL) == (curWild->nsSet == NULL)) && ((completeWild->negNsSet == NULL) == (curWild->negNsSet == NULL))) { if ((completeWild->negNsSet == NULL) || (completeWild->negNsSet->value == curWild->negNsSet->value)) { if (completeWild->nsSet != NULL) { int found = 0; /* * Check equality of sets. */ cur = completeWild->nsSet; while (cur != NULL) { found = 0; curB = curWild->nsSet; while (curB != NULL) { if (cur->value == curB->value) { found = 1; break; } curB = curB->next; } if (!found) break; cur = cur->next; } if (found) return(0); } else return(0); } } /* * 2 If either O1 or O2 is any, then any must be the value */ if (completeWild->any != curWild->any) { if (completeWild->any == 0) { completeWild->any = 1; if (completeWild->nsSet != NULL) { xmlSchemaFreeWildcardNsSet(completeWild->nsSet); completeWild->nsSet = NULL; } if (completeWild->negNsSet != NULL) { xmlFree(completeWild->negNsSet); completeWild->negNsSet = NULL; } } return (0); } /* * 3 If both O1 and O2 are sets of (namespace names or `absent`), * then the union of those sets must be the value. */ if ((completeWild->nsSet != NULL) && (curWild->nsSet != NULL)) { int found; xmlSchemaWildcardNsPtr start; cur = curWild->nsSet; start = completeWild->nsSet; while (cur != NULL) { found = 0; curB = start; while (curB != NULL) { if (cur->value == curB->value) { found = 1; break; } curB = curB->next; } if (!found) { tmp = xmlSchemaNewWildcardNsConstraint(ctxt); if (tmp == NULL) return (-1); tmp->value = cur->value; tmp->next = completeWild->nsSet; completeWild->nsSet = tmp; } cur = cur->next; } return(0); } /* * 4 If the two are negations of different values (namespace names * or `absent`), then a pair of not and `absent` must be the value. */ if ((completeWild->negNsSet != NULL) && (curWild->negNsSet != NULL) && (completeWild->negNsSet->value != curWild->negNsSet->value)) { completeWild->negNsSet->value = NULL; return(0); } /* * 5. */ if (((completeWild->negNsSet != NULL) && (completeWild->negNsSet->value != NULL) && (curWild->nsSet != NULL)) || ((curWild->negNsSet != NULL) && (curWild->negNsSet->value != NULL) && (completeWild->nsSet != NULL))) { int nsFound, absentFound = 0; if (completeWild->nsSet != NULL) { cur = completeWild->nsSet; curB = curWild->negNsSet; } else { cur = curWild->nsSet; curB = completeWild->negNsSet; } nsFound = 0; while (cur != NULL) { if (cur->value == NULL) absentFound = 1; else if (cur->value == curB->value) nsFound = 1; if (nsFound && absentFound) break; cur = cur->next; } if (nsFound && absentFound) { /* * 5.1 If the set S includes both the negated namespace * name and `absent`, then any must be the value. */ completeWild->any = 1; if (completeWild->nsSet != NULL) { xmlSchemaFreeWildcardNsSet(completeWild->nsSet); completeWild->nsSet = NULL; } if (completeWild->negNsSet != NULL) { xmlFree(completeWild->negNsSet); completeWild->negNsSet = NULL; } } else if (nsFound && (!absentFound)) { /* * 5.2 If the set S includes the negated namespace name * but not `absent`, then a pair of not and `absent` must * be the value. */ if (completeWild->nsSet != NULL) { xmlSchemaFreeWildcardNsSet(completeWild->nsSet); completeWild->nsSet = NULL; } if (completeWild->negNsSet == NULL) { completeWild->negNsSet = xmlSchemaNewWildcardNsConstraint(ctxt); if (completeWild->negNsSet == NULL) return (-1); } completeWild->negNsSet->value = NULL; } else if ((!nsFound) && absentFound) { /* * 5.3 If the set S includes `absent` but not the negated * namespace name, then the union is not expressible. */ xmlSchemaPErr(ctxt, completeWild->node, XML_SCHEMAP_UNION_NOT_EXPRESSIBLE, "The union of the wildcard is not expressible.\n", NULL, NULL); return(XML_SCHEMAP_UNION_NOT_EXPRESSIBLE); } else if ((!nsFound) && (!absentFound)) { /* * 5.4 If the set S does not include either the negated namespace * name or `absent`, then whichever of O1 or O2 is a pair of not * and a namespace name must be the value. */ if (completeWild->negNsSet == NULL) { if (completeWild->nsSet != NULL) { xmlSchemaFreeWildcardNsSet(completeWild->nsSet); completeWild->nsSet = NULL; } completeWild->negNsSet = xmlSchemaNewWildcardNsConstraint(ctxt); if (completeWild->negNsSet == NULL) return (-1); completeWild->negNsSet->value = curWild->negNsSet->value; } } return (0); } /* * 6. */ if (((completeWild->negNsSet != NULL) && (completeWild->negNsSet->value == NULL) && (curWild->nsSet != NULL)) || ((curWild->negNsSet != NULL) && (curWild->negNsSet->value == NULL) && (completeWild->nsSet != NULL))) { if (completeWild->nsSet != NULL) { cur = completeWild->nsSet; } else { cur = curWild->nsSet; } while (cur != NULL) { if (cur->value == NULL) { /* * 6.1 If the set S includes `absent`, then any must be the * value. */ completeWild->any = 1; if (completeWild->nsSet != NULL) { xmlSchemaFreeWildcardNsSet(completeWild->nsSet); completeWild->nsSet = NULL; } if (completeWild->negNsSet != NULL) { xmlFree(completeWild->negNsSet); completeWild->negNsSet = NULL; } return (0); } cur = cur->next; } if (completeWild->negNsSet == NULL) { /* * 6.2 If the set S does not include `absent`, then a pair of not * and `absent` must be the value. */ if (completeWild->nsSet != NULL) { xmlSchemaFreeWildcardNsSet(completeWild->nsSet); completeWild->nsSet = NULL; } completeWild->negNsSet = xmlSchemaNewWildcardNsConstraint(ctxt); if (completeWild->negNsSet == NULL) return (-1); completeWild->negNsSet->value = NULL; } return (0); } return (0); } /** * xmlSchemaIntersectWildcards: * @ctxt: the schema parser context * @completeWild: the first wildcard * @curWild: the second wildcard * * Intersects the namespace constraints of the given wildcards. * @completeWild will hold the resulting intersection. * Returns a positive error code on failure, -1 in case of an * internal error, 0 otherwise. */ static int xmlSchemaIntersectWildcards(xmlSchemaParserCtxtPtr ctxt, xmlSchemaWildcardPtr completeWild, xmlSchemaWildcardPtr curWild) { xmlSchemaWildcardNsPtr cur, curB, prev, tmp; /* * 1 If O1 and O2 are the same value, then that value must be the * value. */ if ((completeWild->any == curWild->any) && ((completeWild->nsSet == NULL) == (curWild->nsSet == NULL)) && ((completeWild->negNsSet == NULL) == (curWild->negNsSet == NULL))) { if ((completeWild->negNsSet == NULL) || (completeWild->negNsSet->value == curWild->negNsSet->value)) { if (completeWild->nsSet != NULL) { int found = 0; /* * Check equality of sets. */ cur = completeWild->nsSet; while (cur != NULL) { found = 0; curB = curWild->nsSet; while (curB != NULL) { if (cur->value == curB->value) { found = 1; break; } curB = curB->next; } if (!found) break; cur = cur->next; } if (found) return(0); } else return(0); } } /* * 2 If either O1 or O2 is any, then the other must be the value. */ if ((completeWild->any != curWild->any) && (completeWild->any)) { if (xmlSchemaCloneWildcardNsConstraints(ctxt, completeWild, curWild) == -1) return(-1); return(0); } /* * 3 If either O1 or O2 is a pair of not and a value (a namespace * name or `absent`) and the other is a set of (namespace names or * `absent`), then that set, minus the negated value if it was in * the set, minus `absent` if it was in the set, must be the value. */ if (((completeWild->negNsSet != NULL) && (curWild->nsSet != NULL)) || ((curWild->negNsSet != NULL) && (completeWild->nsSet != NULL))) { const xmlChar *neg; if (completeWild->nsSet == NULL) { neg = completeWild->negNsSet->value; if (xmlSchemaCloneWildcardNsConstraints(ctxt, completeWild, curWild) == -1) return(-1); } else neg = curWild->negNsSet->value; /* * Remove absent and negated. */ prev = NULL; cur = completeWild->nsSet; while (cur != NULL) { if (cur->value == NULL) { if (prev == NULL) completeWild->nsSet = cur->next; else prev->next = cur->next; xmlFree(cur); break; } prev = cur; cur = cur->next; } if (neg != NULL) { prev = NULL; cur = completeWild->nsSet; while (cur != NULL) { if (cur->value == neg) { if (prev == NULL) completeWild->nsSet = cur->next; else prev->next = cur->next; xmlFree(cur); break; } prev = cur; cur = cur->next; } } return(0); } /* * 4 If both O1 and O2 are sets of (namespace names or `absent`), * then the intersection of those sets must be the value. */ if ((completeWild->nsSet != NULL) && (curWild->nsSet != NULL)) { int found; cur = completeWild->nsSet; prev = NULL; while (cur != NULL) { found = 0; curB = curWild->nsSet; while (curB != NULL) { if (cur->value == curB->value) { found = 1; break; } curB = curB->next; } if (!found) { if (prev == NULL) completeWild->nsSet = cur->next; else prev->next = cur->next; tmp = cur->next; xmlFree(cur); cur = tmp; continue; } prev = cur; cur = cur->next; } return(0); } /* 5 If the two are negations of different namespace names, * then the intersection is not expressible */ if ((completeWild->negNsSet != NULL) && (curWild->negNsSet != NULL) && (completeWild->negNsSet->value != curWild->negNsSet->value) && (completeWild->negNsSet->value != NULL) && (curWild->negNsSet->value != NULL)) { xmlSchemaPErr(ctxt, completeWild->node, XML_SCHEMAP_INTERSECTION_NOT_EXPRESSIBLE, "The intersection of the wildcard is not expressible.\n", NULL, NULL); return(XML_SCHEMAP_INTERSECTION_NOT_EXPRESSIBLE); } /* * 6 If the one is a negation of a namespace name and the other * is a negation of `absent`, then the one which is the negation * of a namespace name must be the value. */ if ((completeWild->negNsSet != NULL) && (curWild->negNsSet != NULL) && (completeWild->negNsSet->value != curWild->negNsSet->value) && (completeWild->negNsSet->value == NULL)) { completeWild->negNsSet->value = curWild->negNsSet->value; } return(0); } /** * xmlSchemaIsWildcardNsConstraintSubset: * @ctxt: the schema parser context * @sub: the first wildcard * @super: the second wildcard * * Schema Component Constraint: Wildcard Subset (cos-ns-subset) * * Returns 0 if the namespace constraint of @sub is an intensional * subset of @super, 1 otherwise. */ static int xmlSchemaCheckCOSNSSubset(xmlSchemaWildcardPtr sub, xmlSchemaWildcardPtr super) { /* * 1 super must be any. */ if (super->any) return (0); /* * 2.1 sub must be a pair of not and a namespace name or `absent`. * 2.2 super must be a pair of not and the same value. */ if ((sub->negNsSet != NULL) && (super->negNsSet != NULL) && (sub->negNsSet->value == super->negNsSet->value)) return (0); /* * 3.1 sub must be a set whose members are either namespace names or `absent`. */ if (sub->nsSet != NULL) { /* * 3.2.1 super must be the same set or a superset thereof. */ if (super->nsSet != NULL) { xmlSchemaWildcardNsPtr cur, curB; int found = 0; cur = sub->nsSet; while (cur != NULL) { found = 0; curB = super->nsSet; while (curB != NULL) { if (cur->value == curB->value) { found = 1; break; } curB = curB->next; } if (!found) return (1); cur = cur->next; } if (found) return (0); } else if (super->negNsSet != NULL) { xmlSchemaWildcardNsPtr cur; /* * 3.2.2 super must be a pair of not and a namespace name or * `absent` and that value must not be in sub's set. */ cur = sub->nsSet; while (cur != NULL) { if (cur->value == super->negNsSet->value) return (1); cur = cur->next; } return (0); } } return (1); } static int xmlSchemaGetEffectiveValueConstraint(xmlSchemaAttributeUsePtr attruse, int *fixed, const xmlChar **value, xmlSchemaValPtr *val) { *fixed = 0; *value = NULL; if (val != 0) *val = NULL; if (attruse->defValue != NULL) { *value = attruse->defValue; if (val != NULL) *val = attruse->defVal; if (attruse->flags & XML_SCHEMA_ATTR_USE_FIXED) *fixed = 1; return(1); } else if ((attruse->attrDecl != NULL) && (attruse->attrDecl->defValue != NULL)) { *value = attruse->attrDecl->defValue; if (val != NULL) *val = attruse->attrDecl->defVal; if (attruse->attrDecl->flags & XML_SCHEMAS_ATTR_FIXED) *fixed = 1; return(1); } return(0); } /** * xmlSchemaCheckCVCWildcardNamespace: * @wild: the wildcard * @ns: the namespace * * Validation Rule: Wildcard allows Namespace Name * (cvc-wildcard-namespace) * * Returns 0 if the given namespace matches the wildcard, * 1 otherwise and -1 on API errors. */ static int xmlSchemaCheckCVCWildcardNamespace(xmlSchemaWildcardPtr wild, const xmlChar* ns) { if (wild == NULL) return(-1); if (wild->any) return(0); else if (wild->nsSet != NULL) { xmlSchemaWildcardNsPtr cur; cur = wild->nsSet; while (cur != NULL) { if (xmlStrEqual(cur->value, ns)) return(0); cur = cur->next; } } else if ((wild->negNsSet != NULL) && (ns != NULL) && (!xmlStrEqual(wild->negNsSet->value, ns))) return(0); return(1); } #define XML_SCHEMA_ACTION_DERIVE 0 #define XML_SCHEMA_ACTION_REDEFINE 1 #define WXS_ACTION_STR(a) \ ((a) == XML_SCHEMA_ACTION_DERIVE) ? (const xmlChar *) "base" : (const xmlChar *) "redefined" /* * Schema Component Constraint: * Derivation Valid (Restriction, Complex) * derivation-ok-restriction (2) - (4) * * ATTENTION: * In XML Schema 1.1 this will be: * Validation Rule: * Checking complex type subsumption (practicalSubsumption) (1, 2 and 3) * */ static int xmlSchemaCheckDerivationOKRestriction2to4(xmlSchemaParserCtxtPtr pctxt, int action, xmlSchemaBasicItemPtr item, xmlSchemaBasicItemPtr baseItem, xmlSchemaItemListPtr uses, xmlSchemaItemListPtr baseUses, xmlSchemaWildcardPtr wild, xmlSchemaWildcardPtr baseWild) { xmlSchemaAttributeUsePtr cur = NULL, bcur; int i, j, found; /* err = 0; */ const xmlChar *bEffValue; int effFixed; if (uses != NULL) { for (i = 0; i < uses->nbItems; i++) { cur = uses->items[i]; found = 0; if (baseUses == NULL) goto not_found; for (j = 0; j < baseUses->nbItems; j++) { bcur = baseUses->items[j]; if ((WXS_ATTRUSE_DECL_NAME(cur) == WXS_ATTRUSE_DECL_NAME(bcur)) && (WXS_ATTRUSE_DECL_TNS(cur) == WXS_ATTRUSE_DECL_TNS(bcur))) { /* * (2.1) "If there is an attribute use in the {attribute * uses} of the {base type definition} (call this B) whose * {attribute declaration} has the same {name} and {target * namespace}, then all of the following must be true:" */ found = 1; if ((cur->occurs == XML_SCHEMAS_ATTR_USE_OPTIONAL) && (bcur->occurs == XML_SCHEMAS_ATTR_USE_REQUIRED)) { xmlChar *str = NULL; /* * (2.1.1) "one of the following must be true:" * (2.1.1.1) "B's {required} is false." * (2.1.1.2) "R's {required} is true." */ xmlSchemaPAttrUseErr4(pctxt, XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_1, WXS_ITEM_NODE(item), item, cur, "The 'optional' attribute use is inconsistent " "with the corresponding 'required' attribute use of " "the %s %s", WXS_ACTION_STR(action), xmlSchemaGetComponentDesignation(&str, baseItem), NULL, NULL); FREE_AND_NULL(str); /* err = pctxt->err; */ } else if (xmlSchemaCheckCOSSTDerivedOK(ACTXT_CAST pctxt, WXS_ATTRUSE_TYPEDEF(cur), WXS_ATTRUSE_TYPEDEF(bcur), 0) != 0) { xmlChar *strA = NULL, *strB = NULL, *strC = NULL; /* * SPEC (2.1.2) "R's {attribute declaration}'s * {type definition} must be validly derived from * B's {type definition} given the empty set as * defined in Type Derivation OK (Simple) ($3.14.6)." */ xmlSchemaPAttrUseErr4(pctxt, XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_2, WXS_ITEM_NODE(item), item, cur, "The attribute declaration's %s " "is not validly derived from " "the corresponding %s of the " "attribute declaration in the %s %s", xmlSchemaGetComponentDesignation(&strA, WXS_ATTRUSE_TYPEDEF(cur)), xmlSchemaGetComponentDesignation(&strB, WXS_ATTRUSE_TYPEDEF(bcur)), WXS_ACTION_STR(action), xmlSchemaGetComponentDesignation(&strC, baseItem)); /* xmlSchemaGetComponentDesignation(&str, baseItem), */ FREE_AND_NULL(strA); FREE_AND_NULL(strB); FREE_AND_NULL(strC); /* err = pctxt->err; */ } else { /* * 2.1.3 [Definition:] Let the effective value * constraint of an attribute use be its {value * constraint}, if present, otherwise its {attribute * declaration}'s {value constraint} . */ xmlSchemaGetEffectiveValueConstraint(bcur, &effFixed, &bEffValue, NULL); /* * 2.1.3 ... one of the following must be true * * 2.1.3.1 B's `effective value constraint` is * `absent` or default. */ if ((bEffValue != NULL) && (effFixed == 1)) { const xmlChar *rEffValue = NULL; xmlSchemaGetEffectiveValueConstraint(bcur, &effFixed, &rEffValue, NULL); /* * 2.1.3.2 R's `effective value constraint` is * fixed with the same string as B's. * MAYBE TODO: Compare the computed values. * Hmm, it says "same string" so * string-equality might really be sufficient. */ if ((effFixed == 0) || (! WXS_ARE_DEFAULT_STR_EQUAL(rEffValue, bEffValue))) { xmlChar *str = NULL; xmlSchemaPAttrUseErr4(pctxt, XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_3, WXS_ITEM_NODE(item), item, cur, "The effective value constraint of the " "attribute use is inconsistent with " "its correspondent in the %s %s", WXS_ACTION_STR(action), xmlSchemaGetComponentDesignation(&str, baseItem), NULL, NULL); FREE_AND_NULL(str); /* err = pctxt->err; */ } } } break; } } not_found: if (!found) { /* * (2.2) "otherwise the {base type definition} must have an * {attribute wildcard} and the {target namespace} of the * R's {attribute declaration} must be `valid` with respect * to that wildcard, as defined in Wildcard allows Namespace * Name ($3.10.4)." */ if ((baseWild == NULL) || (xmlSchemaCheckCVCWildcardNamespace(baseWild, (WXS_ATTRUSE_DECL(cur))->targetNamespace) != 0)) { xmlChar *str = NULL; xmlSchemaPAttrUseErr4(pctxt, XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_2, WXS_ITEM_NODE(item), item, cur, "Neither a matching attribute use, " "nor a matching wildcard exists in the %s %s", WXS_ACTION_STR(action), xmlSchemaGetComponentDesignation(&str, baseItem), NULL, NULL); FREE_AND_NULL(str); /* err = pctxt->err; */ } } } } /* * SPEC derivation-ok-restriction (3): * (3) "For each attribute use in the {attribute uses} of the {base type * definition} whose {required} is true, there must be an attribute * use with an {attribute declaration} with the same {name} and * {target namespace} as its {attribute declaration} in the {attribute * uses} of the complex type definition itself whose {required} is true. */ if (baseUses != NULL) { for (j = 0; j < baseUses->nbItems; j++) { bcur = baseUses->items[j]; if (bcur->occurs != XML_SCHEMAS_ATTR_USE_REQUIRED) continue; found = 0; if (uses != NULL) { for (i = 0; i < uses->nbItems; i++) { cur = uses->items[i]; if ((WXS_ATTRUSE_DECL_NAME(cur) == WXS_ATTRUSE_DECL_NAME(bcur)) && (WXS_ATTRUSE_DECL_TNS(cur) == WXS_ATTRUSE_DECL_TNS(bcur))) { found = 1; break; } } } if (!found) { xmlChar *strA = NULL, *strB = NULL; xmlSchemaCustomErr4(ACTXT_CAST pctxt, XML_SCHEMAP_DERIVATION_OK_RESTRICTION_3, NULL, item, "A matching attribute use for the " "'required' %s of the %s %s is missing", xmlSchemaGetComponentDesignation(&strA, bcur), WXS_ACTION_STR(action), xmlSchemaGetComponentDesignation(&strB, baseItem), NULL); FREE_AND_NULL(strA); FREE_AND_NULL(strB); } } } /* * derivation-ok-restriction (4) */ if (wild != NULL) { /* * (4) "If there is an {attribute wildcard}, all of the * following must be true:" */ if (baseWild == NULL) { xmlChar *str = NULL; /* * (4.1) "The {base type definition} must also have one." */ xmlSchemaCustomErr4(ACTXT_CAST pctxt, XML_SCHEMAP_DERIVATION_OK_RESTRICTION_4_1, NULL, item, "The %s has an attribute wildcard, " "but the %s %s '%s' does not have one", WXS_ITEM_TYPE_NAME(item), WXS_ACTION_STR(action), WXS_ITEM_TYPE_NAME(baseItem), xmlSchemaGetComponentQName(&str, baseItem)); FREE_AND_NULL(str); return(pctxt->err); } else if ((baseWild->any == 0) && xmlSchemaCheckCOSNSSubset(wild, baseWild)) { xmlChar *str = NULL; /* * (4.2) "The complex type definition's {attribute wildcard}'s * {namespace constraint} must be a subset of the {base type * definition}'s {attribute wildcard}'s {namespace constraint}, * as defined by Wildcard Subset ($3.10.6)." */ xmlSchemaCustomErr4(ACTXT_CAST pctxt, XML_SCHEMAP_DERIVATION_OK_RESTRICTION_4_2, NULL, item, "The attribute wildcard is not a valid " "subset of the wildcard in the %s %s '%s'", WXS_ACTION_STR(action), WXS_ITEM_TYPE_NAME(baseItem), xmlSchemaGetComponentQName(&str, baseItem), NULL); FREE_AND_NULL(str); return(pctxt->err); } /* 4.3 Unless the {base type definition} is the `ur-type * definition`, the complex type definition's {attribute * wildcard}'s {process contents} must be identical to or * stronger than the {base type definition}'s {attribute * wildcard}'s {process contents}, where strict is stronger * than lax is stronger than skip. */ if ((! WXS_IS_ANYTYPE(baseItem)) && (wild->processContents < baseWild->processContents)) { xmlChar *str = NULL; xmlSchemaCustomErr4(ACTXT_CAST pctxt, XML_SCHEMAP_DERIVATION_OK_RESTRICTION_4_3, NULL, baseItem, "The {process contents} of the attribute wildcard is " "weaker than the one in the %s %s '%s'", WXS_ACTION_STR(action), WXS_ITEM_TYPE_NAME(baseItem), xmlSchemaGetComponentQName(&str, baseItem), NULL); FREE_AND_NULL(str) return(pctxt->err); } } return(0); } static int xmlSchemaExpandAttributeGroupRefs(xmlSchemaParserCtxtPtr pctxt, xmlSchemaBasicItemPtr item, xmlSchemaWildcardPtr *completeWild, xmlSchemaItemListPtr list, xmlSchemaItemListPtr prohibs); /** * xmlSchemaFixupTypeAttributeUses: * @ctxt: the schema parser context * @type: the complex type definition * * * Builds the wildcard and the attribute uses on the given complex type. * Returns -1 if an internal error occurs, 0 otherwise. * * ATTENTION TODO: Experimentally this uses pointer comparisons for * strings, so recheck this if we start to hardcode some schemata, since * they might not be in the same dict. * NOTE: It is allowed to "extend" the xs:anyType type. */ static int xmlSchemaFixupTypeAttributeUses(xmlSchemaParserCtxtPtr pctxt, xmlSchemaTypePtr type) { xmlSchemaTypePtr baseType = NULL; xmlSchemaAttributeUsePtr use; xmlSchemaItemListPtr uses, baseUses, prohibs = NULL; if (type->baseType == NULL) { PERROR_INT("xmlSchemaFixupTypeAttributeUses", "no base type"); return (-1); } baseType = type->baseType; if (WXS_IS_TYPE_NOT_FIXED(baseType)) if (xmlSchemaTypeFixup(baseType, ACTXT_CAST pctxt) == -1) return(-1); uses = type->attrUses; baseUses = baseType->attrUses; /* * Expand attribute group references. And build the 'complete' * wildcard, i.e. intersect multiple wildcards. * Move attribute prohibitions into a separate list. */ if (uses != NULL) { if (WXS_IS_RESTRICTION(type)) { /* * This one will transfer all attr. prohibitions * into pctxt->attrProhibs. */ if (xmlSchemaExpandAttributeGroupRefs(pctxt, WXS_BASIC_CAST type, &(type->attributeWildcard), uses, pctxt->attrProhibs) == -1) { PERROR_INT("xmlSchemaFixupTypeAttributeUses", "failed to expand attributes"); } if (pctxt->attrProhibs->nbItems != 0) prohibs = pctxt->attrProhibs; } else { if (xmlSchemaExpandAttributeGroupRefs(pctxt, WXS_BASIC_CAST type, &(type->attributeWildcard), uses, NULL) == -1) { PERROR_INT("xmlSchemaFixupTypeAttributeUses", "failed to expand attributes"); } } } /* * Inherit the attribute uses of the base type. */ if (baseUses != NULL) { int i, j; xmlSchemaAttributeUseProhibPtr pro; if (WXS_IS_RESTRICTION(type)) { int usesCount; xmlSchemaAttributeUsePtr tmp; if (uses != NULL) usesCount = uses->nbItems; else usesCount = 0; /* Restriction. */ for (i = 0; i < baseUses->nbItems; i++) { use = baseUses->items[i]; if (prohibs) { /* * Filter out prohibited uses. */ for (j = 0; j < prohibs->nbItems; j++) { pro = prohibs->items[j]; if ((WXS_ATTRUSE_DECL_NAME(use) == pro->name) && (WXS_ATTRUSE_DECL_TNS(use) == pro->targetNamespace)) { goto inherit_next; } } } if (usesCount) { /* * Filter out existing uses. */ for (j = 0; j < usesCount; j++) { tmp = uses->items[j]; if ((WXS_ATTRUSE_DECL_NAME(use) == WXS_ATTRUSE_DECL_NAME(tmp)) && (WXS_ATTRUSE_DECL_TNS(use) == WXS_ATTRUSE_DECL_TNS(tmp))) { goto inherit_next; } } } if (uses == NULL) { type->attrUses = xmlSchemaItemListCreate(); if (type->attrUses == NULL) goto exit_failure; uses = type->attrUses; } xmlSchemaItemListAddSize(uses, 2, use); inherit_next: {} } } else { /* Extension. */ for (i = 0; i < baseUses->nbItems; i++) { use = baseUses->items[i]; if (uses == NULL) { type->attrUses = xmlSchemaItemListCreate(); if (type->attrUses == NULL) goto exit_failure; uses = type->attrUses; } xmlSchemaItemListAddSize(uses, baseUses->nbItems, use); } } } /* * Shrink attr. uses. */ if (uses) { if (uses->nbItems == 0) { xmlSchemaItemListFree(uses); type->attrUses = NULL; } /* * TODO: We could shrink the size of the array * to fit the actual number of items. */ } /* * Compute the complete wildcard. */ if (WXS_IS_EXTENSION(type)) { if (baseType->attributeWildcard != NULL) { /* * (3.2.2.1) "If the `base wildcard` is non-`absent`, then * the appropriate case among the following:" */ if (type->attributeWildcard != NULL) { /* * Union the complete wildcard with the base wildcard. * SPEC {attribute wildcard} * (3.2.2.1.2) "otherwise a wildcard whose {process contents} * and {annotation} are those of the `complete wildcard`, * and whose {namespace constraint} is the intensional union * of the {namespace constraint} of the `complete wildcard` * and of the `base wildcard`, as defined in Attribute * Wildcard Union ($3.10.6)." */ if (xmlSchemaUnionWildcards(pctxt, type->attributeWildcard, baseType->attributeWildcard) == -1) goto exit_failure; } else { /* * (3.2.2.1.1) "If the `complete wildcard` is `absent`, * then the `base wildcard`." */ type->attributeWildcard = baseType->attributeWildcard; } } else { /* * (3.2.2.2) "otherwise (the `base wildcard` is `absent`) the * `complete wildcard`" * NOOP */ } } else { /* * SPEC {attribute wildcard} * (3.1) "If the <restriction> alternative is chosen, then the * `complete wildcard`;" * NOOP */ } return (0); exit_failure: return(-1); } /** * xmlSchemaTypeFinalContains: * @schema: the schema * @type: the type definition * @final: the final * * Evaluates if a type definition contains the given "final". * This does take "finalDefault" into account as well. * * Returns 1 if the type does contain the given "final", * 0 otherwise. */ static int xmlSchemaTypeFinalContains(xmlSchemaTypePtr type, int final) { if (type == NULL) return (0); if (type->flags & final) return (1); else return (0); } /** * xmlSchemaGetUnionSimpleTypeMemberTypes: * @type: the Union Simple Type * * Returns a list of member types of @type if existing, * returns NULL otherwise. */ static xmlSchemaTypeLinkPtr xmlSchemaGetUnionSimpleTypeMemberTypes(xmlSchemaTypePtr type) { while ((type != NULL) && (type->type == XML_SCHEMA_TYPE_SIMPLE)) { if (type->memberTypes != NULL) return (type->memberTypes); else type = type->baseType; } return (NULL); } #if 0 /** * xmlSchemaGetParticleTotalRangeMin: * @particle: the particle * * Schema Component Constraint: Effective Total Range * (all and sequence) + (choice) * * Returns the minimum Effective Total Range. */ static int xmlSchemaGetParticleTotalRangeMin(xmlSchemaParticlePtr particle) { if ((particle->children == NULL) || (particle->minOccurs == 0)) return (0); if (particle->children->type == XML_SCHEMA_TYPE_CHOICE) { int min = -1, cur; xmlSchemaParticlePtr part = (xmlSchemaParticlePtr) particle->children->children; if (part == NULL) return (0); while (part != NULL) { if ((part->children->type == XML_SCHEMA_TYPE_ELEMENT) || (part->children->type == XML_SCHEMA_TYPE_ANY)) cur = part->minOccurs; else cur = xmlSchemaGetParticleTotalRangeMin(part); if (cur == 0) return (0); if ((min > cur) || (min == -1)) min = cur; part = (xmlSchemaParticlePtr) part->next; } return (particle->minOccurs * min); } else { /* <all> and <sequence> */ int sum = 0; xmlSchemaParticlePtr part = (xmlSchemaParticlePtr) particle->children->children; if (part == NULL) return (0); do { if ((part->children->type == XML_SCHEMA_TYPE_ELEMENT) || (part->children->type == XML_SCHEMA_TYPE_ANY)) sum += part->minOccurs; else sum += xmlSchemaGetParticleTotalRangeMin(part); part = (xmlSchemaParticlePtr) part->next; } while (part != NULL); return (particle->minOccurs * sum); } } /** * xmlSchemaGetParticleTotalRangeMax: * @particle: the particle * * Schema Component Constraint: Effective Total Range * (all and sequence) + (choice) * * Returns the maximum Effective Total Range. */ static int xmlSchemaGetParticleTotalRangeMax(xmlSchemaParticlePtr particle) { if ((particle->children == NULL) || (particle->children->children == NULL)) return (0); if (particle->children->type == XML_SCHEMA_TYPE_CHOICE) { int max = -1, cur; xmlSchemaParticlePtr part = (xmlSchemaParticlePtr) particle->children->children; for (; part != NULL; part = (xmlSchemaParticlePtr) part->next) { if (part->children == NULL) continue; if ((part->children->type == XML_SCHEMA_TYPE_ELEMENT) || (part->children->type == XML_SCHEMA_TYPE_ANY)) cur = part->maxOccurs; else cur = xmlSchemaGetParticleTotalRangeMax(part); if (cur == UNBOUNDED) return (UNBOUNDED); if ((max < cur) || (max == -1)) max = cur; } /* TODO: Handle overflows? */ return (particle->maxOccurs * max); } else { /* <all> and <sequence> */ int sum = 0, cur; xmlSchemaParticlePtr part = (xmlSchemaParticlePtr) particle->children->children; for (; part != NULL; part = (xmlSchemaParticlePtr) part->next) { if (part->children == NULL) continue; if ((part->children->type == XML_SCHEMA_TYPE_ELEMENT) || (part->children->type == XML_SCHEMA_TYPE_ANY)) cur = part->maxOccurs; else cur = xmlSchemaGetParticleTotalRangeMax(part); if (cur == UNBOUNDED) return (UNBOUNDED); if ((cur > 0) && (particle->maxOccurs == UNBOUNDED)) return (UNBOUNDED); sum += cur; } /* TODO: Handle overflows? */ return (particle->maxOccurs * sum); } } #endif /** * xmlSchemaGetParticleEmptiable: * @particle: the particle * * Returns 1 if emptiable, 0 otherwise. */ static int xmlSchemaGetParticleEmptiable(xmlSchemaParticlePtr particle) { xmlSchemaParticlePtr part; int emptiable; if ((particle->children == NULL) || (particle->minOccurs == 0)) return (1); part = (xmlSchemaParticlePtr) particle->children->children; if (part == NULL) return (1); while (part != NULL) { if ((part->children->type == XML_SCHEMA_TYPE_ELEMENT) || (part->children->type == XML_SCHEMA_TYPE_ANY)) emptiable = (part->minOccurs == 0); else emptiable = xmlSchemaGetParticleEmptiable(part); if (particle->children->type == XML_SCHEMA_TYPE_CHOICE) { if (emptiable) return (1); } else { /* <all> and <sequence> */ if (!emptiable) return (0); } part = (xmlSchemaParticlePtr) part->next; } if (particle->children->type == XML_SCHEMA_TYPE_CHOICE) return (0); else return (1); } /** * xmlSchemaIsParticleEmptiable: * @particle: the particle * * Schema Component Constraint: Particle Emptiable * Checks whether the given particle is emptiable. * * Returns 1 if emptiable, 0 otherwise. */ static int xmlSchemaIsParticleEmptiable(xmlSchemaParticlePtr particle) { /* * SPEC (1) "Its {min occurs} is 0." */ if ((particle == NULL) || (particle->minOccurs == 0) || (particle->children == NULL)) return (1); /* * SPEC (2) "Its {term} is a group and the minimum part of the * effective total range of that group, [...] is 0." */ if (WXS_IS_MODEL_GROUP(particle->children)) return (xmlSchemaGetParticleEmptiable(particle)); return (0); } /** * xmlSchemaCheckCOSSTDerivedOK: * @actxt: a context * @type: the derived simple type definition * @baseType: the base type definition * @subset: the subset of ('restriction', etc.) * * Schema Component Constraint: * Type Derivation OK (Simple) (cos-st-derived-OK) * * Checks whether @type can be validly * derived from @baseType. * * Returns 0 on success, an positive error code otherwise. */ static int xmlSchemaCheckCOSSTDerivedOK(xmlSchemaAbstractCtxtPtr actxt, xmlSchemaTypePtr type, xmlSchemaTypePtr baseType, int subset) { /* * 1 They are the same type definition. * TODO: The identity check might have to be more complex than this. */ if (type == baseType) return (0); /* * 2.1 restriction is not in the subset, or in the {final} * of its own {base type definition}; * * NOTE that this will be used also via "xsi:type". * * TODO: Revise this, it looks strange. How can the "type" * not be fixed or *in* fixing? */ if (WXS_IS_TYPE_NOT_FIXED(type)) if (xmlSchemaTypeFixup(type, actxt) == -1) return(-1); if (WXS_IS_TYPE_NOT_FIXED(baseType)) if (xmlSchemaTypeFixup(baseType, actxt) == -1) return(-1); if ((subset & SUBSET_RESTRICTION) || (xmlSchemaTypeFinalContains(type->baseType, XML_SCHEMAS_TYPE_FINAL_RESTRICTION))) { return (XML_SCHEMAP_COS_ST_DERIVED_OK_2_1); } /* 2.2 */ if (type->baseType == baseType) { /* * 2.2.1 D's `base type definition` is B. */ return (0); } /* * 2.2.2 D's `base type definition` is not the `ur-type definition` * and is validly derived from B given the subset, as defined by this * constraint. */ if ((! WXS_IS_ANYTYPE(type->baseType)) && (xmlSchemaCheckCOSSTDerivedOK(actxt, type->baseType, baseType, subset) == 0)) { return (0); } /* * 2.2.3 D's {variety} is list or union and B is the `simple ur-type * definition`. */ if (WXS_IS_ANY_SIMPLE_TYPE(baseType) && (WXS_IS_LIST(type) || WXS_IS_UNION(type))) { return (0); } /* * 2.2.4 B's {variety} is union and D is validly derived from a type * definition in B's {member type definitions} given the subset, as * defined by this constraint. * * NOTE: This seems not to involve built-in types, since there is no * built-in Union Simple Type. */ if (WXS_IS_UNION(baseType)) { xmlSchemaTypeLinkPtr cur; cur = baseType->memberTypes; while (cur != NULL) { if (WXS_IS_TYPE_NOT_FIXED(cur->type)) if (xmlSchemaTypeFixup(cur->type, actxt) == -1) return(-1); if (xmlSchemaCheckCOSSTDerivedOK(actxt, type, cur->type, subset) == 0) { /* * It just has to be validly derived from at least one * member-type. */ return (0); } cur = cur->next; } } return (XML_SCHEMAP_COS_ST_DERIVED_OK_2_2); } /** * xmlSchemaCheckTypeDefCircularInternal: * @pctxt: the schema parser context * @ctxtType: the type definition * @ancestor: an ancestor of @ctxtType * * Checks st-props-correct (2) + ct-props-correct (3). * Circular type definitions are not allowed. * * Returns XML_SCHEMAP_ST_PROPS_CORRECT_2 if the given type is * circular, 0 otherwise. */ static int xmlSchemaCheckTypeDefCircularInternal(xmlSchemaParserCtxtPtr pctxt, xmlSchemaTypePtr ctxtType, xmlSchemaTypePtr ancestor) { int ret; if ((ancestor == NULL) || (ancestor->type == XML_SCHEMA_TYPE_BASIC)) return (0); if (ctxtType == ancestor) { xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_ST_PROPS_CORRECT_2, WXS_BASIC_CAST ctxtType, WXS_ITEM_NODE(ctxtType), "The definition is circular", NULL); return (XML_SCHEMAP_ST_PROPS_CORRECT_2); } if (ancestor->flags & XML_SCHEMAS_TYPE_MARKED) { /* * Avoid infinite recursion on circular types not yet checked. */ return (0); } ancestor->flags |= XML_SCHEMAS_TYPE_MARKED; ret = xmlSchemaCheckTypeDefCircularInternal(pctxt, ctxtType, ancestor->baseType); ancestor->flags ^= XML_SCHEMAS_TYPE_MARKED; return (ret); } /** * xmlSchemaCheckTypeDefCircular: * @item: the complex/simple type definition * @ctxt: the parser context * @name: the name * * Checks for circular type definitions. */ static void xmlSchemaCheckTypeDefCircular(xmlSchemaTypePtr item, xmlSchemaParserCtxtPtr ctxt) { if ((item == NULL) || (item->type == XML_SCHEMA_TYPE_BASIC) || (item->baseType == NULL)) return; xmlSchemaCheckTypeDefCircularInternal(ctxt, item, item->baseType); } /* * Simple Type Definition Representation OK (src-simple-type) 4 * * "4 Circular union type definition is disallowed. That is, if the * <union> alternative is chosen, there must not be any entries in the * memberTypes [attribute] at any depth which resolve to the component * corresponding to the <simpleType>." * * Note that this should work on the *representation* of a component, * thus assumes any union types in the member types not being yet * substituted. At this stage we need the variety of the types * to be already computed. */ static int xmlSchemaCheckUnionTypeDefCircularRecur(xmlSchemaParserCtxtPtr pctxt, xmlSchemaTypePtr ctxType, xmlSchemaTypeLinkPtr members) { xmlSchemaTypeLinkPtr member; xmlSchemaTypePtr memberType; member = members; while (member != NULL) { memberType = member->type; while ((memberType != NULL) && (memberType->type != XML_SCHEMA_TYPE_BASIC)) { if (memberType == ctxType) { xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_SRC_SIMPLE_TYPE_4, WXS_BASIC_CAST ctxType, NULL, "The union type definition is circular", NULL); return (XML_SCHEMAP_SRC_SIMPLE_TYPE_4); } if ((WXS_IS_UNION(memberType)) && ((memberType->flags & XML_SCHEMAS_TYPE_MARKED) == 0)) { int res; memberType->flags |= XML_SCHEMAS_TYPE_MARKED; res = xmlSchemaCheckUnionTypeDefCircularRecur(pctxt, ctxType, xmlSchemaGetUnionSimpleTypeMemberTypes(memberType)); memberType->flags ^= XML_SCHEMAS_TYPE_MARKED; if (res != 0) return(res); } memberType = memberType->baseType; } member = member->next; } return(0); } static int xmlSchemaCheckUnionTypeDefCircular(xmlSchemaParserCtxtPtr pctxt, xmlSchemaTypePtr type) { if (! WXS_IS_UNION(type)) return(0); return(xmlSchemaCheckUnionTypeDefCircularRecur(pctxt, type, type->memberTypes)); } /** * xmlSchemaResolveTypeReferences: * @item: the complex/simple type definition * @ctxt: the parser context * @name: the name * * Resolves type definition references */ static void xmlSchemaResolveTypeReferences(xmlSchemaTypePtr typeDef, xmlSchemaParserCtxtPtr ctxt) { if (typeDef == NULL) return; /* * Resolve the base type. */ if (typeDef->baseType == NULL) { typeDef->baseType = xmlSchemaGetType(ctxt->schema, typeDef->base, typeDef->baseNs); if (typeDef->baseType == NULL) { xmlSchemaPResCompAttrErr(ctxt, XML_SCHEMAP_SRC_RESOLVE, WXS_BASIC_CAST typeDef, typeDef->node, "base", typeDef->base, typeDef->baseNs, XML_SCHEMA_TYPE_SIMPLE, NULL); return; } } if (WXS_IS_SIMPLE(typeDef)) { if (WXS_IS_UNION(typeDef)) { /* * Resolve the memberTypes. */ xmlSchemaResolveUnionMemberTypes(ctxt, typeDef); return; } else if (WXS_IS_LIST(typeDef)) { /* * Resolve the itemType. */ if ((typeDef->subtypes == NULL) && (typeDef->base != NULL)) { typeDef->subtypes = xmlSchemaGetType(ctxt->schema, typeDef->base, typeDef->baseNs); if ((typeDef->subtypes == NULL) || (! WXS_IS_SIMPLE(typeDef->subtypes))) { typeDef->subtypes = NULL; xmlSchemaPResCompAttrErr(ctxt, XML_SCHEMAP_SRC_RESOLVE, WXS_BASIC_CAST typeDef, typeDef->node, "itemType", typeDef->base, typeDef->baseNs, XML_SCHEMA_TYPE_SIMPLE, NULL); } } return; } } /* * The ball of letters below means, that if we have a particle * which has a QName-helper component as its {term}, we want * to resolve it... */ else if ((WXS_TYPE_CONTENTTYPE(typeDef) != NULL) && ((WXS_TYPE_CONTENTTYPE(typeDef))->type == XML_SCHEMA_TYPE_PARTICLE) && (WXS_TYPE_PARTICLE_TERM(typeDef) != NULL) && ((WXS_TYPE_PARTICLE_TERM(typeDef))->type == XML_SCHEMA_EXTRA_QNAMEREF)) { xmlSchemaQNameRefPtr ref = WXS_QNAME_CAST WXS_TYPE_PARTICLE_TERM(typeDef); xmlSchemaModelGroupDefPtr groupDef; /* * URGENT TODO: Test this. */ WXS_TYPE_PARTICLE_TERM(typeDef) = NULL; /* * Resolve the MG definition reference. */ groupDef = WXS_MODEL_GROUPDEF_CAST xmlSchemaGetNamedComponent(ctxt->schema, ref->itemType, ref->name, ref->targetNamespace); if (groupDef == NULL) { xmlSchemaPResCompAttrErr(ctxt, XML_SCHEMAP_SRC_RESOLVE, NULL, WXS_ITEM_NODE(WXS_TYPE_PARTICLE(typeDef)), "ref", ref->name, ref->targetNamespace, ref->itemType, NULL); /* Remove the particle. */ WXS_TYPE_CONTENTTYPE(typeDef) = NULL; } else if (WXS_MODELGROUPDEF_MODEL(groupDef) == NULL) /* Remove the particle. */ WXS_TYPE_CONTENTTYPE(typeDef) = NULL; else { /* * Assign the MG definition's {model group} to the * particle's {term}. */ WXS_TYPE_PARTICLE_TERM(typeDef) = WXS_MODELGROUPDEF_MODEL(groupDef); if (WXS_MODELGROUPDEF_MODEL(groupDef)->type == XML_SCHEMA_TYPE_ALL) { /* * SPEC cos-all-limited (1.2) * "1.2 the {term} property of a particle with * {max occurs}=1 which is part of a pair which constitutes * the {content type} of a complex type definition." */ if ((WXS_TYPE_PARTICLE(typeDef))->maxOccurs != 1) { xmlSchemaCustomErr(ACTXT_CAST ctxt, /* TODO: error code */ XML_SCHEMAP_COS_ALL_LIMITED, WXS_ITEM_NODE(WXS_TYPE_PARTICLE(typeDef)), NULL, "The particle's {max occurs} must be 1, since the " "reference resolves to an 'all' model group", NULL, NULL); } } } } } /** * xmlSchemaCheckSTPropsCorrect: * @ctxt: the schema parser context * @type: the simple type definition * * Checks st-props-correct. * * Returns 0 if the properties are correct, * if not, a positive error code and -1 on internal * errors. */ static int xmlSchemaCheckSTPropsCorrect(xmlSchemaParserCtxtPtr ctxt, xmlSchemaTypePtr type) { xmlSchemaTypePtr baseType = type->baseType; xmlChar *str = NULL; /* STATE: error funcs converted. */ /* * Schema Component Constraint: Simple Type Definition Properties Correct * * NOTE: This is somehow redundant, since we actually built a simple type * to have all the needed information; this acts as an self test. */ /* Base type: If the datatype has been `derived` by `restriction` * then the Simple Type Definition component from which it is `derived`, * otherwise the Simple Type Definition for anySimpleType ($4.1.6). */ if (baseType == NULL) { /* * TODO: Think about: "modulo the impact of Missing * Sub-components ($5.3)." */ xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_ST_PROPS_CORRECT_1, WXS_BASIC_CAST type, NULL, "No base type existent", NULL); return (XML_SCHEMAP_ST_PROPS_CORRECT_1); } if (! WXS_IS_SIMPLE(baseType)) { xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_ST_PROPS_CORRECT_1, WXS_BASIC_CAST type, NULL, "The base type '%s' is not a simple type", xmlSchemaGetComponentQName(&str, baseType)); FREE_AND_NULL(str) return (XML_SCHEMAP_ST_PROPS_CORRECT_1); } if ((WXS_IS_LIST(type) || WXS_IS_UNION(type)) && (WXS_IS_RESTRICTION(type) == 0) && ((! WXS_IS_ANY_SIMPLE_TYPE(baseType)) && (baseType->type != XML_SCHEMA_TYPE_SIMPLE))) { xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_ST_PROPS_CORRECT_1, WXS_BASIC_CAST type, NULL, "A type, derived by list or union, must have " "the simple ur-type definition as base type, not '%s'", xmlSchemaGetComponentQName(&str, baseType)); FREE_AND_NULL(str) return (XML_SCHEMAP_ST_PROPS_CORRECT_1); } /* * Variety: One of {atomic, list, union}. */ if ((! WXS_IS_ATOMIC(type)) && (! WXS_IS_UNION(type)) && (! WXS_IS_LIST(type))) { xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_ST_PROPS_CORRECT_1, WXS_BASIC_CAST type, NULL, "The variety is absent", NULL); return (XML_SCHEMAP_ST_PROPS_CORRECT_1); } /* TODO: Finish this. Hmm, is this finished? */ /* * 3 The {final} of the {base type definition} must not contain restriction. */ if (xmlSchemaTypeFinalContains(baseType, XML_SCHEMAS_TYPE_FINAL_RESTRICTION)) { xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_ST_PROPS_CORRECT_3, WXS_BASIC_CAST type, NULL, "The 'final' of its base type '%s' must not contain " "'restriction'", xmlSchemaGetComponentQName(&str, baseType)); FREE_AND_NULL(str) return (XML_SCHEMAP_ST_PROPS_CORRECT_3); } /* * 2 All simple type definitions must be derived ultimately from the `simple * ur-type definition` (so circular definitions are disallowed). That is, it * must be possible to reach a built-in primitive datatype or the `simple * ur-type definition` by repeatedly following the {base type definition}. * * NOTE: this is done in xmlSchemaCheckTypeDefCircular(). */ return (0); } /** * xmlSchemaCheckCOSSTRestricts: * @ctxt: the schema parser context * @type: the simple type definition * * Schema Component Constraint: * Derivation Valid (Restriction, Simple) (cos-st-restricts) * Checks if the given @type (simpleType) is derived validly by restriction. * STATUS: * * Returns -1 on internal errors, 0 if the type is validly derived, * a positive error code otherwise. */ static int xmlSchemaCheckCOSSTRestricts(xmlSchemaParserCtxtPtr pctxt, xmlSchemaTypePtr type) { xmlChar *str = NULL; if (type->type != XML_SCHEMA_TYPE_SIMPLE) { PERROR_INT("xmlSchemaCheckCOSSTRestricts", "given type is not a user-derived simpleType"); return (-1); } if (WXS_IS_ATOMIC(type)) { xmlSchemaTypePtr primitive; /* * 1.1 The {base type definition} must be an atomic simple * type definition or a built-in primitive datatype. */ if (! WXS_IS_ATOMIC(type->baseType)) { xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_COS_ST_RESTRICTS_1_1, WXS_BASIC_CAST type, NULL, "The base type '%s' is not an atomic simple type", xmlSchemaGetComponentQName(&str, type->baseType)); FREE_AND_NULL(str) return (XML_SCHEMAP_COS_ST_RESTRICTS_1_1); } /* 1.2 The {final} of the {base type definition} must not contain * restriction. */ /* OPTIMIZE TODO : This is already done in xmlSchemaCheckStPropsCorrect */ if (xmlSchemaTypeFinalContains(type->baseType, XML_SCHEMAS_TYPE_FINAL_RESTRICTION)) { xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_COS_ST_RESTRICTS_1_2, WXS_BASIC_CAST type, NULL, "The final of its base type '%s' must not contain 'restriction'", xmlSchemaGetComponentQName(&str, type->baseType)); FREE_AND_NULL(str) return (XML_SCHEMAP_COS_ST_RESTRICTS_1_2); } /* * 1.3.1 DF must be an allowed constraining facet for the {primitive * type definition}, as specified in the appropriate subsection of 3.2 * Primitive datatypes. */ if (type->facets != NULL) { xmlSchemaFacetPtr facet; int ok = 1; primitive = xmlSchemaGetPrimitiveType(type); if (primitive == NULL) { PERROR_INT("xmlSchemaCheckCOSSTRestricts", "failed to get primitive type"); return (-1); } facet = type->facets; do { if (xmlSchemaIsBuiltInTypeFacet(primitive, facet->type) == 0) { ok = 0; xmlSchemaPIllegalFacetAtomicErr(pctxt, XML_SCHEMAP_COS_ST_RESTRICTS_1_3_1, type, primitive, facet); } facet = facet->next; } while (facet != NULL); if (ok == 0) return (XML_SCHEMAP_COS_ST_RESTRICTS_1_3_1); } /* * SPEC (1.3.2) "If there is a facet of the same kind in the {facets} * of the {base type definition} (call this BF),then the DF's {value} * must be a valid restriction of BF's {value} as defined in * [XML Schemas: Datatypes]." * * NOTE (1.3.2) Facet derivation constraints are currently handled in * xmlSchemaDeriveAndValidateFacets() */ } else if (WXS_IS_LIST(type)) { xmlSchemaTypePtr itemType = NULL; itemType = type->subtypes; if ((itemType == NULL) || (! WXS_IS_SIMPLE(itemType))) { PERROR_INT("xmlSchemaCheckCOSSTRestricts", "failed to evaluate the item type"); return (-1); } if (WXS_IS_TYPE_NOT_FIXED(itemType)) xmlSchemaTypeFixup(itemType, ACTXT_CAST pctxt); /* * 2.1 The {item type definition} must have a {variety} of atomic or * union (in which case all the {member type definitions} * must be atomic). */ if ((! WXS_IS_ATOMIC(itemType)) && (! WXS_IS_UNION(itemType))) { xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_COS_ST_RESTRICTS_2_1, WXS_BASIC_CAST type, NULL, "The item type '%s' does not have a variety of atomic or union", xmlSchemaGetComponentQName(&str, itemType)); FREE_AND_NULL(str) return (XML_SCHEMAP_COS_ST_RESTRICTS_2_1); } else if (WXS_IS_UNION(itemType)) { xmlSchemaTypeLinkPtr member; member = itemType->memberTypes; while (member != NULL) { if (! WXS_IS_ATOMIC(member->type)) { xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_COS_ST_RESTRICTS_2_1, WXS_BASIC_CAST type, NULL, "The item type is a union type, but the " "member type '%s' of this item type is not atomic", xmlSchemaGetComponentQName(&str, member->type)); FREE_AND_NULL(str) return (XML_SCHEMAP_COS_ST_RESTRICTS_2_1); } member = member->next; } } if (WXS_IS_ANY_SIMPLE_TYPE(type->baseType)) { xmlSchemaFacetPtr facet; /* * This is the case if we have: <simpleType><list .. */ /* * 2.3.1 * 2.3.1.1 The {final} of the {item type definition} must not * contain list. */ if (xmlSchemaTypeFinalContains(itemType, XML_SCHEMAS_TYPE_FINAL_LIST)) { xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_COS_ST_RESTRICTS_2_3_1_1, WXS_BASIC_CAST type, NULL, "The final of its item type '%s' must not contain 'list'", xmlSchemaGetComponentQName(&str, itemType)); FREE_AND_NULL(str) return (XML_SCHEMAP_COS_ST_RESTRICTS_2_3_1_1); } /* * 2.3.1.2 The {facets} must only contain the whiteSpace * facet component. * OPTIMIZE TODO: the S4S already disallows any facet * to be specified. */ if (type->facets != NULL) { facet = type->facets; do { if (facet->type != XML_SCHEMA_FACET_WHITESPACE) { xmlSchemaPIllegalFacetListUnionErr(pctxt, XML_SCHEMAP_COS_ST_RESTRICTS_2_3_1_2, type, facet); return (XML_SCHEMAP_COS_ST_RESTRICTS_2_3_1_2); } facet = facet->next; } while (facet != NULL); } /* * MAYBE TODO: (Hmm, not really) Datatypes states: * A `list` datatype can be `derived` from an `atomic` datatype * whose `lexical space` allows space (such as string or anyURI)or * a `union` datatype any of whose {member type definitions}'s * `lexical space` allows space. */ } else { /* * This is the case if we have: <simpleType><restriction ... * I.e. the variety of "list" is inherited. */ /* * 2.3.2 * 2.3.2.1 The {base type definition} must have a {variety} of list. */ if (! WXS_IS_LIST(type->baseType)) { xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_1, WXS_BASIC_CAST type, NULL, "The base type '%s' must be a list type", xmlSchemaGetComponentQName(&str, type->baseType)); FREE_AND_NULL(str) return (XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_1); } /* * 2.3.2.2 The {final} of the {base type definition} must not * contain restriction. */ if (xmlSchemaTypeFinalContains(type->baseType, XML_SCHEMAS_TYPE_FINAL_RESTRICTION)) { xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_2, WXS_BASIC_CAST type, NULL, "The 'final' of the base type '%s' must not contain 'restriction'", xmlSchemaGetComponentQName(&str, type->baseType)); FREE_AND_NULL(str) return (XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_2); } /* * 2.3.2.3 The {item type definition} must be validly derived * from the {base type definition}'s {item type definition} given * the empty set, as defined in Type Derivation OK (Simple) ($3.14.6). */ { xmlSchemaTypePtr baseItemType; baseItemType = type->baseType->subtypes; if ((baseItemType == NULL) || (! WXS_IS_SIMPLE(baseItemType))) { PERROR_INT("xmlSchemaCheckCOSSTRestricts", "failed to eval the item type of a base type"); return (-1); } if ((itemType != baseItemType) && (xmlSchemaCheckCOSSTDerivedOK(ACTXT_CAST pctxt, itemType, baseItemType, 0) != 0)) { xmlChar *strBIT = NULL, *strBT = NULL; xmlSchemaPCustomErrExt(pctxt, XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_3, WXS_BASIC_CAST type, NULL, "The item type '%s' is not validly derived from " "the item type '%s' of the base type '%s'", xmlSchemaGetComponentQName(&str, itemType), xmlSchemaGetComponentQName(&strBIT, baseItemType), xmlSchemaGetComponentQName(&strBT, type->baseType)); FREE_AND_NULL(str) FREE_AND_NULL(strBIT) FREE_AND_NULL(strBT) return (XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_3); } } if (type->facets != NULL) { xmlSchemaFacetPtr facet; int ok = 1; /* * 2.3.2.4 Only length, minLength, maxLength, whiteSpace, pattern * and enumeration facet components are allowed among the {facets}. */ facet = type->facets; do { switch (facet->type) { case XML_SCHEMA_FACET_LENGTH: case XML_SCHEMA_FACET_MINLENGTH: case XML_SCHEMA_FACET_MAXLENGTH: case XML_SCHEMA_FACET_WHITESPACE: /* * TODO: 2.5.1.2 List datatypes * The value of `whiteSpace` is fixed to the value collapse. */ case XML_SCHEMA_FACET_PATTERN: case XML_SCHEMA_FACET_ENUMERATION: break; default: { xmlSchemaPIllegalFacetListUnionErr(pctxt, XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_4, type, facet); /* * We could return, but it's nicer to report all * invalid facets. */ ok = 0; } } facet = facet->next; } while (facet != NULL); if (ok == 0) return (XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_4); /* * SPEC (2.3.2.5) (same as 1.3.2) * * NOTE (2.3.2.5) This is currently done in * xmlSchemaDeriveAndValidateFacets() */ } } } else if (WXS_IS_UNION(type)) { /* * 3.1 The {member type definitions} must all have {variety} of * atomic or list. */ xmlSchemaTypeLinkPtr member; member = type->memberTypes; while (member != NULL) { if (WXS_IS_TYPE_NOT_FIXED(member->type)) xmlSchemaTypeFixup(member->type, ACTXT_CAST pctxt); if ((! WXS_IS_ATOMIC(member->type)) && (! WXS_IS_LIST(member->type))) { xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_COS_ST_RESTRICTS_3_1, WXS_BASIC_CAST type, NULL, "The member type '%s' is neither an atomic, nor a list type", xmlSchemaGetComponentQName(&str, member->type)); FREE_AND_NULL(str) return (XML_SCHEMAP_COS_ST_RESTRICTS_3_1); } member = member->next; } /* * 3.3.1 If the {base type definition} is the `simple ur-type * definition` */ if (type->baseType->builtInType == XML_SCHEMAS_ANYSIMPLETYPE) { /* * 3.3.1.1 All of the {member type definitions} must have a * {final} which does not contain union. */ member = type->memberTypes; while (member != NULL) { if (xmlSchemaTypeFinalContains(member->type, XML_SCHEMAS_TYPE_FINAL_UNION)) { xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_COS_ST_RESTRICTS_3_3_1, WXS_BASIC_CAST type, NULL, "The 'final' of member type '%s' contains 'union'", xmlSchemaGetComponentQName(&str, member->type)); FREE_AND_NULL(str) return (XML_SCHEMAP_COS_ST_RESTRICTS_3_3_1); } member = member->next; } /* * 3.3.1.2 The {facets} must be empty. */ if (type->facetSet != NULL) { xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_COS_ST_RESTRICTS_3_3_1_2, WXS_BASIC_CAST type, NULL, "No facets allowed", NULL); return (XML_SCHEMAP_COS_ST_RESTRICTS_3_3_1_2); } } else { /* * 3.3.2.1 The {base type definition} must have a {variety} of union. * I.e. the variety of "list" is inherited. */ if (! WXS_IS_UNION(type->baseType)) { xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_1, WXS_BASIC_CAST type, NULL, "The base type '%s' is not a union type", xmlSchemaGetComponentQName(&str, type->baseType)); FREE_AND_NULL(str) return (XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_1); } /* * 3.3.2.2 The {final} of the {base type definition} must not contain restriction. */ if (xmlSchemaTypeFinalContains(type->baseType, XML_SCHEMAS_TYPE_FINAL_RESTRICTION)) { xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_2, WXS_BASIC_CAST type, NULL, "The 'final' of its base type '%s' must not contain 'restriction'", xmlSchemaGetComponentQName(&str, type->baseType)); FREE_AND_NULL(str) return (XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_2); } /* * 3.3.2.3 The {member type definitions}, in order, must be validly * derived from the corresponding type definitions in the {base * type definition}'s {member type definitions} given the empty set, * as defined in Type Derivation OK (Simple) ($3.14.6). */ { xmlSchemaTypeLinkPtr baseMember; /* * OPTIMIZE: if the type is restricting, it has no local defined * member types and inherits the member types of the base type; * thus a check for equality can be skipped. */ /* * Even worse: I cannot see a scenario where a restricting * union simple type can have other member types as the member * types of it's base type. This check seems not necessary with * respect to the derivation process in libxml2. * But necessary if constructing types with an API. */ if (type->memberTypes != NULL) { member = type->memberTypes; baseMember = xmlSchemaGetUnionSimpleTypeMemberTypes(type->baseType); if ((member == NULL) && (baseMember != NULL)) { PERROR_INT("xmlSchemaCheckCOSSTRestricts", "different number of member types in base"); } while (member != NULL) { if (baseMember == NULL) { PERROR_INT("xmlSchemaCheckCOSSTRestricts", "different number of member types in base"); } else if ((member->type != baseMember->type) && (xmlSchemaCheckCOSSTDerivedOK(ACTXT_CAST pctxt, member->type, baseMember->type, 0) != 0)) { xmlChar *strBMT = NULL, *strBT = NULL; xmlSchemaPCustomErrExt(pctxt, XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_3, WXS_BASIC_CAST type, NULL, "The member type %s is not validly " "derived from its corresponding member " "type %s of the base type %s", xmlSchemaGetComponentQName(&str, member->type), xmlSchemaGetComponentQName(&strBMT, baseMember->type), xmlSchemaGetComponentQName(&strBT, type->baseType)); FREE_AND_NULL(str) FREE_AND_NULL(strBMT) FREE_AND_NULL(strBT) return (XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_3); } member = member->next; if (baseMember != NULL) baseMember = baseMember->next; } } } /* * 3.3.2.4 Only pattern and enumeration facet components are * allowed among the {facets}. */ if (type->facets != NULL) { xmlSchemaFacetPtr facet; int ok = 1; facet = type->facets; do { if ((facet->type != XML_SCHEMA_FACET_PATTERN) && (facet->type != XML_SCHEMA_FACET_ENUMERATION)) { xmlSchemaPIllegalFacetListUnionErr(pctxt, XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_4, type, facet); ok = 0; } facet = facet->next; } while (facet != NULL); if (ok == 0) return (XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_4); } /* * SPEC (3.3.2.5) (same as 1.3.2) * * NOTE (3.3.2.5) This is currently done in * xmlSchemaDeriveAndValidateFacets() */ } } return (0); } /** * xmlSchemaCheckSRCSimpleType: * @ctxt: the schema parser context * @type: the simple type definition * * Checks crc-simple-type constraints. * * Returns 0 if the constraints are satisfied, * if not a positive error code and -1 on internal * errors. */ #if 0 static int xmlSchemaCheckSRCSimpleType(xmlSchemaParserCtxtPtr ctxt, xmlSchemaTypePtr type) { /* * src-simple-type.1 The corresponding simple type definition, if any, * must satisfy the conditions set out in Constraints on Simple Type * Definition Schema Components ($3.14.6). */ if (WXS_IS_RESTRICTION(type)) { /* * src-simple-type.2 "If the <restriction> alternative is chosen, * either it must have a base [attribute] or a <simpleType> among its * [children], but not both." * NOTE: This is checked in the parse function of <restriction>. */ /* * */ } else if (WXS_IS_LIST(type)) { /* src-simple-type.3 "If the <list> alternative is chosen, either it must have * an itemType [attribute] or a <simpleType> among its [children], * but not both." * * NOTE: This is checked in the parse function of <list>. */ } else if (WXS_IS_UNION(type)) { /* * src-simple-type.4 is checked in xmlSchemaCheckUnionTypeDefCircular(). */ } return (0); } #endif static int xmlSchemaCreateVCtxtOnPCtxt(xmlSchemaParserCtxtPtr ctxt) { if (ctxt->vctxt == NULL) { ctxt->vctxt = xmlSchemaNewValidCtxt(NULL); if (ctxt->vctxt == NULL) { xmlSchemaPErr(ctxt, NULL, XML_SCHEMAP_INTERNAL, "Internal error: xmlSchemaCreateVCtxtOnPCtxt, " "failed to create a temp. validation context.\n", NULL, NULL); return (-1); } /* TODO: Pass user data. */ xmlSchemaSetValidErrors(ctxt->vctxt, ctxt->error, ctxt->warning, ctxt->errCtxt); xmlSchemaSetValidStructuredErrors(ctxt->vctxt, ctxt->serror, ctxt->errCtxt); } return (0); } static int xmlSchemaVCheckCVCSimpleType(xmlSchemaAbstractCtxtPtr actxt, xmlNodePtr node, xmlSchemaTypePtr type, const xmlChar *value, xmlSchemaValPtr *retVal, int fireErrors, int normalize, int isNormalized); /** * xmlSchemaParseCheckCOSValidDefault: * @pctxt: the schema parser context * @type: the simple type definition * @value: the default value * @node: an optional node (the holder of the value) * * Schema Component Constraint: Element Default Valid (Immediate) * (cos-valid-default) * This will be used by the parser only. For the validator there's * an other version. * * Returns 0 if the constraints are satisfied, * if not, a positive error code and -1 on internal * errors. */ static int xmlSchemaParseCheckCOSValidDefault(xmlSchemaParserCtxtPtr pctxt, xmlNodePtr node, xmlSchemaTypePtr type, const xmlChar *value, xmlSchemaValPtr *val) { int ret = 0; /* * cos-valid-default: * Schema Component Constraint: Element Default Valid (Immediate) * For a string to be a valid default with respect to a type * definition the appropriate case among the following must be true: */ if WXS_IS_COMPLEX(type) { /* * Complex type. * * SPEC (2.1) "its {content type} must be a simple type definition * or mixed." * SPEC (2.2.2) "If the {content type} is mixed, then the {content * type}'s particle must be `emptiable` as defined by * Particle Emptiable ($3.9.6)." */ if ((! WXS_HAS_SIMPLE_CONTENT(type)) && ((! WXS_HAS_MIXED_CONTENT(type)) || (! WXS_EMPTIABLE(type)))) { /* NOTE that this covers (2.2.2) as well. */ xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_COS_VALID_DEFAULT_2_1, WXS_BASIC_CAST type, type->node, "For a string to be a valid default, the type definition " "must be a simple type or a complex type with mixed content " "and a particle emptiable", NULL); return(XML_SCHEMAP_COS_VALID_DEFAULT_2_1); } } /* * 1 If the type definition is a simple type definition, then the string * must be `valid` with respect to that definition as defined by String * Valid ($3.14.4). * * AND * * 2.2.1 If the {content type} is a simple type definition, then the * string must be `valid` with respect to that simple type definition * as defined by String Valid ($3.14.4). */ if (WXS_IS_SIMPLE(type)) ret = xmlSchemaVCheckCVCSimpleType(ACTXT_CAST pctxt, node, type, value, val, 1, 1, 0); else if (WXS_HAS_SIMPLE_CONTENT(type)) ret = xmlSchemaVCheckCVCSimpleType(ACTXT_CAST pctxt, node, type->contentTypeDef, value, val, 1, 1, 0); else return (ret); if (ret < 0) { PERROR_INT("xmlSchemaParseCheckCOSValidDefault", "calling xmlSchemaVCheckCVCSimpleType()"); } return (ret); } /** * xmlSchemaCheckCTPropsCorrect: * @ctxt: the schema parser context * @type: the complex type definition * *.(4.6) Constraints on Complex Type Definition Schema Components * Schema Component Constraint: * Complex Type Definition Properties Correct (ct-props-correct) * STATUS: (seems) complete * * Returns 0 if the constraints are satisfied, a positive * error code if not and -1 if an internal error occurred. */ static int xmlSchemaCheckCTPropsCorrect(xmlSchemaParserCtxtPtr pctxt, xmlSchemaTypePtr type) { /* * TODO: Correct the error code; XML_SCHEMAP_SRC_CT_1 is used temporarily. * * SPEC (1) "The values of the properties of a complex type definition must * be as described in the property tableau in The Complex Type Definition * Schema Component ($3.4.1), modulo the impact of Missing * Sub-components ($5.3)." */ if ((type->baseType != NULL) && (WXS_IS_SIMPLE(type->baseType)) && (WXS_IS_EXTENSION(type) == 0)) { /* * SPEC (2) "If the {base type definition} is a simple type definition, * the {derivation method} must be extension." */ xmlSchemaCustomErr(ACTXT_CAST pctxt, XML_SCHEMAP_SRC_CT_1, NULL, WXS_BASIC_CAST type, "If the base type is a simple type, the derivation method must be " "'extension'", NULL, NULL); return (XML_SCHEMAP_SRC_CT_1); } /* * SPEC (3) "Circular definitions are disallowed, except for the `ur-type * definition`. That is, it must be possible to reach the `ur-type * definition` by repeatedly following the {base type definition}." * * NOTE (3) is done in xmlSchemaCheckTypeDefCircular(). */ /* * NOTE that (4) and (5) need the following: * - attribute uses need to be already inherited (apply attr. prohibitions) * - attribute group references need to be expanded already * - simple types need to be typefixed already */ if (type->attrUses && (((xmlSchemaItemListPtr) type->attrUses)->nbItems > 1)) { xmlSchemaItemListPtr uses = (xmlSchemaItemListPtr) type->attrUses; xmlSchemaAttributeUsePtr use, tmp; int i, j, hasId = 0; for (i = uses->nbItems -1; i >= 0; i--) { use = uses->items[i]; /* * SPEC ct-props-correct * (4) "Two distinct attribute declarations in the * {attribute uses} must not have identical {name}s and * {target namespace}s." */ if (i > 0) { for (j = i -1; j >= 0; j--) { tmp = uses->items[j]; if ((WXS_ATTRUSE_DECL_NAME(use) == WXS_ATTRUSE_DECL_NAME(tmp)) && (WXS_ATTRUSE_DECL_TNS(use) == WXS_ATTRUSE_DECL_TNS(tmp))) { xmlChar *str = NULL; xmlSchemaCustomErr(ACTXT_CAST pctxt, XML_SCHEMAP_AG_PROPS_CORRECT, NULL, WXS_BASIC_CAST type, "Duplicate %s", xmlSchemaGetComponentDesignation(&str, use), NULL); FREE_AND_NULL(str); /* * Remove the duplicate. */ if (xmlSchemaItemListRemove(uses, i) == -1) goto exit_failure; goto next_use; } } } /* * SPEC ct-props-correct * (5) "Two distinct attribute declarations in the * {attribute uses} must not have {type definition}s which * are or are derived from ID." */ if (WXS_ATTRUSE_TYPEDEF(use) != NULL) { if (xmlSchemaIsDerivedFromBuiltInType( WXS_ATTRUSE_TYPEDEF(use), XML_SCHEMAS_ID)) { if (hasId) { xmlChar *str = NULL; xmlSchemaCustomErr(ACTXT_CAST pctxt, XML_SCHEMAP_AG_PROPS_CORRECT, NULL, WXS_BASIC_CAST type, "There must not exist more than one attribute " "declaration of type 'xs:ID' " "(or derived from 'xs:ID'). The %s violates this " "constraint", xmlSchemaGetComponentDesignation(&str, use), NULL); FREE_AND_NULL(str); if (xmlSchemaItemListRemove(uses, i) == -1) goto exit_failure; } hasId = 1; } } next_use: {} } } return (0); exit_failure: return(-1); } static int xmlSchemaAreEqualTypes(xmlSchemaTypePtr typeA, xmlSchemaTypePtr typeB) { /* * TODO: This should implement component-identity * in the future. */ if ((typeA == NULL) || (typeB == NULL)) return (0); return (typeA == typeB); } /** * xmlSchemaCheckCOSCTDerivedOK: * @ctxt: the schema parser context * @type: the to-be derived complex type definition * @baseType: the base complex type definition * @set: the given set * * Schema Component Constraint: * Type Derivation OK (Complex) (cos-ct-derived-ok) * * STATUS: completed * * Returns 0 if the constraints are satisfied, or 1 * if not. */ static int xmlSchemaCheckCOSCTDerivedOK(xmlSchemaAbstractCtxtPtr actxt, xmlSchemaTypePtr type, xmlSchemaTypePtr baseType, int set) { int equal = xmlSchemaAreEqualTypes(type, baseType); /* TODO: Error codes. */ /* * SPEC "For a complex type definition (call it D, for derived) * to be validly derived from a type definition (call this * B, for base) given a subset of {extension, restriction} * all of the following must be true:" */ if (! equal) { /* * SPEC (1) "If B and D are not the same type definition, then the * {derivation method} of D must not be in the subset." */ if (((set & SUBSET_EXTENSION) && (WXS_IS_EXTENSION(type))) || ((set & SUBSET_RESTRICTION) && (WXS_IS_RESTRICTION(type)))) return (1); } else { /* * SPEC (2.1) "B and D must be the same type definition." */ return (0); } /* * SPEC (2.2) "B must be D's {base type definition}." */ if (type->baseType == baseType) return (0); /* * SPEC (2.3.1) "D's {base type definition} must not be the `ur-type * definition`." */ if (WXS_IS_ANYTYPE(type->baseType)) return (1); if (WXS_IS_COMPLEX(type->baseType)) { /* * SPEC (2.3.2.1) "If D's {base type definition} is complex, then it * must be validly derived from B given the subset as defined by this * constraint." */ return (xmlSchemaCheckCOSCTDerivedOK(actxt, type->baseType, baseType, set)); } else { /* * SPEC (2.3.2.2) "If D's {base type definition} is simple, then it * must be validly derived from B given the subset as defined in Type * Derivation OK (Simple) ($3.14.6). */ return (xmlSchemaCheckCOSSTDerivedOK(actxt, type->baseType, baseType, set)); } } /** * xmlSchemaCheckCOSDerivedOK: * @type: the derived simple type definition * @baseType: the base type definition * * Calls: * Type Derivation OK (Simple) AND Type Derivation OK (Complex) * * Checks whether @type can be validly derived from @baseType. * * Returns 0 on success, an positive error code otherwise. */ static int xmlSchemaCheckCOSDerivedOK(xmlSchemaAbstractCtxtPtr actxt, xmlSchemaTypePtr type, xmlSchemaTypePtr baseType, int set) { if (WXS_IS_SIMPLE(type)) return (xmlSchemaCheckCOSSTDerivedOK(actxt, type, baseType, set)); else return (xmlSchemaCheckCOSCTDerivedOK(actxt, type, baseType, set)); } /** * xmlSchemaCheckCOSCTExtends: * @ctxt: the schema parser context * @type: the complex type definition * * (3.4.6) Constraints on Complex Type Definition Schema Components * Schema Component Constraint: * Derivation Valid (Extension) (cos-ct-extends) * * STATUS: * missing: * (1.5) * (1.4.3.2.2.2) "Particle Valid (Extension)" * * Returns 0 if the constraints are satisfied, a positive * error code if not and -1 if an internal error occurred. */ static int xmlSchemaCheckCOSCTExtends(xmlSchemaParserCtxtPtr ctxt, xmlSchemaTypePtr type) { xmlSchemaTypePtr base = type->baseType; /* * TODO: Correct the error code; XML_SCHEMAP_COS_CT_EXTENDS_1_1 is used * temporarily only. */ /* * SPEC (1) "If the {base type definition} is a complex type definition, * then all of the following must be true:" */ if (WXS_IS_COMPLEX(base)) { /* * SPEC (1.1) "The {final} of the {base type definition} must not * contain extension." */ if (base->flags & XML_SCHEMAS_TYPE_FINAL_EXTENSION) { xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_COS_CT_EXTENDS_1_1, WXS_BASIC_CAST type, NULL, "The 'final' of the base type definition " "contains 'extension'", NULL); return (XML_SCHEMAP_COS_CT_EXTENDS_1_1); } /* * ATTENTION: The constrains (1.2) and (1.3) are not applied, * since they are automatically satisfied through the * inheriting mechanism. * Note that even if redefining components, the inheriting mechanism * is used. */ #if 0 /* * SPEC (1.2) "Its {attribute uses} must be a subset of the {attribute * uses} * of the complex type definition itself, that is, for every attribute * use in the {attribute uses} of the {base type definition}, there * must be an attribute use in the {attribute uses} of the complex * type definition itself whose {attribute declaration} has the same * {name}, {target namespace} and {type definition} as its attribute * declaration" */ if (base->attrUses != NULL) { int i, j, found; xmlSchemaAttributeUsePtr use, buse; for (i = 0; i < (WXS_LIST_CAST base->attrUses)->nbItems; i ++) { buse = (WXS_LIST_CAST base->attrUses)->items[i]; found = 0; if (type->attrUses != NULL) { use = (WXS_LIST_CAST type->attrUses)->items[j]; for (j = 0; j < (WXS_LIST_CAST type->attrUses)->nbItems; j ++) { if ((WXS_ATTRUSE_DECL_NAME(use) == WXS_ATTRUSE_DECL_NAME(buse)) && (WXS_ATTRUSE_DECL_TNS(use) == WXS_ATTRUSE_DECL_TNS(buse)) && (WXS_ATTRUSE_TYPEDEF(use) == WXS_ATTRUSE_TYPEDEF(buse)) { found = 1; break; } } } if (! found) { xmlChar *str = NULL; xmlSchemaCustomErr(ACTXT_CAST ctxt, XML_SCHEMAP_COS_CT_EXTENDS_1_2, NULL, WXS_BASIC_CAST type, /* * TODO: The report does not indicate that also the * type needs to be the same. */ "This type is missing a matching correspondent " "for its {base type}'s %s in its {attribute uses}", xmlSchemaGetComponentDesignation(&str, buse->children), NULL); FREE_AND_NULL(str) } } } /* * SPEC (1.3) "If it has an {attribute wildcard}, the complex type * definition must also have one, and the base type definition's * {attribute wildcard}'s {namespace constraint} must be a subset * of the complex type definition's {attribute wildcard}'s {namespace * constraint}, as defined by Wildcard Subset ($3.10.6)." */ /* * MAYBE TODO: Enable if ever needed. But this will be needed only * if created the type via a schema construction API. */ if (base->attributeWildcard != NULL) { if (type->attributeWildcard == NULL) { xmlChar *str = NULL; xmlSchemaCustomErr(ACTXT_CAST pctxt, XML_SCHEMAP_COS_CT_EXTENDS_1_3, NULL, type, "The base %s has an attribute wildcard, " "but this type is missing an attribute wildcard", xmlSchemaGetComponentDesignation(&str, base)); FREE_AND_NULL(str) } else if (xmlSchemaCheckCOSNSSubset( base->attributeWildcard, type->attributeWildcard)) { xmlChar *str = NULL; xmlSchemaCustomErr(ACTXT_CAST pctxt, XML_SCHEMAP_COS_CT_EXTENDS_1_3, NULL, type, "The attribute wildcard is not a valid " "superset of the one in the base %s", xmlSchemaGetComponentDesignation(&str, base)); FREE_AND_NULL(str) } } #endif /* * SPEC (1.4) "One of the following must be true:" */ if ((type->contentTypeDef != NULL) && (type->contentTypeDef == base->contentTypeDef)) { /* * SPEC (1.4.1) "The {content type} of the {base type definition} * and the {content type} of the complex type definition itself * must be the same simple type definition" * PASS */ } else if ((type->contentType == XML_SCHEMA_CONTENT_EMPTY) && (base->contentType == XML_SCHEMA_CONTENT_EMPTY) ) { /* * SPEC (1.4.2) "The {content type} of both the {base type * definition} and the complex type definition itself must * be empty." * PASS */ } else { /* * SPEC (1.4.3) "All of the following must be true:" */ if (type->subtypes == NULL) { /* * SPEC 1.4.3.1 The {content type} of the complex type * definition itself must specify a particle. */ xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_COS_CT_EXTENDS_1_1, WXS_BASIC_CAST type, NULL, "The content type must specify a particle", NULL); return (XML_SCHEMAP_COS_CT_EXTENDS_1_1); } /* * SPEC (1.4.3.2) "One of the following must be true:" */ if (base->contentType == XML_SCHEMA_CONTENT_EMPTY) { /* * SPEC (1.4.3.2.1) "The {content type} of the {base type * definition} must be empty. * PASS */ } else { /* * SPEC (1.4.3.2.2) "All of the following must be true:" */ if ((type->contentType != base->contentType) || ((type->contentType != XML_SCHEMA_CONTENT_MIXED) && (type->contentType != XML_SCHEMA_CONTENT_ELEMENTS))) { /* * SPEC (1.4.3.2.2.1) "Both {content type}s must be mixed * or both must be element-only." */ xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_COS_CT_EXTENDS_1_1, WXS_BASIC_CAST type, NULL, "The content type of both, the type and its base " "type, must either 'mixed' or 'element-only'", NULL); return (XML_SCHEMAP_COS_CT_EXTENDS_1_1); } /* * URGENT TODO SPEC (1.4.3.2.2.2) "The particle of the * complex type definition must be a `valid extension` * of the {base type definition}'s particle, as defined * in Particle Valid (Extension) ($3.9.6)." * * NOTE that we won't check "Particle Valid (Extension)", * since it is ensured by the derivation process in * xmlSchemaTypeFixup(). We need to implement this when heading * for a construction API * TODO: !! This is needed to be checked if redefining a type !! */ } /* * URGENT TODO (1.5) */ } } else { /* * SPEC (2) "If the {base type definition} is a simple type definition, * then all of the following must be true:" */ if (type->contentTypeDef != base) { /* * SPEC (2.1) "The {content type} must be the same simple type * definition." */ xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_COS_CT_EXTENDS_1_1, WXS_BASIC_CAST type, NULL, "The content type must be the simple base type", NULL); return (XML_SCHEMAP_COS_CT_EXTENDS_1_1); } if (base->flags & XML_SCHEMAS_TYPE_FINAL_EXTENSION) { /* * SPEC (2.2) "The {final} of the {base type definition} must not * contain extension" * NOTE that this is the same as (1.1). */ xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_COS_CT_EXTENDS_1_1, WXS_BASIC_CAST type, NULL, "The 'final' of the base type definition " "contains 'extension'", NULL); return (XML_SCHEMAP_COS_CT_EXTENDS_1_1); } } return (0); } /** * xmlSchemaCheckDerivationOKRestriction: * @ctxt: the schema parser context * @type: the complex type definition * * (3.4.6) Constraints on Complex Type Definition Schema Components * Schema Component Constraint: * Derivation Valid (Restriction, Complex) (derivation-ok-restriction) * * STATUS: * missing: * (5.4.2) ??? * * ATTENTION: * In XML Schema 1.1 this will be: * Validation Rule: Checking complex type subsumption * * Returns 0 if the constraints are satisfied, a positive * error code if not and -1 if an internal error occurred. */ static int xmlSchemaCheckDerivationOKRestriction(xmlSchemaParserCtxtPtr ctxt, xmlSchemaTypePtr type) { xmlSchemaTypePtr base; /* * TODO: Correct the error code; XML_SCHEMAP_DERIVATION_OK_RESTRICTION_1 is used * temporarily only. */ base = type->baseType; if (! WXS_IS_COMPLEX(base)) { xmlSchemaCustomErr(ACTXT_CAST ctxt, XML_SCHEMAP_DERIVATION_OK_RESTRICTION_1, type->node, WXS_BASIC_CAST type, "The base type must be a complex type", NULL, NULL); return(ctxt->err); } if (base->flags & XML_SCHEMAS_TYPE_FINAL_RESTRICTION) { /* * SPEC (1) "The {base type definition} must be a complex type * definition whose {final} does not contain restriction." */ xmlSchemaCustomErr(ACTXT_CAST ctxt, XML_SCHEMAP_DERIVATION_OK_RESTRICTION_1, type->node, WXS_BASIC_CAST type, "The 'final' of the base type definition " "contains 'restriction'", NULL, NULL); return (ctxt->err); } /* * SPEC (2), (3) and (4) * Those are handled in a separate function, since the * same constraints are needed for redefinition of * attribute groups as well. */ if (xmlSchemaCheckDerivationOKRestriction2to4(ctxt, XML_SCHEMA_ACTION_DERIVE, WXS_BASIC_CAST type, WXS_BASIC_CAST base, type->attrUses, base->attrUses, type->attributeWildcard, base->attributeWildcard) == -1) { return(-1); } /* * SPEC (5) "One of the following must be true:" */ if (base->builtInType == XML_SCHEMAS_ANYTYPE) { /* * SPEC (5.1) "The {base type definition} must be the * `ur-type definition`." * PASS */ } else if ((type->contentType == XML_SCHEMA_CONTENT_SIMPLE) || (type->contentType == XML_SCHEMA_CONTENT_BASIC)) { /* * SPEC (5.2.1) "The {content type} of the complex type definition * must be a simple type definition" * * SPEC (5.2.2) "One of the following must be true:" */ if ((base->contentType == XML_SCHEMA_CONTENT_SIMPLE) || (base->contentType == XML_SCHEMA_CONTENT_BASIC)) { int err; /* * SPEC (5.2.2.1) "The {content type} of the {base type * definition} must be a simple type definition from which * the {content type} is validly derived given the empty * set as defined in Type Derivation OK (Simple) ($3.14.6)." * * ATTENTION TODO: This seems not needed if the type implicitly * derived from the base type. * */ err = xmlSchemaCheckCOSSTDerivedOK(ACTXT_CAST ctxt, type->contentTypeDef, base->contentTypeDef, 0); if (err != 0) { xmlChar *strA = NULL, *strB = NULL; if (err == -1) return(-1); xmlSchemaCustomErr(ACTXT_CAST ctxt, XML_SCHEMAP_DERIVATION_OK_RESTRICTION_1, NULL, WXS_BASIC_CAST type, "The {content type} %s is not validly derived from the " "base type's {content type} %s", xmlSchemaGetComponentDesignation(&strA, type->contentTypeDef), xmlSchemaGetComponentDesignation(&strB, base->contentTypeDef)); FREE_AND_NULL(strA); FREE_AND_NULL(strB); return(ctxt->err); } } else if ((base->contentType == XML_SCHEMA_CONTENT_MIXED) && (xmlSchemaIsParticleEmptiable( (xmlSchemaParticlePtr) base->subtypes))) { /* * SPEC (5.2.2.2) "The {base type definition} must be mixed * and have a particle which is `emptiable` as defined in * Particle Emptiable ($3.9.6)." * PASS */ } else { xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_DERIVATION_OK_RESTRICTION_1, WXS_BASIC_CAST type, NULL, "The content type of the base type must be either " "a simple type or 'mixed' and an emptiable particle", NULL); return (ctxt->err); } } else if (type->contentType == XML_SCHEMA_CONTENT_EMPTY) { /* * SPEC (5.3.1) "The {content type} of the complex type itself must * be empty" */ if (base->contentType == XML_SCHEMA_CONTENT_EMPTY) { /* * SPEC (5.3.2.1) "The {content type} of the {base type * definition} must also be empty." * PASS */ } else if (((base->contentType == XML_SCHEMA_CONTENT_ELEMENTS) || (base->contentType == XML_SCHEMA_CONTENT_MIXED)) && xmlSchemaIsParticleEmptiable( (xmlSchemaParticlePtr) base->subtypes)) { /* * SPEC (5.3.2.2) "The {content type} of the {base type * definition} must be elementOnly or mixed and have a particle * which is `emptiable` as defined in Particle Emptiable ($3.9.6)." * PASS */ } else { xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_DERIVATION_OK_RESTRICTION_1, WXS_BASIC_CAST type, NULL, "The content type of the base type must be either " "empty or 'mixed' (or 'elements-only') and an emptiable " "particle", NULL); return (ctxt->err); } } else if ((type->contentType == XML_SCHEMA_CONTENT_ELEMENTS) || WXS_HAS_MIXED_CONTENT(type)) { /* * SPEC (5.4.1.1) "The {content type} of the complex type definition * itself must be element-only" */ if (WXS_HAS_MIXED_CONTENT(type) && (! WXS_HAS_MIXED_CONTENT(base))) { /* * SPEC (5.4.1.2) "The {content type} of the complex type * definition itself and of the {base type definition} must be * mixed" */ xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_DERIVATION_OK_RESTRICTION_1, WXS_BASIC_CAST type, NULL, "If the content type is 'mixed', then the content type of the " "base type must also be 'mixed'", NULL); return (ctxt->err); } /* * SPEC (5.4.2) "The particle of the complex type definition itself * must be a `valid restriction` of the particle of the {content * type} of the {base type definition} as defined in Particle Valid * (Restriction) ($3.9.6). * * URGENT TODO: (5.4.2) */ } else { xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_DERIVATION_OK_RESTRICTION_1, WXS_BASIC_CAST type, NULL, "The type is not a valid restriction of its base type", NULL); return (ctxt->err); } return (0); } /** * xmlSchemaCheckCTComponent: * @ctxt: the schema parser context * @type: the complex type definition * * (3.4.6) Constraints on Complex Type Definition Schema Components * * Returns 0 if the constraints are satisfied, a positive * error code if not and -1 if an internal error occurred. */ static int xmlSchemaCheckCTComponent(xmlSchemaParserCtxtPtr ctxt, xmlSchemaTypePtr type) { int ret; /* * Complex Type Definition Properties Correct */ ret = xmlSchemaCheckCTPropsCorrect(ctxt, type); if (ret != 0) return (ret); if (WXS_IS_EXTENSION(type)) ret = xmlSchemaCheckCOSCTExtends(ctxt, type); else ret = xmlSchemaCheckDerivationOKRestriction(ctxt, type); return (ret); } /** * xmlSchemaCheckSRCCT: * @ctxt: the schema parser context * @type: the complex type definition * * (3.4.3) Constraints on XML Representations of Complex Type Definitions: * Schema Representation Constraint: * Complex Type Definition Representation OK (src-ct) * * Returns 0 if the constraints are satisfied, a positive * error code if not and -1 if an internal error occurred. */ static int xmlSchemaCheckSRCCT(xmlSchemaParserCtxtPtr ctxt, xmlSchemaTypePtr type) { xmlSchemaTypePtr base; int ret = 0; /* * TODO: Adjust the error codes here, as I used * XML_SCHEMAP_SRC_CT_1 only yet. */ base = type->baseType; if (! WXS_HAS_SIMPLE_CONTENT(type)) { /* * 1 If the <complexContent> alternative is chosen, the type definition * `resolved` to by the `actual value` of the base [attribute] * must be a complex type definition; */ if (! WXS_IS_COMPLEX(base)) { xmlChar *str = NULL; xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_SRC_CT_1, WXS_BASIC_CAST type, type->node, "If using <complexContent>, the base type is expected to be " "a complex type. The base type '%s' is a simple type", xmlSchemaFormatQName(&str, base->targetNamespace, base->name)); FREE_AND_NULL(str) return (XML_SCHEMAP_SRC_CT_1); } } else { /* * SPEC * 2 If the <simpleContent> alternative is chosen, all of the * following must be true: * 2.1 The type definition `resolved` to by the `actual value` of the * base [attribute] must be one of the following: */ if (WXS_IS_SIMPLE(base)) { if (WXS_IS_EXTENSION(type) == 0) { xmlChar *str = NULL; /* * 2.1.3 only if the <extension> alternative is also * chosen, a simple type definition. */ /* TODO: Change error code to ..._SRC_CT_2_1_3. */ xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_SRC_CT_1, WXS_BASIC_CAST type, NULL, "If using <simpleContent> and <restriction>, the base " "type must be a complex type. The base type '%s' is " "a simple type", xmlSchemaFormatQName(&str, base->targetNamespace, base->name)); FREE_AND_NULL(str) return (XML_SCHEMAP_SRC_CT_1); } } else { /* Base type is a complex type. */ if ((base->contentType == XML_SCHEMA_CONTENT_SIMPLE) || (base->contentType == XML_SCHEMA_CONTENT_BASIC)) { /* * 2.1.1 a complex type definition whose {content type} is a * simple type definition; * PASS */ if (base->contentTypeDef == NULL) { xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_INTERNAL, WXS_BASIC_CAST type, NULL, "Internal error: xmlSchemaCheckSRCCT, " "'%s', base type has no content type", type->name); return (-1); } } else if ((base->contentType == XML_SCHEMA_CONTENT_MIXED) && (WXS_IS_RESTRICTION(type))) { /* * 2.1.2 only if the <restriction> alternative is also * chosen, a complex type definition whose {content type} * is mixed and a particle emptiable. */ if (! xmlSchemaIsParticleEmptiable( (xmlSchemaParticlePtr) base->subtypes)) { ret = XML_SCHEMAP_SRC_CT_1; } else /* * Attention: at this point the <simpleType> child is in * ->contentTypeDef (put there during parsing). */ if (type->contentTypeDef == NULL) { xmlChar *str = NULL; /* * 2.2 If clause 2.1.2 above is satisfied, then there * must be a <simpleType> among the [children] of * <restriction>. */ /* TODO: Change error code to ..._SRC_CT_2_2. */ xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_SRC_CT_1, WXS_BASIC_CAST type, NULL, "A <simpleType> is expected among the children " "of <restriction>, if <simpleContent> is used and " "the base type '%s' is a complex type", xmlSchemaFormatQName(&str, base->targetNamespace, base->name)); FREE_AND_NULL(str) return (XML_SCHEMAP_SRC_CT_1); } } else { ret = XML_SCHEMAP_SRC_CT_1; } } if (ret > 0) { xmlChar *str = NULL; if (WXS_IS_RESTRICTION(type)) { xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_SRC_CT_1, WXS_BASIC_CAST type, NULL, "If <simpleContent> and <restriction> is used, the " "base type must be a simple type or a complex type with " "mixed content and particle emptiable. The base type " "'%s' is none of those", xmlSchemaFormatQName(&str, base->targetNamespace, base->name)); } else { xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_SRC_CT_1, WXS_BASIC_CAST type, NULL, "If <simpleContent> and <extension> is used, the " "base type must be a simple type. The base type '%s' " "is a complex type", xmlSchemaFormatQName(&str, base->targetNamespace, base->name)); } FREE_AND_NULL(str) } } /* * SPEC (3) "The corresponding complex type definition component must * satisfy the conditions set out in Constraints on Complex Type * Definition Schema Components ($3.4.6);" * NOTE (3) will be done in xmlSchemaTypeFixup(). */ /* * SPEC (4) If clause 2.2.1 or clause 2.2.2 in the correspondence specification * above for {attribute wildcard} is satisfied, the intensional * intersection must be expressible, as defined in Attribute Wildcard * Intersection ($3.10.6). * NOTE (4) is done in xmlSchemaFixupTypeAttributeUses(). */ return (ret); } #ifdef ENABLE_PARTICLE_RESTRICTION /** * xmlSchemaCheckParticleRangeOK: * @ctxt: the schema parser context * @type: the complex type definition * * (3.9.6) Constraints on Particle Schema Components * Schema Component Constraint: * Occurrence Range OK (range-ok) * * STATUS: complete * * Returns 0 if the constraints are satisfied, a positive * error code if not and -1 if an internal error occurred. */ static int xmlSchemaCheckParticleRangeOK(int rmin, int rmax, int bmin, int bmax) { if (rmin < bmin) return (1); if ((bmax != UNBOUNDED) && (rmax > bmax)) return (1); return (0); } /** * xmlSchemaCheckRCaseNameAndTypeOK: * @ctxt: the schema parser context * @r: the restricting element declaration particle * @b: the base element declaration particle * * (3.9.6) Constraints on Particle Schema Components * Schema Component Constraint: * Particle Restriction OK (Elt:Elt -- NameAndTypeOK) * (rcase-NameAndTypeOK) * * STATUS: * MISSING (3.2.3) * CLARIFY: (3.2.2) * * Returns 0 if the constraints are satisfied, a positive * error code if not and -1 if an internal error occurred. */ static int xmlSchemaCheckRCaseNameAndTypeOK(xmlSchemaParserCtxtPtr ctxt, xmlSchemaParticlePtr r, xmlSchemaParticlePtr b) { xmlSchemaElementPtr elemR, elemB; /* TODO: Error codes (rcase-NameAndTypeOK). */ elemR = (xmlSchemaElementPtr) r->children; elemB = (xmlSchemaElementPtr) b->children; /* * SPEC (1) "The declarations' {name}s and {target namespace}s are * the same." */ if ((elemR != elemB) && ((! xmlStrEqual(elemR->name, elemB->name)) || (! xmlStrEqual(elemR->targetNamespace, elemB->targetNamespace)))) return (1); /* * SPEC (2) "R's occurrence range is a valid restriction of B's * occurrence range as defined by Occurrence Range OK ($3.9.6)." */ if (xmlSchemaCheckParticleRangeOK(r->minOccurs, r->maxOccurs, b->minOccurs, b->maxOccurs) != 0) return (1); /* * SPEC (3.1) "Both B's declaration's {scope} and R's declaration's * {scope} are global." */ if (elemR == elemB) return (0); /* * SPEC (3.2.1) "Either B's {nillable} is true or R's {nillable} is false." */ if (((elemB->flags & XML_SCHEMAS_ELEM_NILLABLE) == 0) && (elemR->flags & XML_SCHEMAS_ELEM_NILLABLE)) return (1); /* * SPEC (3.2.2) "either B's declaration's {value constraint} is absent, * or is not fixed, or R's declaration's {value constraint} is fixed * with the same value." */ if ((elemB->value != NULL) && (elemB->flags & XML_SCHEMAS_ELEM_FIXED) && ((elemR->value == NULL) || ((elemR->flags & XML_SCHEMAS_ELEM_FIXED) == 0) || /* TODO: Equality of the initial value or normalized or canonical? */ (! xmlStrEqual(elemR->value, elemB->value)))) return (1); /* * TODO: SPEC (3.2.3) "R's declaration's {identity-constraint * definitions} is a subset of B's declaration's {identity-constraint * definitions}, if any." */ if (elemB->idcs != NULL) { /* TODO */ } /* * SPEC (3.2.4) "R's declaration's {disallowed substitutions} is a * superset of B's declaration's {disallowed substitutions}." */ if (((elemB->flags & XML_SCHEMAS_ELEM_BLOCK_EXTENSION) && ((elemR->flags & XML_SCHEMAS_ELEM_BLOCK_EXTENSION) == 0)) || ((elemB->flags & XML_SCHEMAS_ELEM_BLOCK_RESTRICTION) && ((elemR->flags & XML_SCHEMAS_ELEM_BLOCK_RESTRICTION) == 0)) || ((elemB->flags & XML_SCHEMAS_ELEM_BLOCK_SUBSTITUTION) && ((elemR->flags & XML_SCHEMAS_ELEM_BLOCK_SUBSTITUTION) == 0))) return (1); /* * SPEC (3.2.5) "R's {type definition} is validly derived given * {extension, list, union} from B's {type definition}" * * BADSPEC TODO: What's the point of adding "list" and "union" to the * set, if the corresponding constraints handle "restriction" and * "extension" only? * */ { int set = 0; set |= SUBSET_EXTENSION; set |= SUBSET_LIST; set |= SUBSET_UNION; if (xmlSchemaCheckCOSDerivedOK(ACTXT_CAST ctxt, elemR->subtypes, elemB->subtypes, set) != 0) return (1); } return (0); } /** * xmlSchemaCheckRCaseNSCompat: * @ctxt: the schema parser context * @r: the restricting element declaration particle * @b: the base wildcard particle * * (3.9.6) Constraints on Particle Schema Components * Schema Component Constraint: * Particle Derivation OK (Elt:Any -- NSCompat) * (rcase-NSCompat) * * STATUS: complete * * Returns 0 if the constraints are satisfied, a positive * error code if not and -1 if an internal error occurred. */ static int xmlSchemaCheckRCaseNSCompat(xmlSchemaParserCtxtPtr ctxt, xmlSchemaParticlePtr r, xmlSchemaParticlePtr b) { /* TODO:Error codes (rcase-NSCompat). */ /* * SPEC "For an element declaration particle to be a `valid restriction` * of a wildcard particle all of the following must be true:" * * SPEC (1) "The element declaration's {target namespace} is `valid` * with respect to the wildcard's {namespace constraint} as defined by * Wildcard allows Namespace Name ($3.10.4)." */ if (xmlSchemaCheckCVCWildcardNamespace((xmlSchemaWildcardPtr) b->children, ((xmlSchemaElementPtr) r->children)->targetNamespace) != 0) return (1); /* * SPEC (2) "R's occurrence range is a valid restriction of B's * occurrence range as defined by Occurrence Range OK ($3.9.6)." */ if (xmlSchemaCheckParticleRangeOK(r->minOccurs, r->maxOccurs, b->minOccurs, b->maxOccurs) != 0) return (1); return (0); } /** * xmlSchemaCheckRCaseRecurseAsIfGroup: * @ctxt: the schema parser context * @r: the restricting element declaration particle * @b: the base model group particle * * (3.9.6) Constraints on Particle Schema Components * Schema Component Constraint: * Particle Derivation OK (Elt:All/Choice/Sequence -- RecurseAsIfGroup) * (rcase-RecurseAsIfGroup) * * STATUS: TODO * * Returns 0 if the constraints are satisfied, a positive * error code if not and -1 if an internal error occurred. */ static int xmlSchemaCheckRCaseRecurseAsIfGroup(xmlSchemaParserCtxtPtr ctxt, xmlSchemaParticlePtr r, xmlSchemaParticlePtr b) { /* TODO: Error codes (rcase-RecurseAsIfGroup). */ TODO return (0); } /** * xmlSchemaCheckRCaseNSSubset: * @ctxt: the schema parser context * @r: the restricting wildcard particle * @b: the base wildcard particle * * (3.9.6) Constraints on Particle Schema Components * Schema Component Constraint: * Particle Derivation OK (Any:Any -- NSSubset) * (rcase-NSSubset) * * STATUS: complete * * Returns 0 if the constraints are satisfied, a positive * error code if not and -1 if an internal error occurred. */ static int xmlSchemaCheckRCaseNSSubset(xmlSchemaParserCtxtPtr ctxt, xmlSchemaParticlePtr r, xmlSchemaParticlePtr b, int isAnyTypeBase) { /* TODO: Error codes (rcase-NSSubset). */ /* * SPEC (1) "R's occurrence range is a valid restriction of B's * occurrence range as defined by Occurrence Range OK ($3.9.6)." */ if (xmlSchemaCheckParticleRangeOK(r->minOccurs, r->maxOccurs, b->minOccurs, b->maxOccurs)) return (1); /* * SPEC (2) "R's {namespace constraint} must be an intensional subset * of B's {namespace constraint} as defined by Wildcard Subset ($3.10.6)." */ if (xmlSchemaCheckCOSNSSubset((xmlSchemaWildcardPtr) r->children, (xmlSchemaWildcardPtr) b->children)) return (1); /* * SPEC (3) "Unless B is the content model wildcard of the `ur-type * definition`, R's {process contents} must be identical to or stronger * than B's {process contents}, where strict is stronger than lax is * stronger than skip." */ if (! isAnyTypeBase) { if ( ((xmlSchemaWildcardPtr) r->children)->processContents < ((xmlSchemaWildcardPtr) b->children)->processContents) return (1); } return (0); } /** * xmlSchemaCheckCOSParticleRestrict: * @ctxt: the schema parser context * @type: the complex type definition * * (3.9.6) Constraints on Particle Schema Components * Schema Component Constraint: * Particle Valid (Restriction) (cos-particle-restrict) * * STATUS: TODO * * Returns 0 if the constraints are satisfied, a positive * error code if not and -1 if an internal error occurred. */ static int xmlSchemaCheckCOSParticleRestrict(xmlSchemaParserCtxtPtr ctxt, xmlSchemaParticlePtr r, xmlSchemaParticlePtr b) { int ret = 0; /*part = WXS_TYPE_PARTICLE(type); basePart = WXS_TYPE_PARTICLE(base); */ TODO /* * SPEC (1) "They are the same particle." */ if (r == b) return (0); return (0); } #if 0 /** * xmlSchemaCheckRCaseNSRecurseCheckCardinality: * @ctxt: the schema parser context * @r: the model group particle * @b: the base wildcard particle * * (3.9.6) Constraints on Particle Schema Components * Schema Component Constraint: * Particle Derivation OK (All/Choice/Sequence:Any -- * NSRecurseCheckCardinality) * (rcase-NSRecurseCheckCardinality) * * STATUS: TODO: subst-groups * * Returns 0 if the constraints are satisfied, a positive * error code if not and -1 if an internal error occurred. */ static int xmlSchemaCheckRCaseNSRecurseCheckCardinality(xmlSchemaParserCtxtPtr ctxt, xmlSchemaParticlePtr r, xmlSchemaParticlePtr b) { xmlSchemaParticlePtr part; /* TODO: Error codes (rcase-NSRecurseCheckCardinality). */ if ((r->children == NULL) || (r->children->children == NULL)) return (-1); /* * SPEC "For a group particle to be a `valid restriction` of a * wildcard particle..." * * SPEC (1) "Every member of the {particles} of the group is a `valid * restriction` of the wildcard as defined by * Particle Valid (Restriction) ($3.9.6)." */ part = (xmlSchemaParticlePtr) r->children->children; do { if (xmlSchemaCheckCOSParticleRestrict(ctxt, part, b)) return (1); part = (xmlSchemaParticlePtr) part->next; } while (part != NULL); /* * SPEC (2) "The effective total range of the group [...] is a * valid restriction of B's occurrence range as defined by * Occurrence Range OK ($3.9.6)." */ if (xmlSchemaCheckParticleRangeOK( xmlSchemaGetParticleTotalRangeMin(r), xmlSchemaGetParticleTotalRangeMax(r), b->minOccurs, b->maxOccurs) != 0) return (1); return (0); } #endif /** * xmlSchemaCheckRCaseRecurse: * @ctxt: the schema parser context * @r: the <all> or <sequence> model group particle * @b: the base <all> or <sequence> model group particle * * (3.9.6) Constraints on Particle Schema Components * Schema Component Constraint: * Particle Derivation OK (All:All,Sequence:Sequence -- Recurse) * (rcase-Recurse) * * STATUS: ? * TODO: subst-groups * * Returns 0 if the constraints are satisfied, a positive * error code if not and -1 if an internal error occurred. */ static int xmlSchemaCheckRCaseRecurse(xmlSchemaParserCtxtPtr ctxt, xmlSchemaParticlePtr r, xmlSchemaParticlePtr b) { /* xmlSchemaParticlePtr part; */ /* TODO: Error codes (rcase-Recurse). */ if ((r->children == NULL) || (b->children == NULL) || (r->children->type != b->children->type)) return (-1); /* * SPEC "For an all or sequence group particle to be a `valid * restriction` of another group particle with the same {compositor}..." * * SPEC (1) "R's occurrence range is a valid restriction of B's * occurrence range as defined by Occurrence Range OK ($3.9.6)." */ if (xmlSchemaCheckParticleRangeOK(r->minOccurs, r->maxOccurs, b->minOccurs, b->maxOccurs)) return (1); return (0); } #endif #define FACET_RESTR_MUTUAL_ERR(fac1, fac2) \ xmlSchemaPCustomErrExt(pctxt, \ XML_SCHEMAP_INVALID_FACET_VALUE, \ WXS_BASIC_CAST fac1, fac1->node, \ "It is an error for both '%s' and '%s' to be specified on the "\ "same type definition", \ BAD_CAST xmlSchemaFacetTypeToString(fac1->type), \ BAD_CAST xmlSchemaFacetTypeToString(fac2->type), NULL); #define FACET_RESTR_ERR(fac1, msg) \ xmlSchemaPCustomErr(pctxt, \ XML_SCHEMAP_INVALID_FACET_VALUE, \ WXS_BASIC_CAST fac1, fac1->node, \ msg, NULL); #define FACET_RESTR_FIXED_ERR(fac) \ xmlSchemaPCustomErr(pctxt, \ XML_SCHEMAP_INVALID_FACET_VALUE, \ WXS_BASIC_CAST fac, fac->node, \ "The base type's facet is 'fixed', thus the value must not " \ "differ", NULL); static void xmlSchemaDeriveFacetErr(xmlSchemaParserCtxtPtr pctxt, xmlSchemaFacetPtr facet1, xmlSchemaFacetPtr facet2, int lessGreater, int orEqual, int ofBase) { xmlChar *msg = NULL; msg = xmlStrdup(BAD_CAST "'"); msg = xmlStrcat(msg, xmlSchemaFacetTypeToString(facet1->type)); msg = xmlStrcat(msg, BAD_CAST "' has to be"); if (lessGreater == 0) msg = xmlStrcat(msg, BAD_CAST " equal to"); if (lessGreater == 1) msg = xmlStrcat(msg, BAD_CAST " greater than"); else msg = xmlStrcat(msg, BAD_CAST " less than"); if (orEqual) msg = xmlStrcat(msg, BAD_CAST " or equal to"); msg = xmlStrcat(msg, BAD_CAST " '"); msg = xmlStrcat(msg, xmlSchemaFacetTypeToString(facet2->type)); if (ofBase) msg = xmlStrcat(msg, BAD_CAST "' of the base type"); else msg = xmlStrcat(msg, BAD_CAST "'"); xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_INVALID_FACET_VALUE, WXS_BASIC_CAST facet1, NULL, (const char *) msg, NULL); if (msg != NULL) xmlFree(msg); } /* * xmlSchemaDeriveAndValidateFacets: * * Schema Component Constraint: Simple Type Restriction (Facets) * (st-restrict-facets) */ static int xmlSchemaDeriveAndValidateFacets(xmlSchemaParserCtxtPtr pctxt, xmlSchemaTypePtr type) { xmlSchemaTypePtr base = type->baseType; xmlSchemaFacetLinkPtr link, cur, last = NULL; xmlSchemaFacetPtr facet, bfacet, flength = NULL, ftotdig = NULL, ffracdig = NULL, fmaxlen = NULL, fminlen = NULL, /* facets of the current type */ fmininc = NULL, fmaxinc = NULL, fminexc = NULL, fmaxexc = NULL, bflength = NULL, bftotdig = NULL, bffracdig = NULL, bfmaxlen = NULL, bfminlen = NULL, /* facets of the base type */ bfmininc = NULL, bfmaxinc = NULL, bfminexc = NULL, bfmaxexc = NULL; int res; /* err = 0, fixedErr; */ /* * SPEC st-restrict-facets 1: * "The {variety} of R is the same as that of B." */ /* * SPEC st-restrict-facets 2: * "If {variety} is atomic, the {primitive type definition} * of R is the same as that of B." * * NOTE: we leave 1 & 2 out for now, since this will be * satisfied by the derivation process. * CONSTRUCTION TODO: Maybe needed if using a construction API. */ /* * SPEC st-restrict-facets 3: * "The {facets} of R are the union of S and the {facets} * of B, eliminating duplicates. To eliminate duplicates, * when a facet of the same kind occurs in both S and the * {facets} of B, the one in the {facets} of B is not * included, with the exception of enumeration and pattern * facets, for which multiple occurrences with distinct values * are allowed." */ if ((type->facetSet == NULL) && (base->facetSet == NULL)) return (0); last = type->facetSet; if (last != NULL) while (last->next != NULL) last = last->next; for (cur = type->facetSet; cur != NULL; cur = cur->next) { facet = cur->facet; switch (facet->type) { case XML_SCHEMA_FACET_LENGTH: flength = facet; break; case XML_SCHEMA_FACET_MINLENGTH: fminlen = facet; break; case XML_SCHEMA_FACET_MININCLUSIVE: fmininc = facet; break; case XML_SCHEMA_FACET_MINEXCLUSIVE: fminexc = facet; break; case XML_SCHEMA_FACET_MAXLENGTH: fmaxlen = facet; break; case XML_SCHEMA_FACET_MAXINCLUSIVE: fmaxinc = facet; break; case XML_SCHEMA_FACET_MAXEXCLUSIVE: fmaxexc = facet; break; case XML_SCHEMA_FACET_TOTALDIGITS: ftotdig = facet; break; case XML_SCHEMA_FACET_FRACTIONDIGITS: ffracdig = facet; break; default: break; } } for (cur = base->facetSet; cur != NULL; cur = cur->next) { facet = cur->facet; switch (facet->type) { case XML_SCHEMA_FACET_LENGTH: bflength = facet; break; case XML_SCHEMA_FACET_MINLENGTH: bfminlen = facet; break; case XML_SCHEMA_FACET_MININCLUSIVE: bfmininc = facet; break; case XML_SCHEMA_FACET_MINEXCLUSIVE: bfminexc = facet; break; case XML_SCHEMA_FACET_MAXLENGTH: bfmaxlen = facet; break; case XML_SCHEMA_FACET_MAXINCLUSIVE: bfmaxinc = facet; break; case XML_SCHEMA_FACET_MAXEXCLUSIVE: bfmaxexc = facet; break; case XML_SCHEMA_FACET_TOTALDIGITS: bftotdig = facet; break; case XML_SCHEMA_FACET_FRACTIONDIGITS: bffracdig = facet; break; default: break; } } /* * length and minLength or maxLength (2.2) + (3.2) */ if (flength && (fminlen || fmaxlen)) { FACET_RESTR_ERR(flength, "It is an error for both 'length' and " "either of 'minLength' or 'maxLength' to be specified on " "the same type definition") } /* * Mutual exclusions in the same derivation step. */ if ((fmaxinc) && (fmaxexc)) { /* * SCC "maxInclusive and maxExclusive" */ FACET_RESTR_MUTUAL_ERR(fmaxinc, fmaxexc) } if ((fmininc) && (fminexc)) { /* * SCC "minInclusive and minExclusive" */ FACET_RESTR_MUTUAL_ERR(fmininc, fminexc) } if (flength && bflength) { /* * SCC "length valid restriction" * The values have to be equal. */ res = xmlSchemaCompareValues(flength->val, bflength->val); if (res == -2) goto internal_error; if (res != 0) xmlSchemaDeriveFacetErr(pctxt, flength, bflength, 0, 0, 1); if ((res != 0) && (bflength->fixed)) { FACET_RESTR_FIXED_ERR(flength) } } if (fminlen && bfminlen) { /* * SCC "minLength valid restriction" * minLength >= BASE minLength */ res = xmlSchemaCompareValues(fminlen->val, bfminlen->val); if (res == -2) goto internal_error; if (res == -1) xmlSchemaDeriveFacetErr(pctxt, fminlen, bfminlen, 1, 1, 1); if ((res != 0) && (bfminlen->fixed)) { FACET_RESTR_FIXED_ERR(fminlen) } } if (fmaxlen && bfmaxlen) { /* * SCC "maxLength valid restriction" * maxLength <= BASE minLength */ res = xmlSchemaCompareValues(fmaxlen->val, bfmaxlen->val); if (res == -2) goto internal_error; if (res == 1) xmlSchemaDeriveFacetErr(pctxt, fmaxlen, bfmaxlen, -1, 1, 1); if ((res != 0) && (bfmaxlen->fixed)) { FACET_RESTR_FIXED_ERR(fmaxlen) } } /* * SCC "length and minLength or maxLength" */ if (! flength) flength = bflength; if (flength) { if (! fminlen) fminlen = bfminlen; if (fminlen) { /* (1.1) length >= minLength */ res = xmlSchemaCompareValues(flength->val, fminlen->val); if (res == -2) goto internal_error; if (res == -1) xmlSchemaDeriveFacetErr(pctxt, flength, fminlen, 1, 1, 0); } if (! fmaxlen) fmaxlen = bfmaxlen; if (fmaxlen) { /* (2.1) length <= maxLength */ res = xmlSchemaCompareValues(flength->val, fmaxlen->val); if (res == -2) goto internal_error; if (res == 1) xmlSchemaDeriveFacetErr(pctxt, flength, fmaxlen, -1, 1, 0); } } if (fmaxinc) { /* * "maxInclusive" */ if (fmininc) { /* SCC "maxInclusive >= minInclusive" */ res = xmlSchemaCompareValues(fmaxinc->val, fmininc->val); if (res == -2) goto internal_error; if (res == -1) { xmlSchemaDeriveFacetErr(pctxt, fmaxinc, fmininc, 1, 1, 0); } } /* * SCC "maxInclusive valid restriction" */ if (bfmaxinc) { /* maxInclusive <= BASE maxInclusive */ res = xmlSchemaCompareValues(fmaxinc->val, bfmaxinc->val); if (res == -2) goto internal_error; if (res == 1) xmlSchemaDeriveFacetErr(pctxt, fmaxinc, bfmaxinc, -1, 1, 1); if ((res != 0) && (bfmaxinc->fixed)) { FACET_RESTR_FIXED_ERR(fmaxinc) } } if (bfmaxexc) { /* maxInclusive < BASE maxExclusive */ res = xmlSchemaCompareValues(fmaxinc->val, bfmaxexc->val); if (res == -2) goto internal_error; if (res != -1) { xmlSchemaDeriveFacetErr(pctxt, fmaxinc, bfmaxexc, -1, 0, 1); } } if (bfmininc) { /* maxInclusive >= BASE minInclusive */ res = xmlSchemaCompareValues(fmaxinc->val, bfmininc->val); if (res == -2) goto internal_error; if (res == -1) { xmlSchemaDeriveFacetErr(pctxt, fmaxinc, bfmininc, 1, 1, 1); } } if (bfminexc) { /* maxInclusive > BASE minExclusive */ res = xmlSchemaCompareValues(fmaxinc->val, bfminexc->val); if (res == -2) goto internal_error; if (res != 1) { xmlSchemaDeriveFacetErr(pctxt, fmaxinc, bfminexc, 1, 0, 1); } } } if (fmaxexc) { /* * "maxExclusive >= minExclusive" */ if (fminexc) { res = xmlSchemaCompareValues(fmaxexc->val, fminexc->val); if (res == -2) goto internal_error; if (res == -1) { xmlSchemaDeriveFacetErr(pctxt, fmaxexc, fminexc, 1, 1, 0); } } /* * "maxExclusive valid restriction" */ if (bfmaxexc) { /* maxExclusive <= BASE maxExclusive */ res = xmlSchemaCompareValues(fmaxexc->val, bfmaxexc->val); if (res == -2) goto internal_error; if (res == 1) { xmlSchemaDeriveFacetErr(pctxt, fmaxexc, bfmaxexc, -1, 1, 1); } if ((res != 0) && (bfmaxexc->fixed)) { FACET_RESTR_FIXED_ERR(fmaxexc) } } if (bfmaxinc) { /* maxExclusive <= BASE maxInclusive */ res = xmlSchemaCompareValues(fmaxexc->val, bfmaxinc->val); if (res == -2) goto internal_error; if (res == 1) { xmlSchemaDeriveFacetErr(pctxt, fmaxexc, bfmaxinc, -1, 1, 1); } } if (bfmininc) { /* maxExclusive > BASE minInclusive */ res = xmlSchemaCompareValues(fmaxexc->val, bfmininc->val); if (res == -2) goto internal_error; if (res != 1) { xmlSchemaDeriveFacetErr(pctxt, fmaxexc, bfmininc, 1, 0, 1); } } if (bfminexc) { /* maxExclusive > BASE minExclusive */ res = xmlSchemaCompareValues(fmaxexc->val, bfminexc->val); if (res == -2) goto internal_error; if (res != 1) { xmlSchemaDeriveFacetErr(pctxt, fmaxexc, bfminexc, 1, 0, 1); } } } if (fminexc) { /* * "minExclusive < maxInclusive" */ if (fmaxinc) { res = xmlSchemaCompareValues(fminexc->val, fmaxinc->val); if (res == -2) goto internal_error; if (res != -1) { xmlSchemaDeriveFacetErr(pctxt, fminexc, fmaxinc, -1, 0, 0); } } /* * "minExclusive valid restriction" */ if (bfminexc) { /* minExclusive >= BASE minExclusive */ res = xmlSchemaCompareValues(fminexc->val, bfminexc->val); if (res == -2) goto internal_error; if (res == -1) { xmlSchemaDeriveFacetErr(pctxt, fminexc, bfminexc, 1, 1, 1); } if ((res != 0) && (bfminexc->fixed)) { FACET_RESTR_FIXED_ERR(fminexc) } } if (bfmaxinc) { /* minExclusive <= BASE maxInclusive */ res = xmlSchemaCompareValues(fminexc->val, bfmaxinc->val); if (res == -2) goto internal_error; if (res == 1) { xmlSchemaDeriveFacetErr(pctxt, fminexc, bfmaxinc, -1, 1, 1); } } if (bfmininc) { /* minExclusive >= BASE minInclusive */ res = xmlSchemaCompareValues(fminexc->val, bfmininc->val); if (res == -2) goto internal_error; if (res == -1) { xmlSchemaDeriveFacetErr(pctxt, fminexc, bfmininc, 1, 1, 1); } } if (bfmaxexc) { /* minExclusive < BASE maxExclusive */ res = xmlSchemaCompareValues(fminexc->val, bfmaxexc->val); if (res == -2) goto internal_error; if (res != -1) { xmlSchemaDeriveFacetErr(pctxt, fminexc, bfmaxexc, -1, 0, 1); } } } if (fmininc) { /* * "minInclusive < maxExclusive" */ if (fmaxexc) { res = xmlSchemaCompareValues(fmininc->val, fmaxexc->val); if (res == -2) goto internal_error; if (res != -1) { xmlSchemaDeriveFacetErr(pctxt, fmininc, fmaxexc, -1, 0, 0); } } /* * "minExclusive valid restriction" */ if (bfmininc) { /* minInclusive >= BASE minInclusive */ res = xmlSchemaCompareValues(fmininc->val, bfmininc->val); if (res == -2) goto internal_error; if (res == -1) { xmlSchemaDeriveFacetErr(pctxt, fmininc, bfmininc, 1, 1, 1); } if ((res != 0) && (bfmininc->fixed)) { FACET_RESTR_FIXED_ERR(fmininc) } } if (bfmaxinc) { /* minInclusive <= BASE maxInclusive */ res = xmlSchemaCompareValues(fmininc->val, bfmaxinc->val); if (res == -2) goto internal_error; if (res == 1) { xmlSchemaDeriveFacetErr(pctxt, fmininc, bfmaxinc, -1, 1, 1); } } if (bfminexc) { /* minInclusive > BASE minExclusive */ res = xmlSchemaCompareValues(fmininc->val, bfminexc->val); if (res == -2) goto internal_error; if (res != 1) xmlSchemaDeriveFacetErr(pctxt, fmininc, bfminexc, 1, 0, 1); } if (bfmaxexc) { /* minInclusive < BASE maxExclusive */ res = xmlSchemaCompareValues(fmininc->val, bfmaxexc->val); if (res == -2) goto internal_error; if (res != -1) xmlSchemaDeriveFacetErr(pctxt, fmininc, bfmaxexc, -1, 0, 1); } } if (ftotdig && bftotdig) { /* * SCC " totalDigits valid restriction" * totalDigits <= BASE totalDigits */ res = xmlSchemaCompareValues(ftotdig->val, bftotdig->val); if (res == -2) goto internal_error; if (res == 1) xmlSchemaDeriveFacetErr(pctxt, ftotdig, bftotdig, -1, 1, 1); if ((res != 0) && (bftotdig->fixed)) { FACET_RESTR_FIXED_ERR(ftotdig) } } if (ffracdig && bffracdig) { /* * SCC "fractionDigits valid restriction" * fractionDigits <= BASE fractionDigits */ res = xmlSchemaCompareValues(ffracdig->val, bffracdig->val); if (res == -2) goto internal_error; if (res == 1) xmlSchemaDeriveFacetErr(pctxt, ffracdig, bffracdig, -1, 1, 1); if ((res != 0) && (bffracdig->fixed)) { FACET_RESTR_FIXED_ERR(ffracdig) } } /* * SCC "fractionDigits less than or equal to totalDigits" */ if (! ftotdig) ftotdig = bftotdig; if (! ffracdig) ffracdig = bffracdig; if (ftotdig && ffracdig) { res = xmlSchemaCompareValues(ffracdig->val, ftotdig->val); if (res == -2) goto internal_error; if (res == 1) xmlSchemaDeriveFacetErr(pctxt, ffracdig, ftotdig, -1, 1, 0); } /* * *Enumerations* won' be added here, since only the first set * of enumerations in the ancestor-or-self axis is used * for validation, plus we need to use the base type of those * enumerations for whitespace. * * *Patterns*: won't be add here, since they are ORed at * type level and ANDed at ancestor level. This will * happen during validation by walking the base axis * of the type. */ for (cur = base->facetSet; cur != NULL; cur = cur->next) { bfacet = cur->facet; /* * Special handling of enumerations and patterns. * TODO: hmm, they should not appear in the set, so remove this. */ if ((bfacet->type == XML_SCHEMA_FACET_PATTERN) || (bfacet->type == XML_SCHEMA_FACET_ENUMERATION)) continue; /* * Search for a duplicate facet in the current type. */ link = type->facetSet; /* err = 0; */ /* fixedErr = 0; */ while (link != NULL) { facet = link->facet; if (facet->type == bfacet->type) { switch (facet->type) { case XML_SCHEMA_FACET_WHITESPACE: /* * The whitespace must be stronger. */ if (facet->whitespace < bfacet->whitespace) { FACET_RESTR_ERR(facet, "The 'whitespace' value has to be equal to " "or stronger than the 'whitespace' value of " "the base type") } if ((bfacet->fixed) && (facet->whitespace != bfacet->whitespace)) { FACET_RESTR_FIXED_ERR(facet) } break; default: break; } /* Duplicate found. */ break; } link = link->next; } /* * If no duplicate was found: add the base types's facet * to the set. */ if (link == NULL) { link = (xmlSchemaFacetLinkPtr) xmlMalloc(sizeof(xmlSchemaFacetLink)); if (link == NULL) { xmlSchemaPErrMemory(pctxt, "deriving facets, creating a facet link", NULL); return (-1); } link->facet = cur->facet; link->next = NULL; if (last == NULL) type->facetSet = link; else last->next = link; last = link; } } return (0); internal_error: PERROR_INT("xmlSchemaDeriveAndValidateFacets", "an error occurred"); return (-1); } static int xmlSchemaFinishMemberTypeDefinitionsProperty(xmlSchemaParserCtxtPtr pctxt, xmlSchemaTypePtr type) { xmlSchemaTypeLinkPtr link, lastLink, prevLink, subLink, newLink; /* * The actual value is then formed by replacing any union type * definition in the `explicit members` with the members of their * {member type definitions}, in order. * * TODO: There's a bug entry at * "http://lists.w3.org/Archives/Public/www-xml-schema-comments/2005JulSep/0287.html" * which indicates that we'll keep the union types the future. */ link = type->memberTypes; while (link != NULL) { if (WXS_IS_TYPE_NOT_FIXED(link->type)) xmlSchemaTypeFixup(link->type, ACTXT_CAST pctxt); if (WXS_IS_UNION(link->type)) { subLink = xmlSchemaGetUnionSimpleTypeMemberTypes(link->type); if (subLink != NULL) { link->type = subLink->type; if (subLink->next != NULL) { lastLink = link->next; subLink = subLink->next; prevLink = link; while (subLink != NULL) { newLink = (xmlSchemaTypeLinkPtr) xmlMalloc(sizeof(xmlSchemaTypeLink)); if (newLink == NULL) { xmlSchemaPErrMemory(pctxt, "allocating a type link", NULL); return (-1); } newLink->type = subLink->type; prevLink->next = newLink; prevLink = newLink; newLink->next = lastLink; subLink = subLink->next; } } } } link = link->next; } return (0); } static void xmlSchemaTypeFixupOptimFacets(xmlSchemaTypePtr type) { int has = 0, needVal = 0, normVal = 0; has = (type->baseType->flags & XML_SCHEMAS_TYPE_HAS_FACETS) ? 1 : 0; if (has) { needVal = (type->baseType->flags & XML_SCHEMAS_TYPE_FACETSNEEDVALUE) ? 1 : 0; normVal = (type->baseType->flags & XML_SCHEMAS_TYPE_NORMVALUENEEDED) ? 1 : 0; } if (type->facets != NULL) { xmlSchemaFacetPtr fac; for (fac = type->facets; fac != NULL; fac = fac->next) { switch (fac->type) { case XML_SCHEMA_FACET_WHITESPACE: break; case XML_SCHEMA_FACET_PATTERN: normVal = 1; has = 1; break; case XML_SCHEMA_FACET_ENUMERATION: needVal = 1; normVal = 1; has = 1; break; default: has = 1; break; } } } if (normVal) type->flags |= XML_SCHEMAS_TYPE_NORMVALUENEEDED; if (needVal) type->flags |= XML_SCHEMAS_TYPE_FACETSNEEDVALUE; if (has) type->flags |= XML_SCHEMAS_TYPE_HAS_FACETS; if (has && (! needVal) && WXS_IS_ATOMIC(type)) { xmlSchemaTypePtr prim = xmlSchemaGetPrimitiveType(type); /* * OPTIMIZE VAL TODO: Some facets need a computed value. */ if ((prim->builtInType != XML_SCHEMAS_ANYSIMPLETYPE) && (prim->builtInType != XML_SCHEMAS_STRING)) { type->flags |= XML_SCHEMAS_TYPE_FACETSNEEDVALUE; } } } static int xmlSchemaTypeFixupWhitespace(xmlSchemaTypePtr type) { /* * Evaluate the whitespace-facet value. */ if (WXS_IS_LIST(type)) { type->flags |= XML_SCHEMAS_TYPE_WHITESPACE_COLLAPSE; return (0); } else if (WXS_IS_UNION(type)) return (0); if (type->facetSet != NULL) { xmlSchemaFacetLinkPtr lin; for (lin = type->facetSet; lin != NULL; lin = lin->next) { if (lin->facet->type == XML_SCHEMA_FACET_WHITESPACE) { switch (lin->facet->whitespace) { case XML_SCHEMAS_FACET_PRESERVE: type->flags |= XML_SCHEMAS_TYPE_WHITESPACE_PRESERVE; break; case XML_SCHEMAS_FACET_REPLACE: type->flags |= XML_SCHEMAS_TYPE_WHITESPACE_REPLACE; break; case XML_SCHEMAS_FACET_COLLAPSE: type->flags |= XML_SCHEMAS_TYPE_WHITESPACE_COLLAPSE; break; default: return (-1); } return (0); } } } /* * For all `atomic` datatypes other than string (and types `derived` * by `restriction` from it) the value of whiteSpace is fixed to * collapse */ { xmlSchemaTypePtr anc; for (anc = type->baseType; anc != NULL && anc->builtInType != XML_SCHEMAS_ANYTYPE; anc = anc->baseType) { if (anc->type == XML_SCHEMA_TYPE_BASIC) { if (anc->builtInType == XML_SCHEMAS_NORMSTRING) { type->flags |= XML_SCHEMAS_TYPE_WHITESPACE_REPLACE; } else if ((anc->builtInType == XML_SCHEMAS_STRING) || (anc->builtInType == XML_SCHEMAS_ANYSIMPLETYPE)) { type->flags |= XML_SCHEMAS_TYPE_WHITESPACE_PRESERVE; } else type->flags |= XML_SCHEMAS_TYPE_WHITESPACE_COLLAPSE; break; } } } return (0); } static int xmlSchemaFixupSimpleTypeStageOne(xmlSchemaParserCtxtPtr pctxt, xmlSchemaTypePtr type) { if (type->type != XML_SCHEMA_TYPE_SIMPLE) return(0); if (! WXS_IS_TYPE_NOT_FIXED_1(type)) return(0); type->flags |= XML_SCHEMAS_TYPE_FIXUP_1; if (WXS_IS_LIST(type)) { /* * Corresponds to <simpleType><list>... */ if (type->subtypes == NULL) { /* * This one is really needed, so get out. */ PERROR_INT("xmlSchemaFixupSimpleTypeStageOne", "list type has no item-type assigned"); return(-1); } } else if (WXS_IS_UNION(type)) { /* * Corresponds to <simpleType><union>... */ if (type->memberTypes == NULL) { /* * This one is really needed, so get out. */ PERROR_INT("xmlSchemaFixupSimpleTypeStageOne", "union type has no member-types assigned"); return(-1); } } else { /* * Corresponds to <simpleType><restriction>... */ if (type->baseType == NULL) { PERROR_INT("xmlSchemaFixupSimpleTypeStageOne", "type has no base-type assigned"); return(-1); } if (WXS_IS_TYPE_NOT_FIXED_1(type->baseType)) if (xmlSchemaFixupSimpleTypeStageOne(pctxt, type->baseType) == -1) return(-1); /* * Variety * If the <restriction> alternative is chosen, then the * {variety} of the {base type definition}. */ if (WXS_IS_ATOMIC(type->baseType)) type->flags |= XML_SCHEMAS_TYPE_VARIETY_ATOMIC; else if (WXS_IS_LIST(type->baseType)) { type->flags |= XML_SCHEMAS_TYPE_VARIETY_LIST; /* * Inherit the itemType. */ type->subtypes = type->baseType->subtypes; } else if (WXS_IS_UNION(type->baseType)) { type->flags |= XML_SCHEMAS_TYPE_VARIETY_UNION; /* * NOTE that we won't assign the memberTypes of the base, * since this will make trouble when freeing them; we will * use a lookup function to access them instead. */ } } return(0); } #ifdef DEBUG_TYPE static void xmlSchemaDebugFixedType(xmlSchemaParserCtxtPtr pctxt, xmlSchemaTypePtr type) { if (type->node != NULL) { xmlGenericError(xmlGenericErrorContext, "Type of %s : %s:%d :", name, type->node->doc->URL, xmlGetLineNo(type->node)); } else { xmlGenericError(xmlGenericErrorContext, "Type of %s :", name); } if ((WXS_IS_SIMPLE(type)) || (WXS_IS_COMPLEX(type))) { switch (type->contentType) { case XML_SCHEMA_CONTENT_SIMPLE: xmlGenericError(xmlGenericErrorContext, "simple\n"); break; case XML_SCHEMA_CONTENT_ELEMENTS: xmlGenericError(xmlGenericErrorContext, "elements\n"); break; case XML_SCHEMA_CONTENT_UNKNOWN: xmlGenericError(xmlGenericErrorContext, "unknown !!!\n"); break; case XML_SCHEMA_CONTENT_EMPTY: xmlGenericError(xmlGenericErrorContext, "empty\n"); break; case XML_SCHEMA_CONTENT_MIXED: if (xmlSchemaIsParticleEmptiable((xmlSchemaParticlePtr) type->subtypes)) xmlGenericError(xmlGenericErrorContext, "mixed as emptiable particle\n"); else xmlGenericError(xmlGenericErrorContext, "mixed\n"); break; /* Removed, since not used. */ /* case XML_SCHEMA_CONTENT_MIXED_OR_ELEMENTS: xmlGenericError(xmlGenericErrorContext, "mixed or elems\n"); break; */ case XML_SCHEMA_CONTENT_BASIC: xmlGenericError(xmlGenericErrorContext, "basic\n"); break; default: xmlGenericError(xmlGenericErrorContext, "not registered !!!\n"); break; } } } #endif /* * 3.14.6 Constraints on Simple Type Definition Schema Components */ static int xmlSchemaFixupSimpleTypeStageTwo(xmlSchemaParserCtxtPtr pctxt, xmlSchemaTypePtr type) { int res, olderrs = pctxt->nberrors; if (type->type != XML_SCHEMA_TYPE_SIMPLE) return(-1); if (! WXS_IS_TYPE_NOT_FIXED(type)) return(0); type->flags |= XML_SCHEMAS_TYPE_INTERNAL_RESOLVED; type->contentType = XML_SCHEMA_CONTENT_SIMPLE; if (type->baseType == NULL) { PERROR_INT("xmlSchemaFixupSimpleTypeStageTwo", "missing baseType"); goto exit_failure; } if (WXS_IS_TYPE_NOT_FIXED(type->baseType)) xmlSchemaTypeFixup(type->baseType, ACTXT_CAST pctxt); /* * If a member type of a union is a union itself, we need to substitute * that member type for its member types. * NOTE that this might change in WXS 1.1; i.e. we will keep the union * types in WXS 1.1. */ if ((type->memberTypes != NULL) && (xmlSchemaFinishMemberTypeDefinitionsProperty(pctxt, type) == -1)) return(-1); /* * SPEC src-simple-type 1 * "The corresponding simple type definition, if any, must satisfy * the conditions set out in Constraints on Simple Type Definition * Schema Components ($3.14.6)." */ /* * Schema Component Constraint: Simple Type Definition Properties Correct * (st-props-correct) */ res = xmlSchemaCheckSTPropsCorrect(pctxt, type); HFAILURE HERROR /* * Schema Component Constraint: Derivation Valid (Restriction, Simple) * (cos-st-restricts) */ res = xmlSchemaCheckCOSSTRestricts(pctxt, type); HFAILURE HERROR /* * TODO: Removed the error report, since it got annoying to get an * extra error report, if anything failed until now. * Enable this if needed. * * xmlSchemaPErr(ctxt, type->node, * XML_SCHEMAP_SRC_SIMPLE_TYPE_1, * "Simple type '%s' does not satisfy the constraints " * "on simple type definitions.\n", * type->name, NULL); */ /* * Schema Component Constraint: Simple Type Restriction (Facets) * (st-restrict-facets) */ res = xmlSchemaCheckFacetValues(type, pctxt); HFAILURE HERROR if ((type->facetSet != NULL) || (type->baseType->facetSet != NULL)) { res = xmlSchemaDeriveAndValidateFacets(pctxt, type); HFAILURE HERROR } /* * Whitespace value. */ res = xmlSchemaTypeFixupWhitespace(type); HFAILURE HERROR xmlSchemaTypeFixupOptimFacets(type); exit_error: #ifdef DEBUG_TYPE xmlSchemaDebugFixedType(pctxt, type); #endif if (olderrs != pctxt->nberrors) return(pctxt->err); return(0); exit_failure: #ifdef DEBUG_TYPE xmlSchemaDebugFixedType(pctxt, type); #endif return(-1); } static int xmlSchemaFixupComplexType(xmlSchemaParserCtxtPtr pctxt, xmlSchemaTypePtr type) { int res = 0, olderrs = pctxt->nberrors; xmlSchemaTypePtr baseType = type->baseType; if (! WXS_IS_TYPE_NOT_FIXED(type)) return(0); type->flags |= XML_SCHEMAS_TYPE_INTERNAL_RESOLVED; if (baseType == NULL) { PERROR_INT("xmlSchemaFixupComplexType", "missing baseType"); goto exit_failure; } /* * Fixup the base type. */ if (WXS_IS_TYPE_NOT_FIXED(baseType)) xmlSchemaTypeFixup(baseType, ACTXT_CAST pctxt); if (baseType->flags & XML_SCHEMAS_TYPE_INTERNAL_INVALID) { /* * Skip fixup if the base type is invalid. * TODO: Generate a warning! */ return(0); } /* * This basically checks if the base type can be derived. */ res = xmlSchemaCheckSRCCT(pctxt, type); HFAILURE HERROR /* * Fixup the content type. */ if (type->contentType == XML_SCHEMA_CONTENT_SIMPLE) { /* * Corresponds to <complexType><simpleContent>... */ if ((WXS_IS_COMPLEX(baseType)) && (baseType->contentTypeDef != NULL) && (WXS_IS_RESTRICTION(type))) { xmlSchemaTypePtr contentBase, content; #ifdef ENABLE_NAMED_LOCALS char buf[30]; const xmlChar *tmpname; #endif /* * SPEC (1) If <restriction> + base type is <complexType>, * "whose own {content type} is a simple type..." */ if (type->contentTypeDef != NULL) { /* * SPEC (1.1) "the simple type definition corresponding to the * <simpleType> among the [children] of <restriction> if there * is one;" * Note that this "<simpleType> among the [children]" was put * into ->contentTypeDef during parsing. */ contentBase = type->contentTypeDef; type->contentTypeDef = NULL; } else { /* * (1.2) "...otherwise (<restriction> has no <simpleType> * among its [children]), the simple type definition which * is the {content type} of the ... base type." */ contentBase = baseType->contentTypeDef; } /* * SPEC * "... a simple type definition which restricts the simple * type definition identified in clause 1.1 or clause 1.2 * with a set of facet components" * * Create the anonymous simple type, which will be the content * type of the complex type. */ #ifdef ENABLE_NAMED_LOCALS snprintf(buf, 29, "#scST%d", ++(pctxt->counter)); tmpname = xmlDictLookup(pctxt->dict, BAD_CAST buf, -1); content = xmlSchemaAddType(pctxt, pctxt->schema, XML_SCHEMA_TYPE_SIMPLE, tmpname, type->targetNamespace, type->node, 0); #else content = xmlSchemaAddType(pctxt, pctxt->schema, XML_SCHEMA_TYPE_SIMPLE, NULL, type->targetNamespace, type->node, 0); #endif if (content == NULL) goto exit_failure; /* * We will use the same node as for the <complexType> * to have it somehow anchored in the schema doc. */ content->type = XML_SCHEMA_TYPE_SIMPLE; content->baseType = contentBase; /* * Move the facets, previously anchored on the * complexType during parsing. */ content->facets = type->facets; type->facets = NULL; content->facetSet = type->facetSet; type->facetSet = NULL; type->contentTypeDef = content; if (WXS_IS_TYPE_NOT_FIXED(contentBase)) xmlSchemaTypeFixup(contentBase, ACTXT_CAST pctxt); /* * Fixup the newly created type. We don't need to check * for circularity here. */ res = xmlSchemaFixupSimpleTypeStageOne(pctxt, content); HFAILURE HERROR res = xmlSchemaFixupSimpleTypeStageTwo(pctxt, content); HFAILURE HERROR } else if ((WXS_IS_COMPLEX(baseType)) && (baseType->contentType == XML_SCHEMA_CONTENT_MIXED) && (WXS_IS_RESTRICTION(type))) { /* * SPEC (2) If <restriction> + base is a mixed <complexType> with * an emptiable particle, then a simple type definition which * restricts the <restriction>'s <simpleType> child. */ if ((type->contentTypeDef == NULL) || (type->contentTypeDef->baseType == NULL)) { /* * TODO: Check if this ever happens. */ xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_INTERNAL, WXS_BASIC_CAST type, NULL, "Internal error: xmlSchemaTypeFixup, " "complex type '%s': the <simpleContent><restriction> " "is missing a <simpleType> child, but was not caught " "by xmlSchemaCheckSRCCT()", type->name); goto exit_failure; } } else if ((WXS_IS_COMPLEX(baseType)) && WXS_IS_EXTENSION(type)) { /* * SPEC (3) If <extension> + base is <complexType> with * <simpleType> content, "...then the {content type} of that * complex type definition" */ if (baseType->contentTypeDef == NULL) { /* * TODO: Check if this ever happens. xmlSchemaCheckSRCCT * should have caught this already. */ xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_INTERNAL, WXS_BASIC_CAST type, NULL, "Internal error: xmlSchemaTypeFixup, " "complex type '%s': the <extension>ed base type is " "a complex type with no simple content type", type->name); goto exit_failure; } type->contentTypeDef = baseType->contentTypeDef; } else if ((WXS_IS_SIMPLE(baseType)) && WXS_IS_EXTENSION(type)) { /* * SPEC (4) <extension> + base is <simpleType> * "... then that simple type definition" */ type->contentTypeDef = baseType; } else { /* * TODO: Check if this ever happens. */ xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_INTERNAL, WXS_BASIC_CAST type, NULL, "Internal error: xmlSchemaTypeFixup, " "complex type '%s' with <simpleContent>: unhandled " "derivation case", type->name); goto exit_failure; } } else { int dummySequence = 0; xmlSchemaParticlePtr particle = (xmlSchemaParticlePtr) type->subtypes; /* * Corresponds to <complexType><complexContent>... * * NOTE that the effective mixed was already set during parsing of * <complexType> and <complexContent>; its flag value is * XML_SCHEMAS_TYPE_MIXED. * * Compute the "effective content": * (2.1.1) + (2.1.2) + (2.1.3) */ if ((particle == NULL) || ((particle->type == XML_SCHEMA_TYPE_PARTICLE) && ((particle->children->type == XML_SCHEMA_TYPE_ALL) || (particle->children->type == XML_SCHEMA_TYPE_SEQUENCE) || ((particle->children->type == XML_SCHEMA_TYPE_CHOICE) && (particle->minOccurs == 0))) && ( ((xmlSchemaTreeItemPtr) particle->children)->children == NULL))) { if (type->flags & XML_SCHEMAS_TYPE_MIXED) { /* * SPEC (2.1.4) "If the `effective mixed` is true, then * a particle whose properties are as follows:..." * * Empty sequence model group with * minOccurs/maxOccurs = 1 (i.e. a "particle emptiable"). * NOTE that we sill assign it the <complexType> node to * somehow anchor it in the doc. */ if ((particle == NULL) || (particle->children->type != XML_SCHEMA_TYPE_SEQUENCE)) { /* * Create the particle. */ particle = xmlSchemaAddParticle(pctxt, type->node, 1, 1); if (particle == NULL) goto exit_failure; /* * Create the model group. */ /* URGENT TODO: avoid adding to pending items. */ particle->children = (xmlSchemaTreeItemPtr) xmlSchemaAddModelGroup(pctxt, pctxt->schema, XML_SCHEMA_TYPE_SEQUENCE, type->node); if (particle->children == NULL) goto exit_failure; type->subtypes = (xmlSchemaTypePtr) particle; } dummySequence = 1; type->contentType = XML_SCHEMA_CONTENT_ELEMENTS; } else { /* * SPEC (2.1.5) "otherwise empty" */ type->contentType = XML_SCHEMA_CONTENT_EMPTY; } } else { /* * SPEC (2.2) "otherwise the particle corresponding to the * <all>, <choice>, <group> or <sequence> among the * [children]." */ type->contentType = XML_SCHEMA_CONTENT_ELEMENTS; } /* * Compute the "content type". */ if (WXS_IS_RESTRICTION(type)) { /* * SPEC (3.1) "If <restriction>..." * (3.1.1) + (3.1.2) */ if (type->contentType != XML_SCHEMA_CONTENT_EMPTY) { if (type->flags & XML_SCHEMAS_TYPE_MIXED) type->contentType = XML_SCHEMA_CONTENT_MIXED; } } else { /* * SPEC (3.2) "If <extension>..." */ if (type->contentType == XML_SCHEMA_CONTENT_EMPTY) { /* * SPEC (3.2.1) * "If the `effective content` is empty, then the * {content type} of the [...] base ..." */ type->contentType = baseType->contentType; type->subtypes = baseType->subtypes; /* * Fixes bug #347316: * This is the case when the base type has a simple * type definition as content. */ type->contentTypeDef = baseType->contentTypeDef; /* * NOTE that the effective mixed is ignored here. */ } else if (baseType->contentType == XML_SCHEMA_CONTENT_EMPTY) { /* * SPEC (3.2.2) */ if (type->flags & XML_SCHEMAS_TYPE_MIXED) type->contentType = XML_SCHEMA_CONTENT_MIXED; } else { /* * SPEC (3.2.3) */ if (type->flags & XML_SCHEMAS_TYPE_MIXED) type->contentType = XML_SCHEMA_CONTENT_MIXED; /* * "A model group whose {compositor} is sequence and whose * {particles} are..." */ if ((WXS_TYPE_PARTICLE(type) != NULL) && (WXS_TYPE_PARTICLE_TERM(type) != NULL) && ((WXS_TYPE_PARTICLE_TERM(type))->type == XML_SCHEMA_TYPE_ALL)) { /* * SPEC cos-all-limited (1) */ xmlSchemaCustomErr(ACTXT_CAST pctxt, /* TODO: error code */ XML_SCHEMAP_COS_ALL_LIMITED, WXS_ITEM_NODE(type), NULL, "The type has an 'all' model group in its " "{content type} and thus cannot be derived from " "a non-empty type, since this would produce a " "'sequence' model group containing the 'all' " "model group; 'all' model groups are not " "allowed to appear inside other model groups", NULL, NULL); } else if ((WXS_TYPE_PARTICLE(baseType) != NULL) && (WXS_TYPE_PARTICLE_TERM(baseType) != NULL) && ((WXS_TYPE_PARTICLE_TERM(baseType))->type == XML_SCHEMA_TYPE_ALL)) { /* * SPEC cos-all-limited (1) */ xmlSchemaCustomErr(ACTXT_CAST pctxt, /* TODO: error code */ XML_SCHEMAP_COS_ALL_LIMITED, WXS_ITEM_NODE(type), NULL, "A type cannot be derived by extension from a type " "which has an 'all' model group in its " "{content type}, since this would produce a " "'sequence' model group containing the 'all' " "model group; 'all' model groups are not " "allowed to appear inside other model groups", NULL, NULL); } else if (! dummySequence) { xmlSchemaTreeItemPtr effectiveContent = (xmlSchemaTreeItemPtr) type->subtypes; /* * Create the particle. */ particle = xmlSchemaAddParticle(pctxt, type->node, 1, 1); if (particle == NULL) goto exit_failure; /* * Create the "sequence" model group. */ particle->children = (xmlSchemaTreeItemPtr) xmlSchemaAddModelGroup(pctxt, pctxt->schema, XML_SCHEMA_TYPE_SEQUENCE, type->node); if (particle->children == NULL) goto exit_failure; WXS_TYPE_CONTENTTYPE(type) = (xmlSchemaTypePtr) particle; /* * SPEC "the particle of the {content type} of * the ... base ..." * Create a duplicate of the base type's particle * and assign its "term" to it. */ particle->children->children = (xmlSchemaTreeItemPtr) xmlSchemaAddParticle(pctxt, type->node, ((xmlSchemaParticlePtr) baseType->subtypes)->minOccurs, ((xmlSchemaParticlePtr) baseType->subtypes)->maxOccurs); if (particle->children->children == NULL) goto exit_failure; particle = (xmlSchemaParticlePtr) particle->children->children; particle->children = ((xmlSchemaParticlePtr) baseType->subtypes)->children; /* * SPEC "followed by the `effective content`." */ particle->next = effectiveContent; /* * This all will result in: * new-particle * --> new-sequence( * new-particle * --> base-model, * this-particle * --> this-model * ) */ } else { /* * This is the case when there is already an empty * <sequence> with minOccurs==maxOccurs==1. * Just add the base types's content type. * NOTE that, although we miss to add an intermediate * <sequence>, this should produce no difference to * neither the regex compilation of the content model, * nor to the complex type constraints. */ particle->children->children = (xmlSchemaTreeItemPtr) baseType->subtypes; } } } } /* * Now fixup attribute uses: * - expand attr. group references * - intersect attribute wildcards * - inherit attribute uses of the base type * - inherit or union attr. wildcards if extending * - apply attr. use prohibitions if restricting */ res = xmlSchemaFixupTypeAttributeUses(pctxt, type); HFAILURE HERROR /* * Apply the complex type component constraints; this will not * check attributes, since this is done in * xmlSchemaFixupTypeAttributeUses(). */ res = xmlSchemaCheckCTComponent(pctxt, type); HFAILURE HERROR #ifdef DEBUG_TYPE xmlSchemaDebugFixedType(pctxt, type); #endif if (olderrs != pctxt->nberrors) return(pctxt->err); else return(0); exit_error: type->flags |= XML_SCHEMAS_TYPE_INTERNAL_INVALID; #ifdef DEBUG_TYPE xmlSchemaDebugFixedType(pctxt, type); #endif return(pctxt->err); exit_failure: type->flags |= XML_SCHEMAS_TYPE_INTERNAL_INVALID; #ifdef DEBUG_TYPE xmlSchemaDebugFixedType(pctxt, type); #endif return(-1); } /** * xmlSchemaTypeFixup: * @typeDecl: the schema type definition * @ctxt: the schema parser context * * Fixes the content model of the type. * URGENT TODO: We need an int result! */ static int xmlSchemaTypeFixup(xmlSchemaTypePtr type, xmlSchemaAbstractCtxtPtr actxt) { if (type == NULL) return(0); if (actxt->type != XML_SCHEMA_CTXT_PARSER) { AERROR_INT("xmlSchemaTypeFixup", "this function needs a parser context"); return(-1); } if (! WXS_IS_TYPE_NOT_FIXED(type)) return(0); if (type->type == XML_SCHEMA_TYPE_COMPLEX) return(xmlSchemaFixupComplexType(PCTXT_CAST actxt, type)); else if (type->type == XML_SCHEMA_TYPE_SIMPLE) return(xmlSchemaFixupSimpleTypeStageTwo(PCTXT_CAST actxt, type)); return(0); } /** * xmlSchemaCheckFacet: * @facet: the facet * @typeDecl: the schema type definition * @pctxt: the schema parser context or NULL * @name: the optional name of the type * * Checks and computes the values of facets. * * Returns 0 if valid, a positive error code if not valid and * -1 in case of an internal or API error. */ int xmlSchemaCheckFacet(xmlSchemaFacetPtr facet, xmlSchemaTypePtr typeDecl, xmlSchemaParserCtxtPtr pctxt, const xmlChar * name ATTRIBUTE_UNUSED) { int ret = 0, ctxtGiven; if ((facet == NULL) || (typeDecl == NULL)) return(-1); /* * TODO: will the parser context be given if used from * the relaxNG module? */ if (pctxt == NULL) ctxtGiven = 0; else ctxtGiven = 1; switch (facet->type) { case XML_SCHEMA_FACET_MININCLUSIVE: case XML_SCHEMA_FACET_MINEXCLUSIVE: case XML_SCHEMA_FACET_MAXINCLUSIVE: case XML_SCHEMA_FACET_MAXEXCLUSIVE: case XML_SCHEMA_FACET_ENUMERATION: { /* * Okay we need to validate the value * at that point. */ xmlSchemaTypePtr base; /* 4.3.5.5 Constraints on enumeration Schema Components * Schema Component Constraint: enumeration valid restriction * It is an `error` if any member of {value} is not in the * `value space` of {base type definition}. * * minInclusive, maxInclusive, minExclusive, maxExclusive: * The value `must` be in the * `value space` of the `base type`. */ /* * This function is intended to deliver a compiled value * on the facet. In this implementation of XML Schemata the * type holding a facet, won't be a built-in type. * Thus to ensure that other API * calls (relaxng) do work, if the given type is a built-in * type, we will assume that the given built-in type *is * already* the base type. */ if (typeDecl->type != XML_SCHEMA_TYPE_BASIC) { base = typeDecl->baseType; if (base == NULL) { PERROR_INT("xmlSchemaCheckFacet", "a type user derived type has no base type"); return (-1); } } else base = typeDecl; if (! ctxtGiven) { /* * A context is needed if called from RelaxNG. */ pctxt = xmlSchemaNewParserCtxt("*"); if (pctxt == NULL) return (-1); } /* * NOTE: This call does not check the content nodes, * since they are not available: * facet->node is just the node holding the facet * definition, *not* the attribute holding the *value* * of the facet. */ ret = xmlSchemaVCheckCVCSimpleType( ACTXT_CAST pctxt, facet->node, base, facet->value, &(facet->val), 1, 1, 0); if (ret != 0) { if (ret < 0) { /* No error message for RelaxNG. */ if (ctxtGiven) { xmlSchemaCustomErr(ACTXT_CAST pctxt, XML_SCHEMAP_INTERNAL, facet->node, NULL, "Internal error: xmlSchemaCheckFacet, " "failed to validate the value '%s' of the " "facet '%s' against the base type", facet->value, xmlSchemaFacetTypeToString(facet->type)); } goto internal_error; } ret = XML_SCHEMAP_INVALID_FACET_VALUE; /* No error message for RelaxNG. */ if (ctxtGiven) { xmlChar *str = NULL; xmlSchemaCustomErr(ACTXT_CAST pctxt, ret, facet->node, WXS_BASIC_CAST facet, "The value '%s' of the facet does not validate " "against the base type '%s'", facet->value, xmlSchemaFormatQName(&str, base->targetNamespace, base->name)); FREE_AND_NULL(str); } goto exit; } else if (facet->val == NULL) { if (ctxtGiven) { PERROR_INT("xmlSchemaCheckFacet", "value was not computed"); } TODO } break; } case XML_SCHEMA_FACET_PATTERN: facet->regexp = xmlRegexpCompile(facet->value); if (facet->regexp == NULL) { ret = XML_SCHEMAP_REGEXP_INVALID; /* No error message for RelaxNG. */ if (ctxtGiven) { xmlSchemaCustomErr(ACTXT_CAST pctxt, ret, facet->node, WXS_BASIC_CAST typeDecl, "The value '%s' of the facet 'pattern' is not a " "valid regular expression", facet->value, NULL); } } break; case XML_SCHEMA_FACET_TOTALDIGITS: case XML_SCHEMA_FACET_FRACTIONDIGITS: case XML_SCHEMA_FACET_LENGTH: case XML_SCHEMA_FACET_MAXLENGTH: case XML_SCHEMA_FACET_MINLENGTH: if (facet->type == XML_SCHEMA_FACET_TOTALDIGITS) { ret = xmlSchemaValidatePredefinedType( xmlSchemaGetBuiltInType(XML_SCHEMAS_PINTEGER), facet->value, &(facet->val)); } else { ret = xmlSchemaValidatePredefinedType( xmlSchemaGetBuiltInType(XML_SCHEMAS_NNINTEGER), facet->value, &(facet->val)); } if (ret != 0) { if (ret < 0) { /* No error message for RelaxNG. */ if (ctxtGiven) { PERROR_INT("xmlSchemaCheckFacet", "validating facet value"); } goto internal_error; } ret = XML_SCHEMAP_INVALID_FACET_VALUE; /* No error message for RelaxNG. */ if (ctxtGiven) { /* error code */ xmlSchemaCustomErr4(ACTXT_CAST pctxt, ret, facet->node, WXS_BASIC_CAST typeDecl, "The value '%s' of the facet '%s' is not a valid '%s'", facet->value, xmlSchemaFacetTypeToString(facet->type), (facet->type != XML_SCHEMA_FACET_TOTALDIGITS) ? BAD_CAST "nonNegativeInteger" : BAD_CAST "positiveInteger", NULL); } } break; case XML_SCHEMA_FACET_WHITESPACE:{ if (xmlStrEqual(facet->value, BAD_CAST "preserve")) { facet->whitespace = XML_SCHEMAS_FACET_PRESERVE; } else if (xmlStrEqual(facet->value, BAD_CAST "replace")) { facet->whitespace = XML_SCHEMAS_FACET_REPLACE; } else if (xmlStrEqual(facet->value, BAD_CAST "collapse")) { facet->whitespace = XML_SCHEMAS_FACET_COLLAPSE; } else { ret = XML_SCHEMAP_INVALID_FACET_VALUE; /* No error message for RelaxNG. */ if (ctxtGiven) { /* error was previously: XML_SCHEMAP_INVALID_WHITE_SPACE */ xmlSchemaCustomErr(ACTXT_CAST pctxt, ret, facet->node, WXS_BASIC_CAST typeDecl, "The value '%s' of the facet 'whitespace' is not " "valid", facet->value, NULL); } } } default: break; } exit: if ((! ctxtGiven) && (pctxt != NULL)) xmlSchemaFreeParserCtxt(pctxt); return (ret); internal_error: if ((! ctxtGiven) && (pctxt != NULL)) xmlSchemaFreeParserCtxt(pctxt); return (-1); } /** * xmlSchemaCheckFacetValues: * @typeDecl: the schema type definition * @ctxt: the schema parser context * * Checks the default values types, especially for facets */ static int xmlSchemaCheckFacetValues(xmlSchemaTypePtr typeDecl, xmlSchemaParserCtxtPtr pctxt) { int res, olderrs = pctxt->nberrors; const xmlChar *name = typeDecl->name; /* * NOTE: It is intended to use the facets list, instead * of facetSet. */ if (typeDecl->facets != NULL) { xmlSchemaFacetPtr facet = typeDecl->facets; /* * Temporarily assign the "schema" to the validation context * of the parser context. This is needed for NOTATION validation. */ if (pctxt->vctxt == NULL) { if (xmlSchemaCreateVCtxtOnPCtxt(pctxt) == -1) return(-1); } pctxt->vctxt->schema = pctxt->schema; while (facet != NULL) { res = xmlSchemaCheckFacet(facet, typeDecl, pctxt, name); HFAILURE facet = facet->next; } pctxt->vctxt->schema = NULL; } if (olderrs != pctxt->nberrors) return(pctxt->err); return(0); exit_failure: return(-1); } /** * xmlSchemaGetCircModelGrDefRef: * @ctxtMGroup: the searched model group * @selfMGroup: the second searched model group * @particle: the first particle * * This one is intended to be used by * xmlSchemaCheckGroupDefCircular only. * * Returns the particle with the circular model group definition reference, * otherwise NULL. */ static xmlSchemaTreeItemPtr xmlSchemaGetCircModelGrDefRef(xmlSchemaModelGroupDefPtr groupDef, xmlSchemaTreeItemPtr particle) { xmlSchemaTreeItemPtr circ = NULL; xmlSchemaTreeItemPtr term; xmlSchemaModelGroupDefPtr gdef; for (; particle != NULL; particle = particle->next) { term = particle->children; if (term == NULL) continue; switch (term->type) { case XML_SCHEMA_TYPE_GROUP: gdef = (xmlSchemaModelGroupDefPtr) term; if (gdef == groupDef) return (particle); /* * Mark this model group definition to avoid infinite * recursion on circular references not yet examined. */ if (gdef->flags & XML_SCHEMA_MODEL_GROUP_DEF_MARKED) continue; if (gdef->children != NULL) { gdef->flags |= XML_SCHEMA_MODEL_GROUP_DEF_MARKED; circ = xmlSchemaGetCircModelGrDefRef(groupDef, gdef->children->children); gdef->flags ^= XML_SCHEMA_MODEL_GROUP_DEF_MARKED; if (circ != NULL) return (circ); } break; case XML_SCHEMA_TYPE_SEQUENCE: case XML_SCHEMA_TYPE_CHOICE: case XML_SCHEMA_TYPE_ALL: circ = xmlSchemaGetCircModelGrDefRef(groupDef, term->children); if (circ != NULL) return (circ); break; default: break; } } return (NULL); } /** * xmlSchemaCheckGroupDefCircular: * @item: the model group definition * @ctxt: the parser context * @name: the name * * Checks for circular references to model group definitions. */ static void xmlSchemaCheckGroupDefCircular(xmlSchemaModelGroupDefPtr item, xmlSchemaParserCtxtPtr ctxt) { /* * Schema Component Constraint: Model Group Correct * 2 Circular groups are disallowed. That is, within the {particles} * of a group there must not be at any depth a particle whose {term} * is the group itself. */ if ((item == NULL) || (item->type != XML_SCHEMA_TYPE_GROUP) || (item->children == NULL)) return; { xmlSchemaTreeItemPtr circ; circ = xmlSchemaGetCircModelGrDefRef(item, item->children->children); if (circ != NULL) { xmlChar *str = NULL; /* * TODO: The error report is not adequate: this constraint * is defined for model groups but not definitions, but since * there cannot be any circular model groups without a model group * definition (if not using a construction API), we check those * definitions only. */ xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_MG_PROPS_CORRECT_2, NULL, WXS_ITEM_NODE(circ), "Circular reference to the model group definition '%s' " "defined", xmlSchemaFormatQName(&str, item->targetNamespace, item->name)); FREE_AND_NULL(str) /* * NOTE: We will cut the reference to avoid further * confusion of the processor. This is a fatal error. */ circ->children = NULL; } } } /** * xmlSchemaModelGroupToModelGroupDefFixup: * @ctxt: the parser context * @mg: the model group * * Assigns the model group of model group definitions to the "term" * of the referencing particle. * In xmlSchemaResolveModelGroupParticleReferences the model group * definitions were assigned to the "term", since needed for the * circularity check. * * Schema Component Constraint: * All Group Limited (cos-all-limited) (1.2) */ static void xmlSchemaModelGroupToModelGroupDefFixup( xmlSchemaParserCtxtPtr ctxt ATTRIBUTE_UNUSED, xmlSchemaModelGroupPtr mg) { xmlSchemaParticlePtr particle = WXS_MODELGROUP_PARTICLE(mg); while (particle != NULL) { if ((WXS_PARTICLE_TERM(particle) == NULL) || ((WXS_PARTICLE_TERM(particle))->type != XML_SCHEMA_TYPE_GROUP)) { particle = WXS_PTC_CAST particle->next; continue; } if (WXS_MODELGROUPDEF_MODEL(WXS_PARTICLE_TERM(particle)) == NULL) { /* * TODO: Remove the particle. */ WXS_PARTICLE_TERM(particle) = NULL; particle = WXS_PTC_CAST particle->next; continue; } /* * Assign the model group to the {term} of the particle. */ WXS_PARTICLE_TERM(particle) = WXS_TREE_CAST WXS_MODELGROUPDEF_MODEL(WXS_PARTICLE_TERM(particle)); particle = WXS_PTC_CAST particle->next; } } /** * xmlSchemaCheckAttrGroupCircularRecur: * @ctxtGr: the searched attribute group * @attr: the current attribute list to be processed * * This one is intended to be used by * xmlSchemaCheckAttrGroupCircular only. * * Returns the circular attribute group reference, otherwise NULL. */ static xmlSchemaQNameRefPtr xmlSchemaCheckAttrGroupCircularRecur(xmlSchemaAttributeGroupPtr ctxtGr, xmlSchemaItemListPtr list) { xmlSchemaAttributeGroupPtr gr; xmlSchemaQNameRefPtr ref, circ; int i; /* * We will search for an attribute group reference which * references the context attribute group. */ for (i = 0; i < list->nbItems; i++) { ref = list->items[i]; if ((ref->type == XML_SCHEMA_EXTRA_QNAMEREF) && (ref->itemType == XML_SCHEMA_TYPE_ATTRIBUTEGROUP) && (ref->item != NULL)) { gr = WXS_ATTR_GROUP_CAST ref->item; if (gr == ctxtGr) return(ref); if (gr->flags & XML_SCHEMAS_ATTRGROUP_MARKED) continue; /* * Mark as visited to avoid infinite recursion on * circular references not yet examined. */ if ((gr->attrUses) && (gr->flags & XML_SCHEMAS_ATTRGROUP_HAS_REFS)) { gr->flags |= XML_SCHEMAS_ATTRGROUP_MARKED; circ = xmlSchemaCheckAttrGroupCircularRecur(ctxtGr, (xmlSchemaItemListPtr) gr->attrUses); gr->flags ^= XML_SCHEMAS_ATTRGROUP_MARKED; if (circ != NULL) return (circ); } } } return (NULL); } /** * xmlSchemaCheckAttrGroupCircular: * attrGr: the attribute group definition * @ctxt: the parser context * @name: the name * * Checks for circular references of attribute groups. */ static int xmlSchemaCheckAttrGroupCircular(xmlSchemaAttributeGroupPtr attrGr, xmlSchemaParserCtxtPtr ctxt) { /* * Schema Representation Constraint: * Attribute Group Definition Representation OK * 3 Circular group reference is disallowed outside <redefine>. * That is, unless this element information item's parent is * <redefine>, then among the [children], if any, there must * not be an <attributeGroup> with ref [attribute] which resolves * to the component corresponding to this <attributeGroup>. Indirect * circularity is also ruled out. That is, when QName resolution * (Schema Document) ($3.15.3) is applied to a `QName` arising from * any <attributeGroup>s with a ref [attribute] among the [children], * it must not be the case that a `QName` is encountered at any depth * which resolves to the component corresponding to this <attributeGroup>. */ if (attrGr->attrUses == NULL) return(0); else if ((attrGr->flags & XML_SCHEMAS_ATTRGROUP_HAS_REFS) == 0) return(0); else { xmlSchemaQNameRefPtr circ; circ = xmlSchemaCheckAttrGroupCircularRecur(attrGr, (xmlSchemaItemListPtr) attrGr->attrUses); if (circ != NULL) { xmlChar *str = NULL; /* * TODO: Report the referenced attr group as QName. */ xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_SRC_ATTRIBUTE_GROUP_3, NULL, WXS_ITEM_NODE(WXS_BASIC_CAST circ), "Circular reference to the attribute group '%s' " "defined", xmlSchemaGetComponentQName(&str, attrGr)); FREE_AND_NULL(str); /* * NOTE: We will cut the reference to avoid further * confusion of the processor. * BADSPEC TODO: The spec should define how to process in this case. */ circ->item = NULL; return(ctxt->err); } } return(0); } static int xmlSchemaAttributeGroupExpandRefs(xmlSchemaParserCtxtPtr pctxt, xmlSchemaAttributeGroupPtr attrGr); /** * xmlSchemaExpandAttributeGroupRefs: * @pctxt: the parser context * @node: the node of the component holding the attribute uses * @completeWild: the intersected wildcard to be returned * @list: the attribute uses * * Substitutes contained attribute group references * for their attribute uses. Wildcards are intersected. * Attribute use prohibitions are removed from the list * and returned via the @prohibs list. * Pointlessness of attr. prohibs, if a matching attr. decl * is existent a well, are checked. */ static int xmlSchemaExpandAttributeGroupRefs(xmlSchemaParserCtxtPtr pctxt, xmlSchemaBasicItemPtr item, xmlSchemaWildcardPtr *completeWild, xmlSchemaItemListPtr list, xmlSchemaItemListPtr prohibs) { xmlSchemaAttributeGroupPtr gr; xmlSchemaAttributeUsePtr use; xmlSchemaItemListPtr sublist; int i, j; int created = (*completeWild == NULL) ? 0 : 1; if (prohibs) prohibs->nbItems = 0; for (i = 0; i < list->nbItems; i++) { use = list->items[i]; if (use->type == XML_SCHEMA_EXTRA_ATTR_USE_PROHIB) { if (prohibs == NULL) { PERROR_INT("xmlSchemaExpandAttributeGroupRefs", "unexpected attr prohibition found"); return(-1); } /* * Remove from attribute uses. */ if (xmlSchemaItemListRemove(list, i) == -1) return(-1); i--; /* * Note that duplicate prohibitions were already * handled at parsing time. */ /* * Add to list of prohibitions. */ xmlSchemaItemListAddSize(prohibs, 2, use); continue; } if ((use->type == XML_SCHEMA_EXTRA_QNAMEREF) && ((WXS_QNAME_CAST use)->itemType == XML_SCHEMA_TYPE_ATTRIBUTEGROUP)) { if ((WXS_QNAME_CAST use)->item == NULL) return(-1); gr = WXS_ATTR_GROUP_CAST (WXS_QNAME_CAST use)->item; /* * Expand the referenced attr. group. * TODO: remove this, this is done in a previous step, so * already done here. */ if ((gr->flags & XML_SCHEMAS_ATTRGROUP_WILDCARD_BUILDED) == 0) { if (xmlSchemaAttributeGroupExpandRefs(pctxt, gr) == -1) return(-1); } /* * Build the 'complete' wildcard; i.e. intersect multiple * wildcards. */ if (gr->attributeWildcard != NULL) { if (*completeWild == NULL) { *completeWild = gr->attributeWildcard; } else { if (! created) { xmlSchemaWildcardPtr tmpWild; /* * Copy the first encountered wildcard as context, * except for the annotation. * * Although the complete wildcard might not correspond * to any node in the schema, we will anchor it on * the node of the owner component. */ tmpWild = xmlSchemaAddWildcard(pctxt, pctxt->schema, XML_SCHEMA_TYPE_ANY_ATTRIBUTE, WXS_ITEM_NODE(item)); if (tmpWild == NULL) return(-1); if (xmlSchemaCloneWildcardNsConstraints(pctxt, tmpWild, *completeWild) == -1) return (-1); tmpWild->processContents = (*completeWild)->processContents; *completeWild = tmpWild; created = 1; } if (xmlSchemaIntersectWildcards(pctxt, *completeWild, gr->attributeWildcard) == -1) return(-1); } } /* * Just remove the reference if the referenced group does not * contain any attribute uses. */ sublist = ((xmlSchemaItemListPtr) gr->attrUses); if ((sublist == NULL) || sublist->nbItems == 0) { if (xmlSchemaItemListRemove(list, i) == -1) return(-1); i--; continue; } /* * Add the attribute uses. */ list->items[i] = sublist->items[0]; if (sublist->nbItems != 1) { for (j = 1; j < sublist->nbItems; j++) { i++; if (xmlSchemaItemListInsert(list, sublist->items[j], i) == -1) return(-1); } } } } /* * Handle pointless prohibitions of declared attributes. */ if (prohibs && (prohibs->nbItems != 0) && (list->nbItems != 0)) { xmlSchemaAttributeUseProhibPtr prohib; for (i = prohibs->nbItems -1; i >= 0; i--) { prohib = prohibs->items[i]; for (j = 0; j < list->nbItems; j++) { use = list->items[j]; if ((prohib->name == WXS_ATTRUSE_DECL_NAME(use)) && (prohib->targetNamespace == WXS_ATTRUSE_DECL_TNS(use))) { xmlChar *str = NULL; xmlSchemaCustomWarning(ACTXT_CAST pctxt, XML_SCHEMAP_WARN_ATTR_POINTLESS_PROH, prohib->node, NULL, "Skipping pointless attribute use prohibition " "'%s', since a corresponding attribute use " "exists already in the type definition", xmlSchemaFormatQName(&str, prohib->targetNamespace, prohib->name), NULL, NULL); FREE_AND_NULL(str); /* * Remove the prohibition. */ if (xmlSchemaItemListRemove(prohibs, i) == -1) return(-1); break; } } } } return(0); } /** * xmlSchemaAttributeGroupExpandRefs: * @pctxt: the parser context * @attrGr: the attribute group definition * * Computation of: * {attribute uses} property * {attribute wildcard} property * * Substitutes contained attribute group references * for their attribute uses. Wildcards are intersected. */ static int xmlSchemaAttributeGroupExpandRefs(xmlSchemaParserCtxtPtr pctxt, xmlSchemaAttributeGroupPtr attrGr) { if ((attrGr->attrUses == NULL) || (attrGr->flags & XML_SCHEMAS_ATTRGROUP_WILDCARD_BUILDED)) return(0); attrGr->flags |= XML_SCHEMAS_ATTRGROUP_WILDCARD_BUILDED; if (xmlSchemaExpandAttributeGroupRefs(pctxt, WXS_BASIC_CAST attrGr, &(attrGr->attributeWildcard), attrGr->attrUses, NULL) == -1) return(-1); return(0); } /** * xmlSchemaAttributeGroupExpandRefs: * @pctxt: the parser context * @attrGr: the attribute group definition * * Substitutes contained attribute group references * for their attribute uses. Wildcards are intersected. * * Schema Component Constraint: * Attribute Group Definition Properties Correct (ag-props-correct) */ static int xmlSchemaCheckAGPropsCorrect(xmlSchemaParserCtxtPtr pctxt, xmlSchemaAttributeGroupPtr attrGr) { /* * SPEC ag-props-correct * (1) "The values of the properties of an attribute group definition * must be as described in the property tableau in The Attribute * Group Definition Schema Component ($3.6.1), modulo the impact of * Missing Sub-components ($5.3);" */ if ((attrGr->attrUses != NULL) && (WXS_LIST_CAST attrGr->attrUses)->nbItems > 1) { xmlSchemaItemListPtr uses = WXS_LIST_CAST attrGr->attrUses; xmlSchemaAttributeUsePtr use, tmp; int i, j, hasId = 0; for (i = uses->nbItems -1; i >= 0; i--) { use = uses->items[i]; /* * SPEC ag-props-correct * (2) "Two distinct members of the {attribute uses} must not have * {attribute declaration}s both of whose {name}s match and whose * {target namespace}s are identical." */ if (i > 0) { for (j = i -1; j >= 0; j--) { tmp = uses->items[j]; if ((WXS_ATTRUSE_DECL_NAME(use) == WXS_ATTRUSE_DECL_NAME(tmp)) && (WXS_ATTRUSE_DECL_TNS(use) == WXS_ATTRUSE_DECL_TNS(tmp))) { xmlChar *str = NULL; xmlSchemaCustomErr(ACTXT_CAST pctxt, XML_SCHEMAP_AG_PROPS_CORRECT, attrGr->node, WXS_BASIC_CAST attrGr, "Duplicate %s", xmlSchemaGetComponentDesignation(&str, use), NULL); FREE_AND_NULL(str); /* * Remove the duplicate. */ if (xmlSchemaItemListRemove(uses, i) == -1) return(-1); goto next_use; } } } /* * SPEC ag-props-correct * (3) "Two distinct members of the {attribute uses} must not have * {attribute declaration}s both of whose {type definition}s are or * are derived from ID." * TODO: Does 'derived' include member-types of unions? */ if (WXS_ATTRUSE_TYPEDEF(use) != NULL) { if (xmlSchemaIsDerivedFromBuiltInType( WXS_ATTRUSE_TYPEDEF(use), XML_SCHEMAS_ID)) { if (hasId) { xmlChar *str = NULL; xmlSchemaCustomErr(ACTXT_CAST pctxt, XML_SCHEMAP_AG_PROPS_CORRECT, attrGr->node, WXS_BASIC_CAST attrGr, "There must not exist more than one attribute " "declaration of type 'xs:ID' " "(or derived from 'xs:ID'). The %s violates this " "constraint", xmlSchemaGetComponentDesignation(&str, use), NULL); FREE_AND_NULL(str); if (xmlSchemaItemListRemove(uses, i) == -1) return(-1); } hasId = 1; } } next_use: {} } } return(0); } /** * xmlSchemaResolveAttrGroupReferences: * @attrgrpDecl: the schema attribute definition * @ctxt: the schema parser context * @name: the attribute name * * Resolves references to attribute group definitions. */ static int xmlSchemaResolveAttrGroupReferences(xmlSchemaQNameRefPtr ref, xmlSchemaParserCtxtPtr ctxt) { xmlSchemaAttributeGroupPtr group; if (ref->item != NULL) return(0); group = xmlSchemaGetAttributeGroup(ctxt->schema, ref->name, ref->targetNamespace); if (group == NULL) { xmlSchemaPResCompAttrErr(ctxt, XML_SCHEMAP_SRC_RESOLVE, NULL, ref->node, "ref", ref->name, ref->targetNamespace, ref->itemType, NULL); return(ctxt->err); } ref->item = WXS_BASIC_CAST group; return(0); } /** * xmlSchemaCheckAttrPropsCorrect: * @item: an schema attribute declaration/use * @ctxt: a schema parser context * @name: the name of the attribute * * * Schema Component Constraint: * Attribute Declaration Properties Correct (a-props-correct) * * Validates the value constraints of an attribute declaration/use. * NOTE that this needs the simple type definitions to be already * built and checked. */ static int xmlSchemaCheckAttrPropsCorrect(xmlSchemaParserCtxtPtr pctxt, xmlSchemaAttributePtr attr) { /* * SPEC a-props-correct (1) * "The values of the properties of an attribute declaration must * be as described in the property tableau in The Attribute * Declaration Schema Component ($3.2.1), modulo the impact of * Missing Sub-components ($5.3)." */ if (WXS_ATTR_TYPEDEF(attr) == NULL) return(0); if (attr->defValue != NULL) { int ret; /* * SPEC a-props-correct (3) * "If the {type definition} is or is derived from ID then there * must not be a {value constraint}." */ if (xmlSchemaIsDerivedFromBuiltInType( WXS_ATTR_TYPEDEF(attr), XML_SCHEMAS_ID)) { xmlSchemaCustomErr(ACTXT_CAST pctxt, XML_SCHEMAP_A_PROPS_CORRECT_3, NULL, WXS_BASIC_CAST attr, "Value constraints are not allowed if the type definition " "is or is derived from xs:ID", NULL, NULL); return(pctxt->err); } /* * SPEC a-props-correct (2) * "if there is a {value constraint}, the canonical lexical * representation of its value must be `valid` with respect * to the {type definition} as defined in String Valid ($3.14.4)." * TODO: Don't care about the *canonical* stuff here, this requirement * will be removed in WXS 1.1 anyway. */ ret = xmlSchemaVCheckCVCSimpleType(ACTXT_CAST pctxt, attr->node, WXS_ATTR_TYPEDEF(attr), attr->defValue, &(attr->defVal), 1, 1, 0); if (ret != 0) { if (ret < 0) { PERROR_INT("xmlSchemaCheckAttrPropsCorrect", "calling xmlSchemaVCheckCVCSimpleType()"); return(-1); } xmlSchemaCustomErr(ACTXT_CAST pctxt, XML_SCHEMAP_A_PROPS_CORRECT_2, NULL, WXS_BASIC_CAST attr, "The value of the value constraint is not valid", NULL, NULL); return(pctxt->err); } } return(0); } static xmlSchemaElementPtr xmlSchemaCheckSubstGroupCircular(xmlSchemaElementPtr elemDecl, xmlSchemaElementPtr ancestor) { xmlSchemaElementPtr ret; if (WXS_SUBST_HEAD(ancestor) == NULL) return (NULL); if (WXS_SUBST_HEAD(ancestor) == elemDecl) return (ancestor); if (WXS_SUBST_HEAD(ancestor)->flags & XML_SCHEMAS_ELEM_CIRCULAR) return (NULL); WXS_SUBST_HEAD(ancestor)->flags |= XML_SCHEMAS_ELEM_CIRCULAR; ret = xmlSchemaCheckSubstGroupCircular(elemDecl, WXS_SUBST_HEAD(ancestor)); WXS_SUBST_HEAD(ancestor)->flags ^= XML_SCHEMAS_ELEM_CIRCULAR; return (ret); } /** * xmlSchemaCheckElemPropsCorrect: * @ctxt: a schema parser context * @decl: the element declaration * @name: the name of the attribute * * Schema Component Constraint: * Element Declaration Properties Correct (e-props-correct) * * STATUS: * missing: (6) */ static int xmlSchemaCheckElemPropsCorrect(xmlSchemaParserCtxtPtr pctxt, xmlSchemaElementPtr elemDecl) { int ret = 0; xmlSchemaTypePtr typeDef = WXS_ELEM_TYPEDEF(elemDecl); /* * SPEC (1) "The values of the properties of an element declaration * must be as described in the property tableau in The Element * Declaration Schema Component ($3.3.1), modulo the impact of Missing * Sub-components ($5.3)." */ if (WXS_SUBST_HEAD(elemDecl) != NULL) { xmlSchemaElementPtr head = WXS_SUBST_HEAD(elemDecl), circ; xmlSchemaCheckElementDeclComponent(head, pctxt); /* * SPEC (3) "If there is a non-`absent` {substitution group * affiliation}, then {scope} must be global." */ if ((elemDecl->flags & XML_SCHEMAS_ELEM_GLOBAL) == 0) { xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_E_PROPS_CORRECT_3, WXS_BASIC_CAST elemDecl, NULL, "Only global element declarations can have a " "substitution group affiliation", NULL); ret = XML_SCHEMAP_E_PROPS_CORRECT_3; } /* * TODO: SPEC (6) "Circular substitution groups are disallowed. * That is, it must not be possible to return to an element declaration * by repeatedly following the {substitution group affiliation} * property." */ if (head == elemDecl) circ = head; else if (WXS_SUBST_HEAD(head) != NULL) circ = xmlSchemaCheckSubstGroupCircular(head, head); else circ = NULL; if (circ != NULL) { xmlChar *strA = NULL, *strB = NULL; xmlSchemaPCustomErrExt(pctxt, XML_SCHEMAP_E_PROPS_CORRECT_6, WXS_BASIC_CAST circ, NULL, "The element declaration '%s' defines a circular " "substitution group to element declaration '%s'", xmlSchemaGetComponentQName(&strA, circ), xmlSchemaGetComponentQName(&strB, head), NULL); FREE_AND_NULL(strA) FREE_AND_NULL(strB) ret = XML_SCHEMAP_E_PROPS_CORRECT_6; } /* * SPEC (4) "If there is a {substitution group affiliation}, * the {type definition} * of the element declaration must be validly derived from the {type * definition} of the {substitution group affiliation}, given the value * of the {substitution group exclusions} of the {substitution group * affiliation}, as defined in Type Derivation OK (Complex) ($3.4.6) * (if the {type definition} is complex) or as defined in * Type Derivation OK (Simple) ($3.14.6) (if the {type definition} is * simple)." * * NOTE: {substitution group exclusions} means the values of the * attribute "final". */ if (typeDef != WXS_ELEM_TYPEDEF(WXS_SUBST_HEAD(elemDecl))) { int set = 0; if (head->flags & XML_SCHEMAS_ELEM_FINAL_EXTENSION) set |= SUBSET_EXTENSION; if (head->flags & XML_SCHEMAS_ELEM_FINAL_RESTRICTION) set |= SUBSET_RESTRICTION; if (xmlSchemaCheckCOSDerivedOK(ACTXT_CAST pctxt, typeDef, WXS_ELEM_TYPEDEF(head), set) != 0) { xmlChar *strA = NULL, *strB = NULL, *strC = NULL; ret = XML_SCHEMAP_E_PROPS_CORRECT_4; xmlSchemaPCustomErrExt(pctxt, XML_SCHEMAP_E_PROPS_CORRECT_4, WXS_BASIC_CAST elemDecl, NULL, "The type definition '%s' was " "either rejected by the substitution group " "affiliation '%s', or not validly derived from its type " "definition '%s'", xmlSchemaGetComponentQName(&strA, typeDef), xmlSchemaGetComponentQName(&strB, head), xmlSchemaGetComponentQName(&strC, WXS_ELEM_TYPEDEF(head))); FREE_AND_NULL(strA) FREE_AND_NULL(strB) FREE_AND_NULL(strC) } } } /* * SPEC (5) "If the {type definition} or {type definition}'s * {content type} * is or is derived from ID then there must not be a {value constraint}. * Note: The use of ID as a type definition for elements goes beyond * XML 1.0, and should be avoided if backwards compatibility is desired" */ if ((elemDecl->value != NULL) && ((WXS_IS_SIMPLE(typeDef) && xmlSchemaIsDerivedFromBuiltInType(typeDef, XML_SCHEMAS_ID)) || (WXS_IS_COMPLEX(typeDef) && WXS_HAS_SIMPLE_CONTENT(typeDef) && xmlSchemaIsDerivedFromBuiltInType(typeDef->contentTypeDef, XML_SCHEMAS_ID)))) { ret = XML_SCHEMAP_E_PROPS_CORRECT_5; xmlSchemaPCustomErr(pctxt, XML_SCHEMAP_E_PROPS_CORRECT_5, WXS_BASIC_CAST elemDecl, NULL, "The type definition (or type definition's content type) is or " "is derived from ID; value constraints are not allowed in " "conjunction with such a type definition", NULL); } else if (elemDecl->value != NULL) { int vcret; xmlNodePtr node = NULL; /* * SPEC (2) "If there is a {value constraint}, the canonical lexical * representation of its value must be `valid` with respect to the * {type definition} as defined in Element Default Valid (Immediate) * ($3.3.6)." */ if (typeDef == NULL) { xmlSchemaPErr(pctxt, elemDecl->node, XML_SCHEMAP_INTERNAL, "Internal error: xmlSchemaCheckElemPropsCorrect, " "type is missing... skipping validation of " "the value constraint", NULL, NULL); return (-1); } if (elemDecl->node != NULL) { if (elemDecl->flags & XML_SCHEMAS_ELEM_FIXED) node = (xmlNodePtr) xmlHasProp(elemDecl->node, BAD_CAST "fixed"); else node = (xmlNodePtr) xmlHasProp(elemDecl->node, BAD_CAST "default"); } vcret = xmlSchemaParseCheckCOSValidDefault(pctxt, node, typeDef, elemDecl->value, &(elemDecl->defVal)); if (vcret != 0) { if (vcret < 0) { PERROR_INT("xmlSchemaElemCheckValConstr", "failed to validate the value constraint of an " "element declaration"); return (-1); } return (vcret); } } return (ret); } /** * xmlSchemaCheckElemSubstGroup: * @ctxt: a schema parser context * @decl: the element declaration * @name: the name of the attribute * * Schema Component Constraint: * Substitution Group (cos-equiv-class) * * In Libxml2 the subst. groups will be precomputed, in terms of that * a list will be built for each subst. group head, holding all direct * referents to this head. * NOTE that this function needs: * 1. circular subst. groups to be checked beforehand * 2. the declaration's type to be derived from the head's type * * STATUS: * */ static void xmlSchemaCheckElemSubstGroup(xmlSchemaParserCtxtPtr ctxt, xmlSchemaElementPtr elemDecl) { if ((WXS_SUBST_HEAD(elemDecl) == NULL) || /* SPEC (1) "Its {abstract} is false." */ (elemDecl->flags & XML_SCHEMAS_ELEM_ABSTRACT)) return; { xmlSchemaElementPtr head; xmlSchemaTypePtr headType, type; int set, methSet; /* * SPEC (2) "It is validly substitutable for HEAD subject to HEAD's * {disallowed substitutions} as the blocking constraint, as defined in * Substitution Group OK (Transitive) ($3.3.6)." */ for (head = WXS_SUBST_HEAD(elemDecl); head != NULL; head = WXS_SUBST_HEAD(head)) { set = 0; methSet = 0; /* * The blocking constraints. */ if (head->flags & XML_SCHEMAS_ELEM_BLOCK_SUBSTITUTION) continue; headType = head->subtypes; type = elemDecl->subtypes; if (headType == type) goto add_member; if (head->flags & XML_SCHEMAS_ELEM_BLOCK_RESTRICTION) set |= XML_SCHEMAS_TYPE_BLOCK_RESTRICTION; if (head->flags & XML_SCHEMAS_ELEM_BLOCK_EXTENSION) set |= XML_SCHEMAS_TYPE_BLOCK_EXTENSION; /* * SPEC: Substitution Group OK (Transitive) (2.3) * "The set of all {derivation method}s involved in the * derivation of D's {type definition} from C's {type definition} * does not intersect with the union of the blocking constraint, * C's {prohibited substitutions} (if C is complex, otherwise the * empty set) and the {prohibited substitutions} (respectively the * empty set) of any intermediate {type definition}s in the * derivation of D's {type definition} from C's {type definition}." */ /* * OPTIMIZE TODO: Optimize this a bit, since, if traversing the * subst.head axis, the methSet does not need to be computed for * the full depth over and over. */ /* * The set of all {derivation method}s involved in the derivation */ while ((type != NULL) && (type != headType)) { if ((WXS_IS_EXTENSION(type)) && ((methSet & XML_SCHEMAS_TYPE_BLOCK_RESTRICTION) == 0)) methSet |= XML_SCHEMAS_TYPE_BLOCK_EXTENSION; if (WXS_IS_RESTRICTION(type) && ((methSet & XML_SCHEMAS_TYPE_BLOCK_RESTRICTION) == 0)) methSet |= XML_SCHEMAS_TYPE_BLOCK_RESTRICTION; type = type->baseType; } /* * The {prohibited substitutions} of all intermediate types + * the head's type. */ type = elemDecl->subtypes->baseType; while (type != NULL) { if (WXS_IS_COMPLEX(type)) { if ((type->flags & XML_SCHEMAS_TYPE_BLOCK_EXTENSION) && ((set & XML_SCHEMAS_TYPE_BLOCK_EXTENSION) == 0)) set |= XML_SCHEMAS_TYPE_BLOCK_EXTENSION; if ((type->flags & XML_SCHEMAS_TYPE_BLOCK_RESTRICTION) && ((set & XML_SCHEMAS_TYPE_BLOCK_RESTRICTION) == 0)) set |= XML_SCHEMAS_TYPE_BLOCK_RESTRICTION; } else break; if (type == headType) break; type = type->baseType; } if ((set != 0) && (((set & XML_SCHEMAS_TYPE_BLOCK_EXTENSION) && (methSet & XML_SCHEMAS_TYPE_BLOCK_EXTENSION)) || ((set & XML_SCHEMAS_TYPE_BLOCK_RESTRICTION) && (methSet & XML_SCHEMAS_TYPE_BLOCK_RESTRICTION)))) { continue; } add_member: xmlSchemaAddElementSubstitutionMember(ctxt, head, elemDecl); if ((head->flags & XML_SCHEMAS_ELEM_SUBST_GROUP_HEAD) == 0) head->flags |= XML_SCHEMAS_ELEM_SUBST_GROUP_HEAD; } } } #ifdef WXS_ELEM_DECL_CONS_ENABLED /* enable when finished */ /** * xmlSchemaCheckElementDeclComponent * @pctxt: the schema parser context * @ctxtComponent: the context component (an element declaration) * @ctxtParticle: the first particle of the context component * @searchParticle: the element declaration particle to be analysed * * Schema Component Constraint: Element Declarations Consistent */ static int xmlSchemaCheckElementDeclConsistent(xmlSchemaParserCtxtPtr pctxt, xmlSchemaBasicItemPtr ctxtComponent, xmlSchemaParticlePtr ctxtParticle, xmlSchemaParticlePtr searchParticle, xmlSchemaParticlePtr curParticle, int search) { return(0); int ret = 0; xmlSchemaParticlePtr cur = curParticle; if (curParticle == NULL) { return(0); } if (WXS_PARTICLE_TERM(curParticle) == NULL) { /* * Just return in this case. A missing "term" of the particle * might arise due to an invalid "term" component. */ return(0); } while (cur != NULL) { switch (WXS_PARTICLE_TERM(cur)->type) { case XML_SCHEMA_TYPE_ANY: break; case XML_SCHEMA_TYPE_ELEMENT: if (search == 0) { ret = xmlSchemaCheckElementDeclConsistent(pctxt, ctxtComponent, ctxtParticle, cur, ctxtParticle, 1); if (ret != 0) return(ret); } else { xmlSchemaElementPtr elem = WXS_ELEM_CAST(WXS_PARTICLE_TERM(cur)); /* * SPEC Element Declarations Consistent: * "If the {particles} contains, either directly, * indirectly (that is, within the {particles} of a * contained model group, recursively) or `implicitly` * two or more element declaration particles with * the same {name} and {target namespace}, then * all their type definitions must be the same * top-level definition [...]" */ if (xmlStrEqual(WXS_PARTICLE_TERM_AS_ELEM(cur)->name, WXS_PARTICLE_TERM_AS_ELEM(searchParticle)->name) && xmlStrEqual(WXS_PARTICLE_TERM_AS_ELEM(cur)->targetNamespace, WXS_PARTICLE_TERM_AS_ELEM(searchParticle)->targetNamespace)) { xmlChar *strA = NULL, *strB = NULL; xmlSchemaCustomErr(ACTXT_CAST pctxt, /* TODO: error code */ XML_SCHEMAP_COS_NONAMBIG, WXS_ITEM_NODE(cur), NULL, "In the content model of %s, there are multiple " "element declarations for '%s' with different " "type definitions", xmlSchemaGetComponentDesignation(&strA, ctxtComponent), xmlSchemaFormatQName(&strB, WXS_PARTICLE_TERM_AS_ELEM(cur)->targetNamespace, WXS_PARTICLE_TERM_AS_ELEM(cur)->name)); FREE_AND_NULL(strA); FREE_AND_NULL(strB); return(XML_SCHEMAP_COS_NONAMBIG); } } break; case XML_SCHEMA_TYPE_SEQUENCE: { break; } case XML_SCHEMA_TYPE_CHOICE:{ /* xmlSchemaTreeItemPtr sub; sub = WXS_PARTICLE_TERM(particle)->children; (xmlSchemaParticlePtr) while (sub != NULL) { ret = xmlSchemaCheckElementDeclConsistent(pctxt, ctxtComponent, ctxtParticle, ctxtElem); if (ret != 0) return(ret); sub = sub->next; } */ break; } case XML_SCHEMA_TYPE_ALL: break; case XML_SCHEMA_TYPE_GROUP: break; default: xmlSchemaInternalErr2(ACTXT_CAST pctxt, "xmlSchemaCheckElementDeclConsistent", "found unexpected term of type '%s' in content model", WXS_ITEM_TYPE_NAME(WXS_PARTICLE_TERM(cur)), NULL); return(-1); } cur = (xmlSchemaParticlePtr) cur->next; } exit: return(ret); } #endif /** * xmlSchemaCheckElementDeclComponent * @item: an schema element declaration/particle * @ctxt: a schema parser context * @name: the name of the attribute * * Validates the value constraints of an element declaration. * Adds substitution group members. */ static void xmlSchemaCheckElementDeclComponent(xmlSchemaElementPtr elemDecl, xmlSchemaParserCtxtPtr ctxt) { if (elemDecl == NULL) return; if (elemDecl->flags & XML_SCHEMAS_ELEM_INTERNAL_CHECKED) return; elemDecl->flags |= XML_SCHEMAS_ELEM_INTERNAL_CHECKED; if (xmlSchemaCheckElemPropsCorrect(ctxt, elemDecl) == 0) { /* * Adds substitution group members. */ xmlSchemaCheckElemSubstGroup(ctxt, elemDecl); } } /** * xmlSchemaResolveModelGroupParticleReferences: * @particle: a particle component * @ctxt: a parser context * * Resolves references of a model group's {particles} to * model group definitions and to element declarations. */ static void xmlSchemaResolveModelGroupParticleReferences( xmlSchemaParserCtxtPtr ctxt, xmlSchemaModelGroupPtr mg) { xmlSchemaParticlePtr particle = WXS_MODELGROUP_PARTICLE(mg); xmlSchemaQNameRefPtr ref; xmlSchemaBasicItemPtr refItem; /* * URGENT TODO: Test this. */ while (particle != NULL) { if ((WXS_PARTICLE_TERM(particle) == NULL) || ((WXS_PARTICLE_TERM(particle))->type != XML_SCHEMA_EXTRA_QNAMEREF)) { goto next_particle; } ref = WXS_QNAME_CAST WXS_PARTICLE_TERM(particle); /* * Resolve the reference. * NULL the {term} by default. */ particle->children = NULL; refItem = xmlSchemaGetNamedComponent(ctxt->schema, ref->itemType, ref->name, ref->targetNamespace); if (refItem == NULL) { xmlSchemaPResCompAttrErr(ctxt, XML_SCHEMAP_SRC_RESOLVE, NULL, WXS_ITEM_NODE(particle), "ref", ref->name, ref->targetNamespace, ref->itemType, NULL); /* TODO: remove the particle. */ goto next_particle; } if (refItem->type == XML_SCHEMA_TYPE_GROUP) { if (WXS_MODELGROUPDEF_MODEL(refItem) == NULL) /* TODO: remove the particle. */ goto next_particle; /* * NOTE that we will assign the model group definition * itself to the "term" of the particle. This will ease * the check for circular model group definitions. After * that the "term" will be assigned the model group of the * model group definition. */ if ((WXS_MODELGROUPDEF_MODEL(refItem))->type == XML_SCHEMA_TYPE_ALL) { /* * SPEC cos-all-limited (1) * SPEC cos-all-limited (1.2) * "It appears only as the value of one or both of the * following properties:" * (1.1) "the {model group} property of a model group * definition." * (1.2) "the {term} property of a particle [... of] the " * {content type} of a complex type definition." */ xmlSchemaCustomErr(ACTXT_CAST ctxt, /* TODO: error code */ XML_SCHEMAP_COS_ALL_LIMITED, WXS_ITEM_NODE(particle), NULL, "A model group definition is referenced, but " "it contains an 'all' model group, which " "cannot be contained by model groups", NULL, NULL); /* TODO: remove the particle. */ goto next_particle; } particle->children = (xmlSchemaTreeItemPtr) refItem; } else { /* * TODO: Are referenced element declarations the only * other components we expect here? */ particle->children = (xmlSchemaTreeItemPtr) refItem; } next_particle: particle = WXS_PTC_CAST particle->next; } } static int xmlSchemaAreValuesEqual(xmlSchemaValPtr x, xmlSchemaValPtr y) { xmlSchemaTypePtr tx, ty, ptx, pty; int ret; while (x != NULL) { /* Same types. */ tx = xmlSchemaGetBuiltInType(xmlSchemaGetValType(x)); ty = xmlSchemaGetBuiltInType(xmlSchemaGetValType(y)); ptx = xmlSchemaGetPrimitiveType(tx); pty = xmlSchemaGetPrimitiveType(ty); /* * (1) if a datatype T' is `derived` by `restriction` from an * atomic datatype T then the `value space` of T' is a subset of * the `value space` of T. */ /* * (2) if datatypes T' and T'' are `derived` by `restriction` * from a common atomic ancestor T then the `value space`s of T' * and T'' may overlap. */ if (ptx != pty) return(0); /* * We assume computed values to be normalized, so do a fast * string comparison for string based types. */ if ((ptx->builtInType == XML_SCHEMAS_STRING) || WXS_IS_ANY_SIMPLE_TYPE(ptx)) { if (! xmlStrEqual( xmlSchemaValueGetAsString(x), xmlSchemaValueGetAsString(y))) return (0); } else { ret = xmlSchemaCompareValuesWhtsp( x, XML_SCHEMA_WHITESPACE_PRESERVE, y, XML_SCHEMA_WHITESPACE_PRESERVE); if (ret == -2) return(-1); if (ret != 0) return(0); } /* * Lists. */ x = xmlSchemaValueGetNext(x); if (x != NULL) { y = xmlSchemaValueGetNext(y); if (y == NULL) return (0); } else if (xmlSchemaValueGetNext(y) != NULL) return (0); else return (1); } return (0); } /** * xmlSchemaResolveAttrUseReferences: * @item: an attribute use * @ctxt: a parser context * * Resolves the referenced attribute declaration. */ static int xmlSchemaResolveAttrUseReferences(xmlSchemaAttributeUsePtr ause, xmlSchemaParserCtxtPtr ctxt) { if ((ctxt == NULL) || (ause == NULL)) return(-1); if ((ause->attrDecl == NULL) || (ause->attrDecl->type != XML_SCHEMA_EXTRA_QNAMEREF)) return(0); { xmlSchemaQNameRefPtr ref = WXS_QNAME_CAST ause->attrDecl; /* * TODO: Evaluate, what errors could occur if the declaration is not * found. */ ause->attrDecl = xmlSchemaGetAttributeDecl(ctxt->schema, ref->name, ref->targetNamespace); if (ause->attrDecl == NULL) { xmlSchemaPResCompAttrErr(ctxt, XML_SCHEMAP_SRC_RESOLVE, WXS_BASIC_CAST ause, ause->node, "ref", ref->name, ref->targetNamespace, XML_SCHEMA_TYPE_ATTRIBUTE, NULL); return(ctxt->err);; } } return(0); } /** * xmlSchemaCheckAttrUsePropsCorrect: * @ctxt: a parser context * @use: an attribute use * * Schema Component Constraint: * Attribute Use Correct (au-props-correct) * */ static int xmlSchemaCheckAttrUsePropsCorrect(xmlSchemaParserCtxtPtr ctxt, xmlSchemaAttributeUsePtr use) { if ((ctxt == NULL) || (use == NULL)) return(-1); if ((use->defValue == NULL) || (WXS_ATTRUSE_DECL(use) == NULL) || ((WXS_ATTRUSE_DECL(use))->type != XML_SCHEMA_TYPE_ATTRIBUTE)) return(0); /* * SPEC au-props-correct (1) * "The values of the properties of an attribute use must be as * described in the property tableau in The Attribute Use Schema * Component ($3.5.1), modulo the impact of Missing * Sub-components ($5.3)." */ if (((WXS_ATTRUSE_DECL(use))->defValue != NULL) && ((WXS_ATTRUSE_DECL(use))->flags & XML_SCHEMAS_ATTR_FIXED) && ((use->flags & XML_SCHEMA_ATTR_USE_FIXED) == 0)) { xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_AU_PROPS_CORRECT_2, WXS_BASIC_CAST use, NULL, "The attribute declaration has a 'fixed' value constraint " ", thus the attribute use must also have a 'fixed' value " "constraint", NULL); return(ctxt->err); } /* * Compute and check the value constraint's value. */ if ((use->defVal != NULL) && (WXS_ATTRUSE_TYPEDEF(use) != NULL)) { int ret; /* * TODO: The spec seems to be missing a check of the * value constraint of the attribute use. We will do it here. */ /* * SPEC a-props-correct (3) */ if (xmlSchemaIsDerivedFromBuiltInType( WXS_ATTRUSE_TYPEDEF(use), XML_SCHEMAS_ID)) { xmlSchemaCustomErr(ACTXT_CAST ctxt, XML_SCHEMAP_AU_PROPS_CORRECT, NULL, WXS_BASIC_CAST use, "Value constraints are not allowed if the type definition " "is or is derived from xs:ID", NULL, NULL); return(ctxt->err); } ret = xmlSchemaVCheckCVCSimpleType(ACTXT_CAST ctxt, use->node, WXS_ATTRUSE_TYPEDEF(use), use->defValue, &(use->defVal), 1, 1, 0); if (ret != 0) { if (ret < 0) { PERROR_INT2("xmlSchemaCheckAttrUsePropsCorrect", "calling xmlSchemaVCheckCVCSimpleType()"); return(-1); } xmlSchemaCustomErr(ACTXT_CAST ctxt, XML_SCHEMAP_AU_PROPS_CORRECT, NULL, WXS_BASIC_CAST use, "The value of the value constraint is not valid", NULL, NULL); return(ctxt->err); } } /* * SPEC au-props-correct (2) * "If the {attribute declaration} has a fixed * {value constraint}, then if the attribute use itself has a * {value constraint}, it must also be fixed and its value must match * that of the {attribute declaration}'s {value constraint}." */ if (((WXS_ATTRUSE_DECL(use))->defVal != NULL) && (((WXS_ATTRUSE_DECL(use))->flags & XML_SCHEMA_ATTR_USE_FIXED) == 0)) { if (! xmlSchemaAreValuesEqual(use->defVal, (WXS_ATTRUSE_DECL(use))->defVal)) { xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_AU_PROPS_CORRECT_2, WXS_BASIC_CAST use, NULL, "The 'fixed' value constraint of the attribute use " "must match the attribute declaration's value " "constraint '%s'", (WXS_ATTRUSE_DECL(use))->defValue); } return(ctxt->err); } return(0); } /** * xmlSchemaResolveAttrTypeReferences: * @item: an attribute declaration * @ctxt: a parser context * * Resolves the referenced type definition component. */ static int xmlSchemaResolveAttrTypeReferences(xmlSchemaAttributePtr item, xmlSchemaParserCtxtPtr ctxt) { /* * The simple type definition corresponding to the <simpleType> element * information item in the [children], if present, otherwise the simple * type definition `resolved` to by the `actual value` of the type * [attribute], if present, otherwise the `simple ur-type definition`. */ if (item->flags & XML_SCHEMAS_ATTR_INTERNAL_RESOLVED) return(0); item->flags |= XML_SCHEMAS_ATTR_INTERNAL_RESOLVED; if (item->subtypes != NULL) return(0); if (item->typeName != NULL) { xmlSchemaTypePtr type; type = xmlSchemaGetType(ctxt->schema, item->typeName, item->typeNs); if ((type == NULL) || (! WXS_IS_SIMPLE(type))) { xmlSchemaPResCompAttrErr(ctxt, XML_SCHEMAP_SRC_RESOLVE, WXS_BASIC_CAST item, item->node, "type", item->typeName, item->typeNs, XML_SCHEMA_TYPE_SIMPLE, NULL); return(ctxt->err); } else item->subtypes = type; } else { /* * The type defaults to the xs:anySimpleType. */ item->subtypes = xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYSIMPLETYPE); } return(0); } /** * xmlSchemaResolveIDCKeyReferences: * @idc: the identity-constraint definition * @ctxt: the schema parser context * @name: the attribute name * * Resolve keyRef references to key/unique IDCs. * Schema Component Constraint: * Identity-constraint Definition Properties Correct (c-props-correct) */ static int xmlSchemaResolveIDCKeyReferences(xmlSchemaIDCPtr idc, xmlSchemaParserCtxtPtr pctxt) { if (idc->type != XML_SCHEMA_TYPE_IDC_KEYREF) return(0); if (idc->ref->name != NULL) { idc->ref->item = (xmlSchemaBasicItemPtr) xmlSchemaGetIDC(pctxt->schema, idc->ref->name, idc->ref->targetNamespace); if (idc->ref->item == NULL) { /* * TODO: It is actually not an error to fail to resolve * at this stage. BUT we need to be that strict! */ xmlSchemaPResCompAttrErr(pctxt, XML_SCHEMAP_SRC_RESOLVE, WXS_BASIC_CAST idc, idc->node, "refer", idc->ref->name, idc->ref->targetNamespace, XML_SCHEMA_TYPE_IDC_KEY, NULL); return(pctxt->err); } else if (idc->ref->item->type == XML_SCHEMA_TYPE_IDC_KEYREF) { /* * SPEC c-props-correct (1) */ xmlSchemaCustomErr(ACTXT_CAST pctxt, XML_SCHEMAP_C_PROPS_CORRECT, NULL, WXS_BASIC_CAST idc, "The keyref references a keyref", NULL, NULL); idc->ref->item = NULL; return(pctxt->err); } else { if (idc->nbFields != ((xmlSchemaIDCPtr) idc->ref->item)->nbFields) { xmlChar *str = NULL; xmlSchemaIDCPtr refer; refer = (xmlSchemaIDCPtr) idc->ref->item; /* * SPEC c-props-correct(2) * "If the {identity-constraint category} is keyref, * the cardinality of the {fields} must equal that of * the {fields} of the {referenced key}. */ xmlSchemaCustomErr(ACTXT_CAST pctxt, XML_SCHEMAP_C_PROPS_CORRECT, NULL, WXS_BASIC_CAST idc, "The cardinality of the keyref differs from the " "cardinality of the referenced key/unique '%s'", xmlSchemaFormatQName(&str, refer->targetNamespace, refer->name), NULL); FREE_AND_NULL(str) return(pctxt->err); } } } return(0); } static int xmlSchemaResolveAttrUseProhibReferences(xmlSchemaAttributeUseProhibPtr prohib, xmlSchemaParserCtxtPtr pctxt) { if (xmlSchemaGetAttributeDecl(pctxt->schema, prohib->name, prohib->targetNamespace) == NULL) { xmlSchemaPResCompAttrErr(pctxt, XML_SCHEMAP_SRC_RESOLVE, NULL, prohib->node, "ref", prohib->name, prohib->targetNamespace, XML_SCHEMA_TYPE_ATTRIBUTE, NULL); return(XML_SCHEMAP_SRC_RESOLVE); } return(0); } #define WXS_REDEFINED_TYPE(c) \ (((xmlSchemaTypePtr) item)->flags & XML_SCHEMAS_TYPE_REDEFINED) #define WXS_REDEFINED_MODEL_GROUP_DEF(c) \ (((xmlSchemaModelGroupDefPtr) item)->flags & XML_SCHEMA_MODEL_GROUP_DEF_REDEFINED) #define WXS_REDEFINED_ATTR_GROUP(c) \ (((xmlSchemaAttributeGroupPtr) item)->flags & XML_SCHEMAS_ATTRGROUP_REDEFINED) static int xmlSchemaCheckSRCRedefineFirst(xmlSchemaParserCtxtPtr pctxt) { int err = 0; xmlSchemaRedefPtr redef = WXS_CONSTRUCTOR(pctxt)->redefs; xmlSchemaBasicItemPtr prev, item; int wasRedefined; if (redef == NULL) return(0); do { item = redef->item; /* * First try to locate the redefined component in the * schema graph starting with the redefined schema. * NOTE: According to this schema bug entry: * http://lists.w3.org/Archives/Public/www-xml-schema-comments/2005OctDec/0019.html * it's not clear if the referenced component needs to originate * from the <redefine>d schema _document_ or the schema; the latter * would include all imported and included sub-schemas of the * <redefine>d schema. Currently the latter approach is used. * SUPPLEMENT: It seems that the WG moves towards the latter * approach, so we are doing it right. * */ prev = xmlSchemaFindRedefCompInGraph( redef->targetBucket, item->type, redef->refName, redef->refTargetNs); if (prev == NULL) { xmlChar *str = NULL; xmlNodePtr node; /* * SPEC src-redefine: * (6.2.1) "The `actual value` of its own name attribute plus * target namespace must successfully `resolve` to a model * group definition in I." * (7.2.1) "The `actual value` of its own name attribute plus * target namespace must successfully `resolve` to an attribute * group definition in I." * * Note that, if we are redefining with the use of references * to components, the spec assumes the src-resolve to be used; * but this won't assure that we search only *inside* the * redefined schema. */ if (redef->reference) node = WXS_ITEM_NODE(redef->reference); else node = WXS_ITEM_NODE(item); xmlSchemaCustomErr(ACTXT_CAST pctxt, /* * TODO: error code. * Probably XML_SCHEMAP_SRC_RESOLVE, if this is using the * reference kind. */ XML_SCHEMAP_SRC_REDEFINE, node, NULL, "The %s '%s' to be redefined could not be found in " "the redefined schema", WXS_ITEM_TYPE_NAME(item), xmlSchemaFormatQName(&str, redef->refTargetNs, redef->refName)); FREE_AND_NULL(str); err = pctxt->err; redef = redef->next; continue; } /* * TODO: Obtaining and setting the redefinition state is really * clumsy. */ wasRedefined = 0; switch (item->type) { case XML_SCHEMA_TYPE_COMPLEX: case XML_SCHEMA_TYPE_SIMPLE: if ((WXS_TYPE_CAST prev)->flags & XML_SCHEMAS_TYPE_REDEFINED) { wasRedefined = 1; break; } /* Mark it as redefined. */ (WXS_TYPE_CAST prev)->flags |= XML_SCHEMAS_TYPE_REDEFINED; /* * Assign the redefined type to the * base type of the redefining type. * TODO: How */ ((xmlSchemaTypePtr) item)->baseType = (xmlSchemaTypePtr) prev; break; case XML_SCHEMA_TYPE_GROUP: if ((WXS_MODEL_GROUPDEF_CAST prev)->flags & XML_SCHEMA_MODEL_GROUP_DEF_REDEFINED) { wasRedefined = 1; break; } /* Mark it as redefined. */ (WXS_MODEL_GROUPDEF_CAST prev)->flags |= XML_SCHEMA_MODEL_GROUP_DEF_REDEFINED; if (redef->reference != NULL) { /* * Overwrite the QName-reference with the * referenced model group def. */ (WXS_PTC_CAST redef->reference)->children = WXS_TREE_CAST prev; } redef->target = prev; break; case XML_SCHEMA_TYPE_ATTRIBUTEGROUP: if ((WXS_ATTR_GROUP_CAST prev)->flags & XML_SCHEMAS_ATTRGROUP_REDEFINED) { wasRedefined = 1; break; } (WXS_ATTR_GROUP_CAST prev)->flags |= XML_SCHEMAS_ATTRGROUP_REDEFINED; if (redef->reference != NULL) { /* * Assign the redefined attribute group to the * QName-reference component. * This is the easy case, since we will just * expand the redefined group. */ (WXS_QNAME_CAST redef->reference)->item = prev; redef->target = NULL; } else { /* * This is the complicated case: we need * to apply src-redefine (7.2.2) at a later * stage, i.e. when attribute group references * have been expanded and simple types have * been fixed. */ redef->target = prev; } break; default: PERROR_INT("xmlSchemaResolveRedefReferences", "Unexpected redefined component type"); return(-1); } if (wasRedefined) { xmlChar *str = NULL; xmlNodePtr node; if (redef->reference) node = WXS_ITEM_NODE(redef->reference); else node = WXS_ITEM_NODE(redef->item); xmlSchemaCustomErr(ACTXT_CAST pctxt, /* TODO: error code. */ XML_SCHEMAP_SRC_REDEFINE, node, NULL, "The referenced %s was already redefined. Multiple " "redefinition of the same component is not supported", xmlSchemaGetComponentDesignation(&str, prev), NULL); FREE_AND_NULL(str) err = pctxt->err; redef = redef->next; continue; } redef = redef->next; } while (redef != NULL); return(err); } static int xmlSchemaCheckSRCRedefineSecond(xmlSchemaParserCtxtPtr pctxt) { int err = 0; xmlSchemaRedefPtr redef = WXS_CONSTRUCTOR(pctxt)->redefs; xmlSchemaBasicItemPtr item; if (redef == NULL) return(0); do { if (redef->target == NULL) { redef = redef->next; continue; } item = redef->item; switch (item->type) { case XML_SCHEMA_TYPE_SIMPLE: case XML_SCHEMA_TYPE_COMPLEX: /* * Since the spec wants the {name} of the redefined * type to be 'absent', we'll NULL it. */ (WXS_TYPE_CAST redef->target)->name = NULL; /* * TODO: Seems like there's nothing more to do. The normal * inheritance mechanism is used. But not 100% sure. */ break; case XML_SCHEMA_TYPE_GROUP: /* * URGENT TODO: * SPEC src-redefine: * (6.2.2) "The {model group} of the model group definition * which corresponds to it per XML Representation of Model * Group Definition Schema Components ($3.7.2) must be a * `valid restriction` of the {model group} of that model * group definition in I, as defined in Particle Valid * (Restriction) ($3.9.6)." */ break; case XML_SCHEMA_TYPE_ATTRIBUTEGROUP: /* * SPEC src-redefine: * (7.2.2) "The {attribute uses} and {attribute wildcard} of * the attribute group definition which corresponds to it * per XML Representation of Attribute Group Definition Schema * Components ($3.6.2) must be `valid restrictions` of the * {attribute uses} and {attribute wildcard} of that attribute * group definition in I, as defined in clause 2, clause 3 and * clause 4 of Derivation Valid (Restriction, Complex) * ($3.4.6) (where references to the base type definition are * understood as references to the attribute group definition * in I)." */ err = xmlSchemaCheckDerivationOKRestriction2to4(pctxt, XML_SCHEMA_ACTION_REDEFINE, item, redef->target, (WXS_ATTR_GROUP_CAST item)->attrUses, (WXS_ATTR_GROUP_CAST redef->target)->attrUses, (WXS_ATTR_GROUP_CAST item)->attributeWildcard, (WXS_ATTR_GROUP_CAST redef->target)->attributeWildcard); if (err == -1) return(-1); break; default: break; } redef = redef->next; } while (redef != NULL); return(0); } static int xmlSchemaAddComponents(xmlSchemaParserCtxtPtr pctxt, xmlSchemaBucketPtr bucket) { xmlSchemaBasicItemPtr item; int err; xmlHashTablePtr *table; const xmlChar *name; int i; #define WXS_GET_GLOBAL_HASH(c, slot) { \ if (WXS_IS_BUCKET_IMPMAIN((c)->type)) \ table = &(WXS_IMPBUCKET((c))->schema->slot); \ else \ table = &(WXS_INCBUCKET((c))->ownerImport->schema->slot); } /* * Add global components to the schema's hash tables. * This is the place where duplicate components will be * detected. * TODO: I think normally we should support imports of the * same namespace from multiple locations. We don't do currently, * but if we do then according to: * http://www.w3.org/Bugs/Public/show_bug.cgi?id=2224 * we would need, if imported directly, to import redefined * components as well to be able to catch clashing components. * (I hope I'll still know what this means after some months :-() */ if (bucket == NULL) return(-1); if (bucket->flags & XML_SCHEMA_BUCKET_COMPS_ADDED) return(0); bucket->flags |= XML_SCHEMA_BUCKET_COMPS_ADDED; for (i = 0; i < bucket->globals->nbItems; i++) { item = bucket->globals->items[i]; table = NULL; switch (item->type) { case XML_SCHEMA_TYPE_COMPLEX: case XML_SCHEMA_TYPE_SIMPLE: if (WXS_REDEFINED_TYPE(item)) continue; name = (WXS_TYPE_CAST item)->name; WXS_GET_GLOBAL_HASH(bucket, typeDecl) break; case XML_SCHEMA_TYPE_ELEMENT: name = (WXS_ELEM_CAST item)->name; WXS_GET_GLOBAL_HASH(bucket, elemDecl) break; case XML_SCHEMA_TYPE_ATTRIBUTE: name = (WXS_ATTR_CAST item)->name; WXS_GET_GLOBAL_HASH(bucket, attrDecl) break; case XML_SCHEMA_TYPE_GROUP: if (WXS_REDEFINED_MODEL_GROUP_DEF(item)) continue; name = (WXS_MODEL_GROUPDEF_CAST item)->name; WXS_GET_GLOBAL_HASH(bucket, groupDecl) break; case XML_SCHEMA_TYPE_ATTRIBUTEGROUP: if (WXS_REDEFINED_ATTR_GROUP(item)) continue; name = (WXS_ATTR_GROUP_CAST item)->name; WXS_GET_GLOBAL_HASH(bucket, attrgrpDecl) break; case XML_SCHEMA_TYPE_IDC_KEY: case XML_SCHEMA_TYPE_IDC_UNIQUE: case XML_SCHEMA_TYPE_IDC_KEYREF: name = (WXS_IDC_CAST item)->name; WXS_GET_GLOBAL_HASH(bucket, idcDef) break; case XML_SCHEMA_TYPE_NOTATION: name = ((xmlSchemaNotationPtr) item)->name; WXS_GET_GLOBAL_HASH(bucket, notaDecl) break; default: PERROR_INT("xmlSchemaAddComponents", "Unexpected global component type"); continue; } if (*table == NULL) { *table = xmlHashCreateDict(10, pctxt->dict); if (*table == NULL) { PERROR_INT("xmlSchemaAddComponents", "failed to create a component hash table"); return(-1); } } err = xmlHashAddEntry(*table, name, item); if (err != 0) { xmlChar *str = NULL; xmlSchemaCustomErr(ACTXT_CAST pctxt, XML_SCHEMAP_REDEFINED_TYPE, WXS_ITEM_NODE(item), WXS_BASIC_CAST item, "A global %s '%s' does already exist", WXS_ITEM_TYPE_NAME(item), xmlSchemaGetComponentQName(&str, item)); FREE_AND_NULL(str); } } /* * Process imported/included schemas. */ if (bucket->relations != NULL) { xmlSchemaSchemaRelationPtr rel = bucket->relations; do { if ((rel->bucket != NULL) && ((rel->bucket->flags & XML_SCHEMA_BUCKET_COMPS_ADDED) == 0)) { if (xmlSchemaAddComponents(pctxt, rel->bucket) == -1) return(-1); } rel = rel->next; } while (rel != NULL); } return(0); } static int xmlSchemaFixupComponents(xmlSchemaParserCtxtPtr pctxt, xmlSchemaBucketPtr rootBucket) { xmlSchemaConstructionCtxtPtr con = pctxt->constructor; xmlSchemaTreeItemPtr item, *items; int nbItems, i, ret = 0; xmlSchemaBucketPtr oldbucket = con->bucket; xmlSchemaElementPtr elemDecl; #define FIXHFAILURE if (pctxt->err == XML_SCHEMAP_INTERNAL) goto exit_failure; if ((con->pending == NULL) || (con->pending->nbItems == 0)) return(0); /* * Since xmlSchemaFixupComplexType() will create new particles * (local components), and those particle components need a bucket * on the constructor, we'll assure here that the constructor has * a bucket. * TODO: Think about storing locals _only_ on the main bucket. */ if (con->bucket == NULL) con->bucket = rootBucket; /* TODO: * SPEC (src-redefine): * (6.2) "If it has no such self-reference, then all of the * following must be true:" * (6.2.2) The {model group} of the model group definition which * corresponds to it per XML Representation of Model Group * Definition Schema Components ($3.7.2) must be a `valid * restriction` of the {model group} of that model group definition * in I, as defined in Particle Valid (Restriction) ($3.9.6)." */ xmlSchemaCheckSRCRedefineFirst(pctxt); /* * Add global components to the schemata's hash tables. */ xmlSchemaAddComponents(pctxt, rootBucket); pctxt->ctxtType = NULL; items = (xmlSchemaTreeItemPtr *) con->pending->items; nbItems = con->pending->nbItems; /* * Now that we have parsed *all* the schema document(s) and converted * them to schema components, we can resolve references, apply component * constraints, create the FSA from the content model, etc. */ /* * Resolve references of.. * * 1. element declarations: * - the type definition * - the substitution group affiliation * 2. simple/complex types: * - the base type definition * - the memberTypes of union types * - the itemType of list types * 3. attributes declarations and attribute uses: * - the type definition * - if an attribute use, then the attribute declaration * 4. attribute group references: * - the attribute group definition * 5. particles: * - the term of the particle (e.g. a model group) * 6. IDC key-references: * - the referenced IDC 'key' or 'unique' definition * 7. Attribute prohibitions which had a "ref" attribute. */ for (i = 0; i < nbItems; i++) { item = items[i]; switch (item->type) { case XML_SCHEMA_TYPE_ELEMENT: xmlSchemaResolveElementReferences( (xmlSchemaElementPtr) item, pctxt); FIXHFAILURE; break; case XML_SCHEMA_TYPE_COMPLEX: case XML_SCHEMA_TYPE_SIMPLE: xmlSchemaResolveTypeReferences( (xmlSchemaTypePtr) item, pctxt); FIXHFAILURE; break; case XML_SCHEMA_TYPE_ATTRIBUTE: xmlSchemaResolveAttrTypeReferences( (xmlSchemaAttributePtr) item, pctxt); FIXHFAILURE; break; case XML_SCHEMA_TYPE_ATTRIBUTE_USE: xmlSchemaResolveAttrUseReferences( (xmlSchemaAttributeUsePtr) item, pctxt); FIXHFAILURE; break; case XML_SCHEMA_EXTRA_QNAMEREF: if ((WXS_QNAME_CAST item)->itemType == XML_SCHEMA_TYPE_ATTRIBUTEGROUP) { xmlSchemaResolveAttrGroupReferences( WXS_QNAME_CAST item, pctxt); } FIXHFAILURE; break; case XML_SCHEMA_TYPE_SEQUENCE: case XML_SCHEMA_TYPE_CHOICE: case XML_SCHEMA_TYPE_ALL: xmlSchemaResolveModelGroupParticleReferences(pctxt, WXS_MODEL_GROUP_CAST item); FIXHFAILURE; break; case XML_SCHEMA_TYPE_IDC_KEY: case XML_SCHEMA_TYPE_IDC_UNIQUE: case XML_SCHEMA_TYPE_IDC_KEYREF: xmlSchemaResolveIDCKeyReferences( (xmlSchemaIDCPtr) item, pctxt); FIXHFAILURE; break; case XML_SCHEMA_EXTRA_ATTR_USE_PROHIB: /* * Handle attribute prohibition which had a * "ref" attribute. */ xmlSchemaResolveAttrUseProhibReferences( WXS_ATTR_PROHIB_CAST item, pctxt); FIXHFAILURE; break; default: break; } } if (pctxt->nberrors != 0) goto exit_error; /* * Now that all references are resolved we * can check for circularity of... * 1. the base axis of type definitions * 2. nested model group definitions * 3. nested attribute group definitions * TODO: check for circular substitution groups. */ for (i = 0; i < nbItems; i++) { item = items[i]; /* * Let's better stop on the first error here. */ switch (item->type) { case XML_SCHEMA_TYPE_COMPLEX: case XML_SCHEMA_TYPE_SIMPLE: xmlSchemaCheckTypeDefCircular( (xmlSchemaTypePtr) item, pctxt); FIXHFAILURE; if (pctxt->nberrors != 0) goto exit_error; break; case XML_SCHEMA_TYPE_GROUP: xmlSchemaCheckGroupDefCircular( (xmlSchemaModelGroupDefPtr) item, pctxt); FIXHFAILURE; if (pctxt->nberrors != 0) goto exit_error; break; case XML_SCHEMA_TYPE_ATTRIBUTEGROUP: xmlSchemaCheckAttrGroupCircular( (xmlSchemaAttributeGroupPtr) item, pctxt); FIXHFAILURE; if (pctxt->nberrors != 0) goto exit_error; break; default: break; } } if (pctxt->nberrors != 0) goto exit_error; /* * Model group definition references: * Such a reference is reflected by a particle at the component * level. Until now the 'term' of such particles pointed * to the model group definition; this was done, in order to * ease circularity checks. Now we need to set the 'term' of * such particles to the model group of the model group definition. */ for (i = 0; i < nbItems; i++) { item = items[i]; switch (item->type) { case XML_SCHEMA_TYPE_SEQUENCE: case XML_SCHEMA_TYPE_CHOICE: xmlSchemaModelGroupToModelGroupDefFixup(pctxt, WXS_MODEL_GROUP_CAST item); break; default: break; } } if (pctxt->nberrors != 0) goto exit_error; /* * Expand attribute group references of attribute group definitions. */ for (i = 0; i < nbItems; i++) { item = items[i]; switch (item->type) { case XML_SCHEMA_TYPE_ATTRIBUTEGROUP: if ((! WXS_ATTR_GROUP_EXPANDED(item)) && WXS_ATTR_GROUP_HAS_REFS(item)) { xmlSchemaAttributeGroupExpandRefs(pctxt, WXS_ATTR_GROUP_CAST item); FIXHFAILURE; } break; default: break; } } if (pctxt->nberrors != 0) goto exit_error; /* * First compute the variety of simple types. This is needed as * a separate step, since otherwise we won't be able to detect * circular union types in all cases. */ for (i = 0; i < nbItems; i++) { item = items[i]; switch (item->type) { case XML_SCHEMA_TYPE_SIMPLE: if (WXS_IS_TYPE_NOT_FIXED_1((xmlSchemaTypePtr) item)) { xmlSchemaFixupSimpleTypeStageOne(pctxt, (xmlSchemaTypePtr) item); FIXHFAILURE; } break; default: break; } } if (pctxt->nberrors != 0) goto exit_error; /* * Detect circular union types. Note that this needs the variety to * be already computed. */ for (i = 0; i < nbItems; i++) { item = items[i]; switch (item->type) { case XML_SCHEMA_TYPE_SIMPLE: if (((xmlSchemaTypePtr) item)->memberTypes != NULL) { xmlSchemaCheckUnionTypeDefCircular(pctxt, (xmlSchemaTypePtr) item); FIXHFAILURE; } break; default: break; } } if (pctxt->nberrors != 0) goto exit_error; /* * Do the complete type fixup for simple types. */ for (i = 0; i < nbItems; i++) { item = items[i]; switch (item->type) { case XML_SCHEMA_TYPE_SIMPLE: if (WXS_IS_TYPE_NOT_FIXED(WXS_TYPE_CAST item)) { xmlSchemaFixupSimpleTypeStageTwo(pctxt, WXS_TYPE_CAST item); FIXHFAILURE; } break; default: break; } } if (pctxt->nberrors != 0) goto exit_error; /* * At this point we need build and check all simple types. */ /* * Apply constraints for attribute declarations. */ for (i = 0; i < nbItems; i++) { item = items[i]; switch (item->type) { case XML_SCHEMA_TYPE_ATTRIBUTE: xmlSchemaCheckAttrPropsCorrect(pctxt, WXS_ATTR_CAST item); FIXHFAILURE; break; default: break; } } if (pctxt->nberrors != 0) goto exit_error; /* * Apply constraints for attribute uses. */ for (i = 0; i < nbItems; i++) { item = items[i]; switch (item->type) { case XML_SCHEMA_TYPE_ATTRIBUTE_USE: if (((xmlSchemaAttributeUsePtr)item)->defValue != NULL) { xmlSchemaCheckAttrUsePropsCorrect(pctxt, WXS_ATTR_USE_CAST item); FIXHFAILURE; } break; default: break; } } if (pctxt->nberrors != 0) goto exit_error; /* * Apply constraints for attribute group definitions. */ for (i = 0; i < nbItems; i++) { item = items[i]; switch (item->type) { case XML_SCHEMA_TYPE_ATTRIBUTEGROUP: if (( (WXS_ATTR_GROUP_CAST item)->attrUses != NULL) && ( (WXS_LIST_CAST (WXS_ATTR_GROUP_CAST item)->attrUses)->nbItems > 1)) { xmlSchemaCheckAGPropsCorrect(pctxt, WXS_ATTR_GROUP_CAST item); FIXHFAILURE; } break; default: break; } } if (pctxt->nberrors != 0) goto exit_error; /* * Apply constraints for redefinitions. */ if (WXS_CONSTRUCTOR(pctxt)->redefs != NULL) xmlSchemaCheckSRCRedefineSecond(pctxt); if (pctxt->nberrors != 0) goto exit_error; /* * Complex types are built and checked. */ for (i = 0; i < nbItems; i++) { item = con->pending->items[i]; switch (item->type) { case XML_SCHEMA_TYPE_COMPLEX: if (WXS_IS_TYPE_NOT_FIXED(WXS_TYPE_CAST item)) { xmlSchemaFixupComplexType(pctxt, WXS_TYPE_CAST item); FIXHFAILURE; } break; default: break; } } if (pctxt->nberrors != 0) goto exit_error; /* * The list could have changed, since xmlSchemaFixupComplexType() * will create particles and model groups in some cases. */ items = (xmlSchemaTreeItemPtr *) con->pending->items; nbItems = con->pending->nbItems; /* * Apply some constraints for element declarations. */ for (i = 0; i < nbItems; i++) { item = items[i]; switch (item->type) { case XML_SCHEMA_TYPE_ELEMENT: elemDecl = (xmlSchemaElementPtr) item; if ((elemDecl->flags & XML_SCHEMAS_ELEM_INTERNAL_CHECKED) == 0) { xmlSchemaCheckElementDeclComponent( (xmlSchemaElementPtr) elemDecl, pctxt); FIXHFAILURE; } #ifdef WXS_ELEM_DECL_CONS_ENABLED /* * Schema Component Constraint: Element Declarations Consistent * Apply this constraint to local types of element declarations. */ if ((WXS_ELEM_TYPEDEF(elemDecl) != NULL) && (WXS_IS_COMPLEX(WXS_ELEM_TYPEDEF(elemDecl))) && (WXS_TYPE_IS_LOCAL(WXS_ELEM_TYPEDEF(elemDecl)))) { xmlSchemaCheckElementDeclConsistent(pctxt, WXS_BASIC_CAST elemDecl, WXS_TYPE_PARTICLE(WXS_ELEM_TYPEDEF(elemDecl)), NULL, NULL, 0); } #endif break; default: break; } } if (pctxt->nberrors != 0) goto exit_error; /* * Finally we can build the automaton from the content model of * complex types. */ for (i = 0; i < nbItems; i++) { item = items[i]; switch (item->type) { case XML_SCHEMA_TYPE_COMPLEX: xmlSchemaBuildContentModel((xmlSchemaTypePtr) item, pctxt); /* FIXHFAILURE; */ break; default: break; } } if (pctxt->nberrors != 0) goto exit_error; /* * URGENT TODO: cos-element-consistent */ goto exit; exit_error: ret = pctxt->err; goto exit; exit_failure: ret = -1; exit: /* * Reset the constructor. This is needed for XSI acquisition, since * those items will be processed over and over again for every XSI * if not cleared here. */ con->bucket = oldbucket; con->pending->nbItems = 0; if (con->substGroups != NULL) { xmlHashFree(con->substGroups, xmlSchemaSubstGroupFreeEntry); con->substGroups = NULL; } if (con->redefs != NULL) { xmlSchemaRedefListFree(con->redefs); con->redefs = NULL; } return(ret); } /** * xmlSchemaParse: * @ctxt: a schema validation context * * parse a schema definition resource and build an internal * XML Schema structure which can be used to validate instances. * * Returns the internal XML Schema structure built from the resource or * NULL in case of error */ xmlSchemaPtr xmlSchemaParse(xmlSchemaParserCtxtPtr ctxt) { xmlSchemaPtr mainSchema = NULL; xmlSchemaBucketPtr bucket = NULL; int res; /* * This one is used if the schema to be parsed was specified via * the API; i.e. not automatically by the validated instance document. */ xmlSchemaInitTypes(); if (ctxt == NULL) return (NULL); /* TODO: Init the context. Is this all we need?*/ ctxt->nberrors = 0; ctxt->err = 0; ctxt->counter = 0; /* Create the *main* schema. */ mainSchema = xmlSchemaNewSchema(ctxt); if (mainSchema == NULL) goto exit_failure; /* * Create the schema constructor. */ if (ctxt->constructor == NULL) { ctxt->constructor = xmlSchemaConstructionCtxtCreate(ctxt->dict); if (ctxt->constructor == NULL) return(NULL); /* Take ownership of the constructor to be able to free it. */ ctxt->ownsConstructor = 1; } ctxt->constructor->mainSchema = mainSchema; /* * Locate and add the schema document. */ res = xmlSchemaAddSchemaDoc(ctxt, XML_SCHEMA_SCHEMA_MAIN, ctxt->URL, ctxt->doc, ctxt->buffer, ctxt->size, NULL, NULL, NULL, &bucket); if (res == -1) goto exit_failure; if (res != 0) goto exit; if (bucket == NULL) { /* TODO: Error code, actually we failed to *locate* the schema. */ if (ctxt->URL) xmlSchemaCustomErr(ACTXT_CAST ctxt, XML_SCHEMAP_FAILED_LOAD, NULL, NULL, "Failed to locate the main schema resource at '%s'", ctxt->URL, NULL); else xmlSchemaCustomErr(ACTXT_CAST ctxt, XML_SCHEMAP_FAILED_LOAD, NULL, NULL, "Failed to locate the main schema resource", NULL, NULL); goto exit; } /* Then do the parsing for good. */ if (xmlSchemaParseNewDocWithContext(ctxt, mainSchema, bucket) == -1) goto exit_failure; if (ctxt->nberrors != 0) goto exit; mainSchema->doc = bucket->doc; mainSchema->preserve = ctxt->preserve; ctxt->schema = mainSchema; if (xmlSchemaFixupComponents(ctxt, WXS_CONSTRUCTOR(ctxt)->mainBucket) == -1) goto exit_failure; /* * TODO: This is not nice, since we cannot distinguish from the * result if there was an internal error or not. */ exit: if (ctxt->nberrors != 0) { if (mainSchema) { xmlSchemaFree(mainSchema); mainSchema = NULL; } if (ctxt->constructor) { xmlSchemaConstructionCtxtFree(ctxt->constructor); ctxt->constructor = NULL; ctxt->ownsConstructor = 0; } } ctxt->schema = NULL; return(mainSchema); exit_failure: /* * Quite verbose, but should catch internal errors, which were * not communicated. */ if (mainSchema) { xmlSchemaFree(mainSchema); mainSchema = NULL; } if (ctxt->constructor) { xmlSchemaConstructionCtxtFree(ctxt->constructor); ctxt->constructor = NULL; ctxt->ownsConstructor = 0; } PERROR_INT2("xmlSchemaParse", "An internal error occurred"); ctxt->schema = NULL; return(NULL); } /** * xmlSchemaSetParserErrors: * @ctxt: a schema validation context * @err: the error callback * @warn: the warning callback * @ctx: contextual data for the callbacks * * Set the callback functions used to handle errors for a validation context */ void xmlSchemaSetParserErrors(xmlSchemaParserCtxtPtr ctxt, xmlSchemaValidityErrorFunc err, xmlSchemaValidityWarningFunc warn, void *ctx) { if (ctxt == NULL) return; ctxt->error = err; ctxt->warning = warn; ctxt->errCtxt = ctx; if (ctxt->vctxt != NULL) xmlSchemaSetValidErrors(ctxt->vctxt, err, warn, ctx); } /** * xmlSchemaSetParserStructuredErrors: * @ctxt: a schema parser context * @serror: the structured error function * @ctx: the functions context * * Set the structured error callback */ void xmlSchemaSetParserStructuredErrors(xmlSchemaParserCtxtPtr ctxt, xmlStructuredErrorFunc serror, void *ctx) { if (ctxt == NULL) return; ctxt->serror = serror; ctxt->errCtxt = ctx; if (ctxt->vctxt != NULL) xmlSchemaSetValidStructuredErrors(ctxt->vctxt, serror, ctx); } /** * xmlSchemaGetParserErrors: * @ctxt: a XMl-Schema parser context * @err: the error callback result * @warn: the warning callback result * @ctx: contextual data for the callbacks result * * Get the callback information used to handle errors for a parser context * * Returns -1 in case of failure, 0 otherwise */ int xmlSchemaGetParserErrors(xmlSchemaParserCtxtPtr ctxt, xmlSchemaValidityErrorFunc * err, xmlSchemaValidityWarningFunc * warn, void **ctx) { if (ctxt == NULL) return(-1); if (err != NULL) *err = ctxt->error; if (warn != NULL) *warn = ctxt->warning; if (ctx != NULL) *ctx = ctxt->errCtxt; return(0); } /** * xmlSchemaFacetTypeToString: * @type: the facet type * * Convert the xmlSchemaTypeType to a char string. * * Returns the char string representation of the facet type if the * type is a facet and an "Internal Error" string otherwise. */ static const xmlChar * xmlSchemaFacetTypeToString(xmlSchemaTypeType type) { switch (type) { case XML_SCHEMA_FACET_PATTERN: return (BAD_CAST "pattern"); case XML_SCHEMA_FACET_MAXEXCLUSIVE: return (BAD_CAST "maxExclusive"); case XML_SCHEMA_FACET_MAXINCLUSIVE: return (BAD_CAST "maxInclusive"); case XML_SCHEMA_FACET_MINEXCLUSIVE: return (BAD_CAST "minExclusive"); case XML_SCHEMA_FACET_MININCLUSIVE: return (BAD_CAST "minInclusive"); case XML_SCHEMA_FACET_WHITESPACE: return (BAD_CAST "whiteSpace"); case XML_SCHEMA_FACET_ENUMERATION: return (BAD_CAST "enumeration"); case XML_SCHEMA_FACET_LENGTH: return (BAD_CAST "length"); case XML_SCHEMA_FACET_MAXLENGTH: return (BAD_CAST "maxLength"); case XML_SCHEMA_FACET_MINLENGTH: return (BAD_CAST "minLength"); case XML_SCHEMA_FACET_TOTALDIGITS: return (BAD_CAST "totalDigits"); case XML_SCHEMA_FACET_FRACTIONDIGITS: return (BAD_CAST "fractionDigits"); default: break; } return (BAD_CAST "Internal Error"); } static xmlSchemaWhitespaceValueType xmlSchemaGetWhiteSpaceFacetValue(xmlSchemaTypePtr type) { /* * The normalization type can be changed only for types which are derived * from xsd:string. */ if (type->type == XML_SCHEMA_TYPE_BASIC) { /* * Note that we assume a whitespace of preserve for anySimpleType. */ if ((type->builtInType == XML_SCHEMAS_STRING) || (type->builtInType == XML_SCHEMAS_ANYSIMPLETYPE)) return(XML_SCHEMA_WHITESPACE_PRESERVE); else if (type->builtInType == XML_SCHEMAS_NORMSTRING) return(XML_SCHEMA_WHITESPACE_REPLACE); else { /* * For all `atomic` datatypes other than string (and types `derived` * by `restriction` from it) the value of whiteSpace is fixed to * collapse * Note that this includes built-in list datatypes. */ return(XML_SCHEMA_WHITESPACE_COLLAPSE); } } else if (WXS_IS_LIST(type)) { /* * For list types the facet "whiteSpace" is fixed to "collapse". */ return (XML_SCHEMA_WHITESPACE_COLLAPSE); } else if (WXS_IS_UNION(type)) { return (XML_SCHEMA_WHITESPACE_UNKNOWN); } else if (WXS_IS_ATOMIC(type)) { if (type->flags & XML_SCHEMAS_TYPE_WHITESPACE_PRESERVE) return (XML_SCHEMA_WHITESPACE_PRESERVE); else if (type->flags & XML_SCHEMAS_TYPE_WHITESPACE_REPLACE) return (XML_SCHEMA_WHITESPACE_REPLACE); else return (XML_SCHEMA_WHITESPACE_COLLAPSE); } return (-1); } /************************************************************************ * * * Simple type validation * * * ************************************************************************/ /************************************************************************ * * * DOM Validation code * * * ************************************************************************/ /** * xmlSchemaAssembleByLocation: * @pctxt: a schema parser context * @vctxt: a schema validation context * @schema: the existing schema * @node: the node that fired the assembling * @nsName: the namespace name of the new schema * @location: the location of the schema * * Expands an existing schema by an additional schema. * * Returns 0 if the new schema is correct, a positive error code * number otherwise and -1 in case of an internal or API error. */ static int xmlSchemaAssembleByLocation(xmlSchemaValidCtxtPtr vctxt, xmlSchemaPtr schema, xmlNodePtr node, const xmlChar *nsName, const xmlChar *location) { int ret = 0; xmlSchemaParserCtxtPtr pctxt; xmlSchemaBucketPtr bucket = NULL; if ((vctxt == NULL) || (schema == NULL)) return (-1); if (vctxt->pctxt == NULL) { VERROR_INT("xmlSchemaAssembleByLocation", "no parser context available"); return(-1); } pctxt = vctxt->pctxt; if (pctxt->constructor == NULL) { PERROR_INT("xmlSchemaAssembleByLocation", "no constructor"); return(-1); } /* * Acquire the schema document. */ location = xmlSchemaBuildAbsoluteURI(pctxt->dict, location, node); /* * Note that we pass XML_SCHEMA_SCHEMA_IMPORT here; * the process will automatically change this to * XML_SCHEMA_SCHEMA_MAIN if it is the first schema document. */ ret = xmlSchemaAddSchemaDoc(pctxt, XML_SCHEMA_SCHEMA_IMPORT, location, NULL, NULL, 0, node, NULL, nsName, &bucket); if (ret != 0) return(ret); if (bucket == NULL) { /* * Generate a warning that the document could not be located. */ xmlSchemaCustomWarning(ACTXT_CAST vctxt, XML_SCHEMAV_MISC, node, NULL, "The document at location '%s' could not be acquired", location, NULL, NULL); return(ret); } /* * The first located schema will be handled as if all other * schemas imported by XSI were imported by this first schema. */ if ((bucket != NULL) && (WXS_CONSTRUCTOR(pctxt)->bucket == NULL)) WXS_CONSTRUCTOR(pctxt)->bucket = bucket; /* * TODO: Is this handled like an import? I.e. is it not an error * if the schema cannot be located? */ if ((bucket == NULL) || (! CAN_PARSE_SCHEMA(bucket))) return(0); /* * We will reuse the parser context for every schema imported * directly via XSI. So reset the context. */ pctxt->nberrors = 0; pctxt->err = 0; pctxt->doc = bucket->doc; ret = xmlSchemaParseNewDocWithContext(pctxt, schema, bucket); if (ret == -1) { pctxt->doc = NULL; goto exit_failure; } /* Paranoid error channelling. */ if ((ret == 0) && (pctxt->nberrors != 0)) ret = pctxt->err; if (pctxt->nberrors == 0) { /* * Only bother to fixup pending components, if there was * no error yet. * For every XSI acquired schema (and its sub-schemata) we will * fixup the components. */ xmlSchemaFixupComponents(pctxt, bucket); ret = pctxt->err; /* * Not nice, but we need somehow to channel the schema parser * error to the validation context. */ if ((ret != 0) && (vctxt->err == 0)) vctxt->err = ret; vctxt->nberrors += pctxt->nberrors; } else { /* Add to validation error sum. */ vctxt->nberrors += pctxt->nberrors; } pctxt->doc = NULL; return(ret); exit_failure: pctxt->doc = NULL; return (-1); } static xmlSchemaAttrInfoPtr xmlSchemaGetMetaAttrInfo(xmlSchemaValidCtxtPtr vctxt, int metaType) { if (vctxt->nbAttrInfos == 0) return (NULL); { int i; xmlSchemaAttrInfoPtr iattr; for (i = 0; i < vctxt->nbAttrInfos; i++) { iattr = vctxt->attrInfos[i]; if (iattr->metaType == metaType) return (iattr); } } return (NULL); } /** * xmlSchemaAssembleByXSI: * @vctxt: a schema validation context * * Expands an existing schema by an additional schema using * the xsi:schemaLocation or xsi:noNamespaceSchemaLocation attribute * of an instance. If xsi:noNamespaceSchemaLocation is used, @noNamespace * must be set to 1. * * Returns 0 if the new schema is correct, a positive error code * number otherwise and -1 in case of an internal or API error. */ static int xmlSchemaAssembleByXSI(xmlSchemaValidCtxtPtr vctxt) { const xmlChar *cur, *end; const xmlChar *nsname = NULL, *location; int count = 0; int ret = 0; xmlSchemaAttrInfoPtr iattr; /* * Parse the value; we will assume an even number of values * to be given (this is how Xerces and XSV work). * * URGENT TODO: !! This needs to work for both * @noNamespaceSchemaLocation AND @schemaLocation on the same * element !! */ iattr = xmlSchemaGetMetaAttrInfo(vctxt, XML_SCHEMA_ATTR_INFO_META_XSI_SCHEMA_LOC); if (iattr == NULL) iattr = xmlSchemaGetMetaAttrInfo(vctxt, XML_SCHEMA_ATTR_INFO_META_XSI_NO_NS_SCHEMA_LOC); if (iattr == NULL) return (0); cur = iattr->value; do { /* * TODO: Move the string parsing mechanism away from here. */ if (iattr->metaType == XML_SCHEMA_ATTR_INFO_META_XSI_SCHEMA_LOC) { /* * Get the namespace name. */ while (IS_BLANK_CH(*cur)) cur++; end = cur; while ((*end != 0) && (!(IS_BLANK_CH(*end)))) end++; if (end == cur) break; count++; /* TODO: Don't use the schema's dict. */ nsname = xmlDictLookup(vctxt->schema->dict, cur, end - cur); cur = end; } /* * Get the URI. */ while (IS_BLANK_CH(*cur)) cur++; end = cur; while ((*end != 0) && (!(IS_BLANK_CH(*end)))) end++; if (end == cur) { if (iattr->metaType == XML_SCHEMA_ATTR_INFO_META_XSI_SCHEMA_LOC) { /* * If using @schemaLocation then tuples are expected. * I.e. the namespace name *and* the document's URI. */ xmlSchemaCustomWarning(ACTXT_CAST vctxt, XML_SCHEMAV_MISC, iattr->node, NULL, "The value must consist of tuples: the target namespace " "name and the document's URI", NULL, NULL, NULL); } break; } count++; /* TODO: Don't use the schema's dict. */ location = xmlDictLookup(vctxt->schema->dict, cur, end - cur); cur = end; ret = xmlSchemaAssembleByLocation(vctxt, vctxt->schema, iattr->node, nsname, location); if (ret == -1) { VERROR_INT("xmlSchemaAssembleByXSI", "assembling schemata"); return (-1); } } while (*cur != 0); return (ret); } static const xmlChar * xmlSchemaLookupNamespace(xmlSchemaValidCtxtPtr vctxt, const xmlChar *prefix) { if (vctxt->sax != NULL) { int i, j; xmlSchemaNodeInfoPtr inode; for (i = vctxt->depth; i >= 0; i--) { if (vctxt->elemInfos[i]->nbNsBindings != 0) { inode = vctxt->elemInfos[i]; for (j = 0; j < inode->nbNsBindings * 2; j += 2) { if (((prefix == NULL) && (inode->nsBindings[j] == NULL)) || ((prefix != NULL) && xmlStrEqual(prefix, inode->nsBindings[j]))) { /* * Note that the namespace bindings are already * in a string dict. */ return (inode->nsBindings[j+1]); } } } } return (NULL); #ifdef LIBXML_READER_ENABLED } else if (vctxt->reader != NULL) { xmlChar *nsName; nsName = xmlTextReaderLookupNamespace(vctxt->reader, prefix); if (nsName != NULL) { const xmlChar *ret; ret = xmlDictLookup(vctxt->dict, nsName, -1); xmlFree(nsName); return (ret); } else return (NULL); #endif } else { xmlNsPtr ns; if ((vctxt->inode->node == NULL) || (vctxt->inode->node->doc == NULL)) { VERROR_INT("xmlSchemaLookupNamespace", "no node or node's doc available"); return (NULL); } ns = xmlSearchNs(vctxt->inode->node->doc, vctxt->inode->node, prefix); if (ns != NULL) return (ns->href); return (NULL); } } /* * This one works on the schema of the validation context. */ static int xmlSchemaValidateNotation(xmlSchemaValidCtxtPtr vctxt, xmlSchemaPtr schema, xmlNodePtr node, const xmlChar *value, xmlSchemaValPtr *val, int valNeeded) { int ret; if (vctxt && (vctxt->schema == NULL)) { VERROR_INT("xmlSchemaValidateNotation", "a schema is needed on the validation context"); return (-1); } ret = xmlValidateQName(value, 1); if (ret != 0) return (ret); { xmlChar *localName = NULL; xmlChar *prefix = NULL; localName = xmlSplitQName2(value, &prefix); if (prefix != NULL) { const xmlChar *nsName = NULL; if (vctxt != NULL) nsName = xmlSchemaLookupNamespace(vctxt, BAD_CAST prefix); else if (node != NULL) { xmlNsPtr ns = xmlSearchNs(node->doc, node, prefix); if (ns != NULL) nsName = ns->href; } else { xmlFree(prefix); xmlFree(localName); return (1); } if (nsName == NULL) { xmlFree(prefix); xmlFree(localName); return (1); } if (xmlSchemaGetNotation(schema, localName, nsName) != NULL) { if ((valNeeded) && (val != NULL)) { (*val) = xmlSchemaNewNOTATIONValue(xmlStrdup(localName), xmlStrdup(nsName)); if (*val == NULL) ret = -1; } } else ret = 1; xmlFree(prefix); xmlFree(localName); } else { if (xmlSchemaGetNotation(schema, value, NULL) != NULL) { if (valNeeded && (val != NULL)) { (*val) = xmlSchemaNewNOTATIONValue( BAD_CAST xmlStrdup(value), NULL); if (*val == NULL) ret = -1; } } else return (1); } } return (ret); } static int xmlSchemaVAddNodeQName(xmlSchemaValidCtxtPtr vctxt, const xmlChar* lname, const xmlChar* nsname) { int i; lname = xmlDictLookup(vctxt->dict, lname, -1); if (lname == NULL) return(-1); if (nsname != NULL) { nsname = xmlDictLookup(vctxt->dict, nsname, -1); if (nsname == NULL) return(-1); } for (i = 0; i < vctxt->nodeQNames->nbItems; i += 2) { if ((vctxt->nodeQNames->items [i] == lname) && (vctxt->nodeQNames->items[i +1] == nsname)) /* Already there */ return(i); } /* Add new entry. */ i = vctxt->nodeQNames->nbItems; xmlSchemaItemListAdd(vctxt->nodeQNames, (void *) lname); xmlSchemaItemListAdd(vctxt->nodeQNames, (void *) nsname); return(i); } /************************************************************************ * * * Validation of identity-constraints (IDC) * * * ************************************************************************/ /** * xmlSchemaAugmentIDC: * @idcDef: the IDC definition * * Creates an augmented IDC definition item. * * Returns the item, or NULL on internal errors. */ static void xmlSchemaAugmentIDC(void *payload, void *data, const xmlChar *name ATTRIBUTE_UNUSED) { xmlSchemaIDCPtr idcDef = (xmlSchemaIDCPtr) payload; xmlSchemaValidCtxtPtr vctxt = (xmlSchemaValidCtxtPtr) data; xmlSchemaIDCAugPtr aidc; aidc = (xmlSchemaIDCAugPtr) xmlMalloc(sizeof(xmlSchemaIDCAug)); if (aidc == NULL) { xmlSchemaVErrMemory(vctxt, "xmlSchemaAugmentIDC: allocating an augmented IDC definition", NULL); return; } aidc->keyrefDepth = -1; aidc->def = idcDef; aidc->next = NULL; if (vctxt->aidcs == NULL) vctxt->aidcs = aidc; else { aidc->next = vctxt->aidcs; vctxt->aidcs = aidc; } /* * Save if we have keyrefs at all. */ if ((vctxt->hasKeyrefs == 0) && (idcDef->type == XML_SCHEMA_TYPE_IDC_KEYREF)) vctxt->hasKeyrefs = 1; } /** * xmlSchemaAugmentImportedIDC: * @imported: the imported schema * * Creates an augmented IDC definition for the imported schema. */ static void xmlSchemaAugmentImportedIDC(void *payload, void *data, const xmlChar *name ATTRIBUTE_UNUSED) { xmlSchemaImportPtr imported = (xmlSchemaImportPtr) payload; xmlSchemaValidCtxtPtr vctxt = (xmlSchemaValidCtxtPtr) data; if (imported->schema->idcDef != NULL) { xmlHashScan(imported->schema->idcDef, xmlSchemaAugmentIDC, vctxt); } } /** * xmlSchemaIDCNewBinding: * @idcDef: the IDC definition of this binding * * Creates a new IDC binding. * * Returns the new IDC binding, NULL on internal errors. */ static xmlSchemaPSVIIDCBindingPtr xmlSchemaIDCNewBinding(xmlSchemaIDCPtr idcDef) { xmlSchemaPSVIIDCBindingPtr ret; ret = (xmlSchemaPSVIIDCBindingPtr) xmlMalloc( sizeof(xmlSchemaPSVIIDCBinding)); if (ret == NULL) { xmlSchemaVErrMemory(NULL, "allocating a PSVI IDC binding item", NULL); return (NULL); } memset(ret, 0, sizeof(xmlSchemaPSVIIDCBinding)); ret->definition = idcDef; return (ret); } /** * xmlSchemaIDCStoreNodeTableItem: * @vctxt: the WXS validation context * @item: the IDC node table item * * The validation context is used to store IDC node table items. * They are stored to avoid copying them if IDC node-tables are merged * with corresponding parent IDC node-tables (bubbling). * * Returns 0 if succeeded, -1 on internal errors. */ static int xmlSchemaIDCStoreNodeTableItem(xmlSchemaValidCtxtPtr vctxt, xmlSchemaPSVIIDCNodePtr item) { /* * Add to global list. */ if (vctxt->idcNodes == NULL) { vctxt->idcNodes = (xmlSchemaPSVIIDCNodePtr *) xmlMalloc(20 * sizeof(xmlSchemaPSVIIDCNodePtr)); if (vctxt->idcNodes == NULL) { xmlSchemaVErrMemory(vctxt, "allocating the IDC node table item list", NULL); return (-1); } vctxt->sizeIdcNodes = 20; } else if (vctxt->sizeIdcNodes <= vctxt->nbIdcNodes) { vctxt->sizeIdcNodes *= 2; vctxt->idcNodes = (xmlSchemaPSVIIDCNodePtr *) xmlRealloc(vctxt->idcNodes, vctxt->sizeIdcNodes * sizeof(xmlSchemaPSVIIDCNodePtr)); if (vctxt->idcNodes == NULL) { xmlSchemaVErrMemory(vctxt, "re-allocating the IDC node table item list", NULL); return (-1); } } vctxt->idcNodes[vctxt->nbIdcNodes++] = item; return (0); } /** * xmlSchemaIDCStoreKey: * @vctxt: the WXS validation context * @item: the IDC key * * The validation context is used to store an IDC key. * * Returns 0 if succeeded, -1 on internal errors. */ static int xmlSchemaIDCStoreKey(xmlSchemaValidCtxtPtr vctxt, xmlSchemaPSVIIDCKeyPtr key) { /* * Add to global list. */ if (vctxt->idcKeys == NULL) { vctxt->idcKeys = (xmlSchemaPSVIIDCKeyPtr *) xmlMalloc(40 * sizeof(xmlSchemaPSVIIDCKeyPtr)); if (vctxt->idcKeys == NULL) { xmlSchemaVErrMemory(vctxt, "allocating the IDC key storage list", NULL); return (-1); } vctxt->sizeIdcKeys = 40; } else if (vctxt->sizeIdcKeys <= vctxt->nbIdcKeys) { vctxt->sizeIdcKeys *= 2; vctxt->idcKeys = (xmlSchemaPSVIIDCKeyPtr *) xmlRealloc(vctxt->idcKeys, vctxt->sizeIdcKeys * sizeof(xmlSchemaPSVIIDCKeyPtr)); if (vctxt->idcKeys == NULL) { xmlSchemaVErrMemory(vctxt, "re-allocating the IDC key storage list", NULL); return (-1); } } vctxt->idcKeys[vctxt->nbIdcKeys++] = key; return (0); } /** * xmlSchemaIDCAppendNodeTableItem: * @bind: the IDC binding * @ntItem: the node-table item * * Appends the IDC node-table item to the binding. * * Returns 0 on success and -1 on internal errors. */ static int xmlSchemaIDCAppendNodeTableItem(xmlSchemaPSVIIDCBindingPtr bind, xmlSchemaPSVIIDCNodePtr ntItem) { if (bind->nodeTable == NULL) { bind->sizeNodes = 10; bind->nodeTable = (xmlSchemaPSVIIDCNodePtr *) xmlMalloc(10 * sizeof(xmlSchemaPSVIIDCNodePtr)); if (bind->nodeTable == NULL) { xmlSchemaVErrMemory(NULL, "allocating an array of IDC node-table items", NULL); return(-1); } } else if (bind->sizeNodes <= bind->nbNodes) { bind->sizeNodes *= 2; bind->nodeTable = (xmlSchemaPSVIIDCNodePtr *) xmlRealloc(bind->nodeTable, bind->sizeNodes * sizeof(xmlSchemaPSVIIDCNodePtr)); if (bind->nodeTable == NULL) { xmlSchemaVErrMemory(NULL, "re-allocating an array of IDC node-table items", NULL); return(-1); } } bind->nodeTable[bind->nbNodes++] = ntItem; return(0); } /** * xmlSchemaIDCAcquireBinding: * @vctxt: the WXS validation context * @matcher: the IDC matcher * * Looks up an PSVI IDC binding, for the IDC definition and * of the given matcher. If none found, a new one is created * and added to the IDC table. * * Returns an IDC binding or NULL on internal errors. */ static xmlSchemaPSVIIDCBindingPtr xmlSchemaIDCAcquireBinding(xmlSchemaValidCtxtPtr vctxt, xmlSchemaIDCMatcherPtr matcher) { xmlSchemaNodeInfoPtr ielem; ielem = vctxt->elemInfos[matcher->depth]; if (ielem->idcTable == NULL) { ielem->idcTable = xmlSchemaIDCNewBinding(matcher->aidc->def); if (ielem->idcTable == NULL) return (NULL); return(ielem->idcTable); } else { xmlSchemaPSVIIDCBindingPtr bind = NULL; bind = ielem->idcTable; do { if (bind->definition == matcher->aidc->def) return(bind); if (bind->next == NULL) { bind->next = xmlSchemaIDCNewBinding(matcher->aidc->def); if (bind->next == NULL) return (NULL); return(bind->next); } bind = bind->next; } while (bind != NULL); } return (NULL); } static xmlSchemaItemListPtr xmlSchemaIDCAcquireTargetList(xmlSchemaValidCtxtPtr vctxt ATTRIBUTE_UNUSED, xmlSchemaIDCMatcherPtr matcher) { if (matcher->targets == NULL) matcher->targets = xmlSchemaItemListCreate(); return(matcher->targets); } /** * xmlSchemaIDCFreeKey: * @key: the IDC key * * Frees an IDC key together with its compiled value. */ static void xmlSchemaIDCFreeKey(xmlSchemaPSVIIDCKeyPtr key) { if (key->val != NULL) xmlSchemaFreeValue(key->val); xmlFree(key); } /** * xmlSchemaIDCFreeBinding: * * Frees an IDC binding. Note that the node table-items * are not freed. */ static void xmlSchemaIDCFreeBinding(xmlSchemaPSVIIDCBindingPtr bind) { if (bind->nodeTable != NULL) xmlFree(bind->nodeTable); if (bind->dupls != NULL) xmlSchemaItemListFree(bind->dupls); xmlFree(bind); } /** * xmlSchemaIDCFreeIDCTable: * @bind: the first IDC binding in the list * * Frees an IDC table, i.e. all the IDC bindings in the list. */ static void xmlSchemaIDCFreeIDCTable(xmlSchemaPSVIIDCBindingPtr bind) { xmlSchemaPSVIIDCBindingPtr prev; while (bind != NULL) { prev = bind; bind = bind->next; xmlSchemaIDCFreeBinding(prev); } } static void xmlFreeIDCHashEntry (void *payload, const xmlChar *name ATTRIBUTE_UNUSED) { xmlIDCHashEntryPtr e = payload, n; while (e) { n = e->next; xmlFree(e); e = n; } } /** * xmlSchemaIDCFreeMatcherList: * @matcher: the first IDC matcher in the list * * Frees a list of IDC matchers. */ static void xmlSchemaIDCFreeMatcherList(xmlSchemaIDCMatcherPtr matcher) { xmlSchemaIDCMatcherPtr next; while (matcher != NULL) { next = matcher->next; if (matcher->keySeqs != NULL) { int i; for (i = 0; i < matcher->sizeKeySeqs; i++) if (matcher->keySeqs[i] != NULL) xmlFree(matcher->keySeqs[i]); xmlFree(matcher->keySeqs); } if (matcher->targets != NULL) { if (matcher->idcType == XML_SCHEMA_TYPE_IDC_KEYREF) { int i; xmlSchemaPSVIIDCNodePtr idcNode; /* * Node-table items for keyrefs are not stored globally * to the validation context, since they are not bubbled. * We need to free them here. */ for (i = 0; i < matcher->targets->nbItems; i++) { idcNode = (xmlSchemaPSVIIDCNodePtr) matcher->targets->items[i]; xmlFree(idcNode->keys); xmlFree(idcNode); } } xmlSchemaItemListFree(matcher->targets); } if (matcher->htab != NULL) xmlHashFree(matcher->htab, xmlFreeIDCHashEntry); xmlFree(matcher); matcher = next; } } /** * xmlSchemaIDCReleaseMatcherList: * @vctxt: the WXS validation context * @matcher: the first IDC matcher in the list * * Caches a list of IDC matchers for reuse. */ static void xmlSchemaIDCReleaseMatcherList(xmlSchemaValidCtxtPtr vctxt, xmlSchemaIDCMatcherPtr matcher) { xmlSchemaIDCMatcherPtr next; while (matcher != NULL) { next = matcher->next; if (matcher->keySeqs != NULL) { int i; /* * Don't free the array, but only the content. */ for (i = 0; i < matcher->sizeKeySeqs; i++) if (matcher->keySeqs[i] != NULL) { xmlFree(matcher->keySeqs[i]); matcher->keySeqs[i] = NULL; } } if (matcher->targets) { if (matcher->idcType == XML_SCHEMA_TYPE_IDC_KEYREF) { int i; xmlSchemaPSVIIDCNodePtr idcNode; /* * Node-table items for keyrefs are not stored globally * to the validation context, since they are not bubbled. * We need to free them here. */ for (i = 0; i < matcher->targets->nbItems; i++) { idcNode = (xmlSchemaPSVIIDCNodePtr) matcher->targets->items[i]; xmlFree(idcNode->keys); xmlFree(idcNode); } } xmlSchemaItemListFree(matcher->targets); matcher->targets = NULL; } if (matcher->htab != NULL) { xmlHashFree(matcher->htab, xmlFreeIDCHashEntry); matcher->htab = NULL; } matcher->next = NULL; /* * Cache the matcher. */ if (vctxt->idcMatcherCache != NULL) matcher->nextCached = vctxt->idcMatcherCache; vctxt->idcMatcherCache = matcher; matcher = next; } } /** * xmlSchemaIDCAddStateObject: * @vctxt: the WXS validation context * @matcher: the IDC matcher * @sel: the XPath information * @parent: the parent "selector" state object if any * @type: "selector" or "field" * * Creates/reuses and activates state objects for the given * XPath information; if the XPath expression consists of unions, * multiple state objects are created for every unioned expression. * * Returns 0 on success and -1 on internal errors. */ static int xmlSchemaIDCAddStateObject(xmlSchemaValidCtxtPtr vctxt, xmlSchemaIDCMatcherPtr matcher, xmlSchemaIDCSelectPtr sel, int type) { xmlSchemaIDCStateObjPtr sto; /* * Reuse the state objects from the pool. */ if (vctxt->xpathStatePool != NULL) { sto = vctxt->xpathStatePool; vctxt->xpathStatePool = sto->next; sto->next = NULL; } else { /* * Create a new state object. */ sto = (xmlSchemaIDCStateObjPtr) xmlMalloc(sizeof(xmlSchemaIDCStateObj)); if (sto == NULL) { xmlSchemaVErrMemory(NULL, "allocating an IDC state object", NULL); return (-1); } memset(sto, 0, sizeof(xmlSchemaIDCStateObj)); } /* * Add to global list. */ if (vctxt->xpathStates != NULL) sto->next = vctxt->xpathStates; vctxt->xpathStates = sto; /* * Free the old xpath validation context. */ if (sto->xpathCtxt != NULL) xmlFreeStreamCtxt((xmlStreamCtxtPtr) sto->xpathCtxt); /* * Create a new XPath (pattern) validation context. */ sto->xpathCtxt = (void *) xmlPatternGetStreamCtxt( (xmlPatternPtr) sel->xpathComp); if (sto->xpathCtxt == NULL) { VERROR_INT("xmlSchemaIDCAddStateObject", "failed to create an XPath validation context"); return (-1); } sto->type = type; sto->depth = vctxt->depth; sto->matcher = matcher; sto->sel = sel; sto->nbHistory = 0; #ifdef DEBUG_IDC xmlGenericError(xmlGenericErrorContext, "IDC: STO push '%s'\n", sto->sel->xpath); #endif return (0); } /** * xmlSchemaXPathEvaluate: * @vctxt: the WXS validation context * @nodeType: the nodeType of the current node * * Evaluates all active XPath state objects. * * Returns the number of IC "field" state objects which resolved to * this node, 0 if none resolved and -1 on internal errors. */ static int xmlSchemaXPathEvaluate(xmlSchemaValidCtxtPtr vctxt, xmlElementType nodeType) { xmlSchemaIDCStateObjPtr sto, head = NULL, first; int res, resolved = 0, depth = vctxt->depth; if (vctxt->xpathStates == NULL) return (0); if (nodeType == XML_ATTRIBUTE_NODE) depth++; #ifdef DEBUG_IDC { xmlChar *str = NULL; xmlGenericError(xmlGenericErrorContext, "IDC: EVAL on %s, depth %d, type %d\n", xmlSchemaFormatQName(&str, vctxt->inode->nsName, vctxt->inode->localName), depth, nodeType); FREE_AND_NULL(str) } #endif /* * Process all active XPath state objects. */ first = vctxt->xpathStates; sto = first; while (sto != head) { #ifdef DEBUG_IDC if (sto->type == XPATH_STATE_OBJ_TYPE_IDC_SELECTOR) xmlGenericError(xmlGenericErrorContext, "IDC: ['%s'] selector '%s'\n", sto->matcher->aidc->def->name, sto->sel->xpath); else xmlGenericError(xmlGenericErrorContext, "IDC: ['%s'] field '%s'\n", sto->matcher->aidc->def->name, sto->sel->xpath); #endif if (nodeType == XML_ELEMENT_NODE) res = xmlStreamPush((xmlStreamCtxtPtr) sto->xpathCtxt, vctxt->inode->localName, vctxt->inode->nsName); else res = xmlStreamPushAttr((xmlStreamCtxtPtr) sto->xpathCtxt, vctxt->inode->localName, vctxt->inode->nsName); if (res == -1) { VERROR_INT("xmlSchemaXPathEvaluate", "calling xmlStreamPush()"); return (-1); } if (res == 0) goto next_sto; /* * Full match. */ #ifdef DEBUG_IDC xmlGenericError(xmlGenericErrorContext, "IDC: " "MATCH\n"); #endif /* * Register a match in the state object history. */ if (sto->history == NULL) { sto->history = (int *) xmlMalloc(5 * sizeof(int)); if (sto->history == NULL) { xmlSchemaVErrMemory(NULL, "allocating the state object history", NULL); return(-1); } sto->sizeHistory = 5; } else if (sto->sizeHistory <= sto->nbHistory) { sto->sizeHistory *= 2; sto->history = (int *) xmlRealloc(sto->history, sto->sizeHistory * sizeof(int)); if (sto->history == NULL) { xmlSchemaVErrMemory(NULL, "re-allocating the state object history", NULL); return(-1); } } sto->history[sto->nbHistory++] = depth; #ifdef DEBUG_IDC xmlGenericError(xmlGenericErrorContext, "IDC: push match '%d'\n", vctxt->depth); #endif if (sto->type == XPATH_STATE_OBJ_TYPE_IDC_SELECTOR) { xmlSchemaIDCSelectPtr sel; /* * Activate state objects for the IDC fields of * the IDC selector. */ #ifdef DEBUG_IDC xmlGenericError(xmlGenericErrorContext, "IDC: " "activating field states\n"); #endif sel = sto->matcher->aidc->def->fields; while (sel != NULL) { if (xmlSchemaIDCAddStateObject(vctxt, sto->matcher, sel, XPATH_STATE_OBJ_TYPE_IDC_FIELD) == -1) return (-1); sel = sel->next; } } else if (sto->type == XPATH_STATE_OBJ_TYPE_IDC_FIELD) { /* * An IDC key node was found by the IDC field. */ #ifdef DEBUG_IDC xmlGenericError(xmlGenericErrorContext, "IDC: key found\n"); #endif /* * Notify that the character value of this node is * needed. */ if (resolved == 0) { if ((vctxt->inode->flags & XML_SCHEMA_NODE_INFO_VALUE_NEEDED) == 0) vctxt->inode->flags |= XML_SCHEMA_NODE_INFO_VALUE_NEEDED; } resolved++; } next_sto: if (sto->next == NULL) { /* * Evaluate field state objects created on this node as well. */ head = first; sto = vctxt->xpathStates; } else sto = sto->next; } return (resolved); } static const xmlChar * xmlSchemaFormatIDCKeySequence_1(xmlSchemaValidCtxtPtr vctxt, xmlChar **buf, xmlSchemaPSVIIDCKeyPtr *seq, int count, int for_hash) { int i, res; xmlChar *value = NULL; *buf = xmlStrdup(BAD_CAST "["); for (i = 0; i < count; i++) { *buf = xmlStrcat(*buf, BAD_CAST "'"); if (!for_hash) res = xmlSchemaGetCanonValueWhtspExt(seq[i]->val, xmlSchemaGetWhiteSpaceFacetValue(seq[i]->type), &value); else { res = xmlSchemaGetCanonValueHash(seq[i]->val, &value); } if (res == 0) *buf = xmlStrcat(*buf, BAD_CAST value); else { VERROR_INT("xmlSchemaFormatIDCKeySequence", "failed to compute a canonical value"); *buf = xmlStrcat(*buf, BAD_CAST "???"); } if (i < count -1) *buf = xmlStrcat(*buf, BAD_CAST "', "); else *buf = xmlStrcat(*buf, BAD_CAST "'"); if (value != NULL) { xmlFree(value); value = NULL; } } *buf = xmlStrcat(*buf, BAD_CAST "]"); return (BAD_CAST *buf); } static const xmlChar * xmlSchemaFormatIDCKeySequence(xmlSchemaValidCtxtPtr vctxt, xmlChar **buf, xmlSchemaPSVIIDCKeyPtr *seq, int count) { return xmlSchemaFormatIDCKeySequence_1(vctxt, buf, seq, count, 0); } static const xmlChar * xmlSchemaHashKeySequence(xmlSchemaValidCtxtPtr vctxt, xmlChar **buf, xmlSchemaPSVIIDCKeyPtr *seq, int count) { return xmlSchemaFormatIDCKeySequence_1(vctxt, buf, seq, count, 1); } /** * xmlSchemaXPathPop: * @vctxt: the WXS validation context * * Pops all XPath states. * * Returns 0 on success and -1 on internal errors. */ static int xmlSchemaXPathPop(xmlSchemaValidCtxtPtr vctxt) { xmlSchemaIDCStateObjPtr sto; int res; if (vctxt->xpathStates == NULL) return(0); sto = vctxt->xpathStates; do { res = xmlStreamPop((xmlStreamCtxtPtr) sto->xpathCtxt); if (res == -1) return (-1); sto = sto->next; } while (sto != NULL); return(0); } /** * xmlSchemaXPathProcessHistory: * @vctxt: the WXS validation context * @type: the simple/complex type of the current node if any at all * @val: the precompiled value * * Processes and pops the history items of the IDC state objects. * IDC key-sequences are validated/created on IDC bindings. * * Returns 0 on success and -1 on internal errors. */ static int xmlSchemaXPathProcessHistory(xmlSchemaValidCtxtPtr vctxt, int depth) { xmlSchemaIDCStateObjPtr sto, nextsto; int res, matchDepth; xmlSchemaPSVIIDCKeyPtr key = NULL; xmlSchemaTypePtr type = vctxt->inode->typeDef, simpleType = NULL; if (vctxt->xpathStates == NULL) return (0); sto = vctxt->xpathStates; #ifdef DEBUG_IDC { xmlChar *str = NULL; xmlGenericError(xmlGenericErrorContext, "IDC: BACK on %s, depth %d\n", xmlSchemaFormatQName(&str, vctxt->inode->nsName, vctxt->inode->localName), vctxt->depth); FREE_AND_NULL(str) } #endif /* * Evaluate the state objects. */ while (sto != NULL) { res = xmlStreamPop((xmlStreamCtxtPtr) sto->xpathCtxt); if (res == -1) { VERROR_INT("xmlSchemaXPathProcessHistory", "calling xmlStreamPop()"); return (-1); } #ifdef DEBUG_IDC xmlGenericError(xmlGenericErrorContext, "IDC: stream pop '%s'\n", sto->sel->xpath); #endif if (sto->nbHistory == 0) goto deregister_check; matchDepth = sto->history[sto->nbHistory -1]; /* * Only matches at the current depth are of interest. */ if (matchDepth != depth) { sto = sto->next; continue; } if (sto->type == XPATH_STATE_OBJ_TYPE_IDC_FIELD) { /* * NOTE: According to * http://www.w3.org/Bugs/Public/show_bug.cgi?id=2198 * ... the simple-content of complex types is also allowed. */ if (WXS_IS_COMPLEX(type)) { if (WXS_HAS_SIMPLE_CONTENT(type)) { /* * Sanity check for complex types with simple content. */ simpleType = type->contentTypeDef; if (simpleType == NULL) { VERROR_INT("xmlSchemaXPathProcessHistory", "field resolves to a CT with simple content " "but the CT is missing the ST definition"); return (-1); } } else simpleType = NULL; } else simpleType = type; if (simpleType == NULL) { xmlChar *str = NULL; /* * Not qualified if the field resolves to a node of non * simple type. */ xmlSchemaCustomErr(ACTXT_CAST vctxt, XML_SCHEMAV_CVC_IDC, NULL, WXS_BASIC_CAST sto->matcher->aidc->def, "The XPath '%s' of a field of %s does evaluate to a node of " "non-simple type", sto->sel->xpath, xmlSchemaGetIDCDesignation(&str, sto->matcher->aidc->def)); FREE_AND_NULL(str); sto->nbHistory--; goto deregister_check; } if ((key == NULL) && (vctxt->inode->val == NULL)) { /* * Failed to provide the normalized value; maybe * the value was invalid. */ VERROR(XML_SCHEMAV_CVC_IDC, WXS_BASIC_CAST sto->matcher->aidc->def, "Warning: No precomputed value available, the value " "was either invalid or something strange happened"); sto->nbHistory--; goto deregister_check; } else { xmlSchemaIDCMatcherPtr matcher = sto->matcher; xmlSchemaPSVIIDCKeyPtr *keySeq; int pos, idx; /* * The key will be anchored on the matcher's list of * key-sequences. The position in this list is determined * by the target node's depth relative to the matcher's * depth of creation (i.e. the depth of the scope element). * * Element Depth Pos List-entries * <scope> 0 NULL * <bar> 1 NULL * <target/> 2 2 target * <bar> * </scope> * * The size of the list is only dependent on the depth of * the tree. * An entry will be NULLed in selector_leave, i.e. when * we hit the target's */ pos = sto->depth - matcher->depth; idx = sto->sel->index; /* * Create/grow the array of key-sequences. */ if (matcher->keySeqs == NULL) { if (pos > 9) matcher->sizeKeySeqs = pos * 2; else matcher->sizeKeySeqs = 10; matcher->keySeqs = (xmlSchemaPSVIIDCKeyPtr **) xmlMalloc(matcher->sizeKeySeqs * sizeof(xmlSchemaPSVIIDCKeyPtr *)); if (matcher->keySeqs == NULL) { xmlSchemaVErrMemory(NULL, "allocating an array of key-sequences", NULL); return(-1); } memset(matcher->keySeqs, 0, matcher->sizeKeySeqs * sizeof(xmlSchemaPSVIIDCKeyPtr *)); } else if (pos >= matcher->sizeKeySeqs) { int i = matcher->sizeKeySeqs; matcher->sizeKeySeqs *= 2; matcher->keySeqs = (xmlSchemaPSVIIDCKeyPtr **) xmlRealloc(matcher->keySeqs, matcher->sizeKeySeqs * sizeof(xmlSchemaPSVIIDCKeyPtr *)); if (matcher->keySeqs == NULL) { xmlSchemaVErrMemory(NULL, "reallocating an array of key-sequences", NULL); return (-1); } /* * The array needs to be NULLed. * TODO: Use memset? */ for (; i < matcher->sizeKeySeqs; i++) matcher->keySeqs[i] = NULL; } /* * Get/create the key-sequence. */ keySeq = matcher->keySeqs[pos]; if (keySeq == NULL) { goto create_sequence; } else if (keySeq[idx] != NULL) { xmlChar *str = NULL; /* * cvc-identity-constraint: * 3 For each node in the `target node set` all * of the {fields}, with that node as the context * node, evaluate to either an empty node-set or * a node-set with exactly one member, which must * have a simple type. * * The key was already set; report an error. */ xmlSchemaCustomErr(ACTXT_CAST vctxt, XML_SCHEMAV_CVC_IDC, NULL, WXS_BASIC_CAST matcher->aidc->def, "The XPath '%s' of a field of %s evaluates to a " "node-set with more than one member", sto->sel->xpath, xmlSchemaGetIDCDesignation(&str, matcher->aidc->def)); FREE_AND_NULL(str); sto->nbHistory--; goto deregister_check; } else goto create_key; create_sequence: /* * Create a key-sequence. */ keySeq = (xmlSchemaPSVIIDCKeyPtr *) xmlMalloc( matcher->aidc->def->nbFields * sizeof(xmlSchemaPSVIIDCKeyPtr)); if (keySeq == NULL) { xmlSchemaVErrMemory(NULL, "allocating an IDC key-sequence", NULL); return(-1); } memset(keySeq, 0, matcher->aidc->def->nbFields * sizeof(xmlSchemaPSVIIDCKeyPtr)); matcher->keySeqs[pos] = keySeq; create_key: /* * Create a key once per node only. */ if (key == NULL) { key = (xmlSchemaPSVIIDCKeyPtr) xmlMalloc( sizeof(xmlSchemaPSVIIDCKey)); if (key == NULL) { xmlSchemaVErrMemory(NULL, "allocating a IDC key", NULL); xmlFree(keySeq); matcher->keySeqs[pos] = NULL; return(-1); } /* * Consume the compiled value. */ key->type = simpleType; key->val = vctxt->inode->val; vctxt->inode->val = NULL; /* * Store the key in a global list. */ if (xmlSchemaIDCStoreKey(vctxt, key) == -1) { xmlSchemaIDCFreeKey(key); return (-1); } } keySeq[idx] = key; } } else if (sto->type == XPATH_STATE_OBJ_TYPE_IDC_SELECTOR) { xmlSchemaPSVIIDCKeyPtr **keySeq = NULL; /* xmlSchemaPSVIIDCBindingPtr bind; */ xmlSchemaPSVIIDCNodePtr ntItem; xmlSchemaIDCMatcherPtr matcher; xmlSchemaIDCPtr idc; xmlSchemaItemListPtr targets; int pos, i, j, nbKeys; /* * Here we have the following scenario: * An IDC 'selector' state object resolved to a target node, * during the time this target node was in the * ancestor-or-self axis, the 'field' state object(s) looked * out for matching nodes to create a key-sequence for this * target node. Now we are back to this target node and need * to put the key-sequence, together with the target node * itself, into the node-table of the corresponding IDC * binding. */ matcher = sto->matcher; idc = matcher->aidc->def; nbKeys = idc->nbFields; pos = depth - matcher->depth; /* * Check if the matcher has any key-sequences at all, plus * if it has a key-sequence for the current target node. */ if ((matcher->keySeqs == NULL) || (matcher->sizeKeySeqs <= pos)) { if (idc->type == XML_SCHEMA_TYPE_IDC_KEY) goto selector_key_error; else goto selector_leave; } keySeq = &(matcher->keySeqs[pos]); if (*keySeq == NULL) { if (idc->type == XML_SCHEMA_TYPE_IDC_KEY) goto selector_key_error; else goto selector_leave; } for (i = 0; i < nbKeys; i++) { if ((*keySeq)[i] == NULL) { /* * Not qualified, if not all fields did resolve. */ if (idc->type == XML_SCHEMA_TYPE_IDC_KEY) { /* * All fields of a "key" IDC must resolve. */ goto selector_key_error; } goto selector_leave; } } /* * All fields did resolve. */ /* * 4.1 If the {identity-constraint category} is unique(/key), * then no two members of the `qualified node set` have * `key-sequences` whose members are pairwise equal, as * defined by Equal in [XML Schemas: Datatypes]. * * Get the IDC binding from the matcher and check for * duplicate key-sequences. */ #if 0 bind = xmlSchemaIDCAcquireBinding(vctxt, matcher); #endif targets = xmlSchemaIDCAcquireTargetList(vctxt, matcher); if ((idc->type != XML_SCHEMA_TYPE_IDC_KEYREF) && (targets->nbItems != 0)) { xmlSchemaPSVIIDCKeyPtr ckey, bkey, *bkeySeq; xmlIDCHashEntryPtr e; res = 0; if (!matcher->htab) e = NULL; else { xmlChar *value = NULL; xmlSchemaHashKeySequence(vctxt, &value, *keySeq, nbKeys); e = xmlHashLookup(matcher->htab, value); FREE_AND_NULL(value); } /* * Compare the key-sequences, key by key. */ for (;e; e = e->next) { bkeySeq = ((xmlSchemaPSVIIDCNodePtr) targets->items[e->index])->keys; for (j = 0; j < nbKeys; j++) { ckey = (*keySeq)[j]; bkey = bkeySeq[j]; res = xmlSchemaAreValuesEqual(ckey->val, bkey->val); if (res == -1) { return (-1); } else if (res == 0) { /* * One of the keys differs, so the key-sequence * won't be equal; get out. */ break; } } if (res == 1) { /* * Duplicate key-sequence found. */ break; } } if (e) { xmlChar *str = NULL, *strB = NULL; /* * TODO: Try to report the key-sequence. */ xmlSchemaCustomErr(ACTXT_CAST vctxt, XML_SCHEMAV_CVC_IDC, NULL, WXS_BASIC_CAST idc, "Duplicate key-sequence %s in %s", xmlSchemaFormatIDCKeySequence(vctxt, &str, (*keySeq), nbKeys), xmlSchemaGetIDCDesignation(&strB, idc)); FREE_AND_NULL(str); FREE_AND_NULL(strB); goto selector_leave; } } /* * Add a node-table item to the IDC binding. */ ntItem = (xmlSchemaPSVIIDCNodePtr) xmlMalloc( sizeof(xmlSchemaPSVIIDCNode)); if (ntItem == NULL) { xmlSchemaVErrMemory(NULL, "allocating an IDC node-table item", NULL); xmlFree(*keySeq); *keySeq = NULL; return(-1); } memset(ntItem, 0, sizeof(xmlSchemaPSVIIDCNode)); /* * Store the node-table item in a global list. */ if (idc->type != XML_SCHEMA_TYPE_IDC_KEYREF) { if (xmlSchemaIDCStoreNodeTableItem(vctxt, ntItem) == -1) { xmlFree(ntItem); xmlFree(*keySeq); *keySeq = NULL; return (-1); } ntItem->nodeQNameID = -1; } else { /* * Save a cached QName for this node on the IDC node, to be * able to report it, even if the node is not saved. */ ntItem->nodeQNameID = xmlSchemaVAddNodeQName(vctxt, vctxt->inode->localName, vctxt->inode->nsName); if (ntItem->nodeQNameID == -1) { xmlFree(ntItem); xmlFree(*keySeq); *keySeq = NULL; return (-1); } } /* * Init the node-table item: Save the node, position and * consume the key-sequence. */ ntItem->node = vctxt->node; ntItem->nodeLine = vctxt->inode->nodeLine; ntItem->keys = *keySeq; *keySeq = NULL; #if 0 if (xmlSchemaIDCAppendNodeTableItem(bind, ntItem) == -1) #endif if (xmlSchemaItemListAdd(targets, ntItem) == -1) { if (idc->type == XML_SCHEMA_TYPE_IDC_KEYREF) { /* * Free the item, since keyref items won't be * put on a global list. */ xmlFree(ntItem->keys); xmlFree(ntItem); } return (-1); } if (idc->type != XML_SCHEMA_TYPE_IDC_KEYREF) { xmlChar *value = NULL; xmlIDCHashEntryPtr r, e; if (!matcher->htab) matcher->htab = xmlHashCreate(4); xmlSchemaHashKeySequence(vctxt, &value, ntItem->keys, nbKeys); e = xmlMalloc(sizeof *e); e->index = targets->nbItems - 1; r = xmlHashLookup(matcher->htab, value); if (r) { e->next = r->next; r->next = e; } else { e->next = NULL; xmlHashAddEntry(matcher->htab, value, e); } FREE_AND_NULL(value); } goto selector_leave; selector_key_error: { xmlChar *str = NULL; /* * 4.2.1 (KEY) The `target node set` and the * `qualified node set` are equal, that is, every * member of the `target node set` is also a member * of the `qualified node set` and vice versa. */ xmlSchemaCustomErr(ACTXT_CAST vctxt, XML_SCHEMAV_CVC_IDC, NULL, WXS_BASIC_CAST idc, "Not all fields of %s evaluate to a node", xmlSchemaGetIDCDesignation(&str, idc), NULL); FREE_AND_NULL(str); } selector_leave: /* * Free the key-sequence if not added to the IDC table. */ if ((keySeq != NULL) && (*keySeq != NULL)) { xmlFree(*keySeq); *keySeq = NULL; } } /* if selector */ sto->nbHistory--; deregister_check: /* * Deregister state objects if they reach the depth of creation. */ if ((sto->nbHistory == 0) && (sto->depth == depth)) { #ifdef DEBUG_IDC xmlGenericError(xmlGenericErrorContext, "IDC: STO pop '%s'\n", sto->sel->xpath); #endif if (vctxt->xpathStates != sto) { VERROR_INT("xmlSchemaXPathProcessHistory", "The state object to be removed is not the first " "in the list"); } nextsto = sto->next; /* * Unlink from the list of active XPath state objects. */ vctxt->xpathStates = sto->next; sto->next = vctxt->xpathStatePool; /* * Link it to the pool of reusable state objects. */ vctxt->xpathStatePool = sto; sto = nextsto; } else sto = sto->next; } /* while (sto != NULL) */ return (0); } /** * xmlSchemaIDCRegisterMatchers: * @vctxt: the WXS validation context * @elemDecl: the element declaration * * Creates helper objects to evaluate IDC selectors/fields * successively. * * Returns 0 if OK and -1 on internal errors. */ static int xmlSchemaIDCRegisterMatchers(xmlSchemaValidCtxtPtr vctxt, xmlSchemaElementPtr elemDecl) { xmlSchemaIDCMatcherPtr matcher, last = NULL; xmlSchemaIDCPtr idc, refIdc; xmlSchemaIDCAugPtr aidc; idc = (xmlSchemaIDCPtr) elemDecl->idcs; if (idc == NULL) return (0); #ifdef DEBUG_IDC { xmlChar *str = NULL; xmlGenericError(xmlGenericErrorContext, "IDC: REGISTER on %s, depth %d\n", (char *) xmlSchemaFormatQName(&str, vctxt->inode->nsName, vctxt->inode->localName), vctxt->depth); FREE_AND_NULL(str) } #endif if (vctxt->inode->idcMatchers != NULL) { VERROR_INT("xmlSchemaIDCRegisterMatchers", "The chain of IDC matchers is expected to be empty"); return (-1); } do { if (idc->type == XML_SCHEMA_TYPE_IDC_KEYREF) { /* * Since IDCs bubbles are expensive we need to know the * depth at which the bubbles should stop; this will be * the depth of the top-most keyref IDC. If no keyref * references a key/unique IDC, the keyrefDepth will * be -1, indicating that no bubbles are needed. */ refIdc = (xmlSchemaIDCPtr) idc->ref->item; if (refIdc != NULL) { /* * Remember that we have keyrefs on this node. */ vctxt->inode->hasKeyrefs = 1; /* * Lookup the referenced augmented IDC info. */ aidc = vctxt->aidcs; while (aidc != NULL) { if (aidc->def == refIdc) break; aidc = aidc->next; } if (aidc == NULL) { VERROR_INT("xmlSchemaIDCRegisterMatchers", "Could not find an augmented IDC item for an IDC " "definition"); return (-1); } if ((aidc->keyrefDepth == -1) || (vctxt->depth < aidc->keyrefDepth)) aidc->keyrefDepth = vctxt->depth; } } /* * Lookup the augmented IDC item for the IDC definition. */ aidc = vctxt->aidcs; while (aidc != NULL) { if (aidc->def == idc) break; aidc = aidc->next; } if (aidc == NULL) { VERROR_INT("xmlSchemaIDCRegisterMatchers", "Could not find an augmented IDC item for an IDC definition"); return (-1); } /* * Create an IDC matcher for every IDC definition. */ if (vctxt->idcMatcherCache != NULL) { /* * Reuse a cached matcher. */ matcher = vctxt->idcMatcherCache; vctxt->idcMatcherCache = matcher->nextCached; matcher->nextCached = NULL; } else { matcher = (xmlSchemaIDCMatcherPtr) xmlMalloc(sizeof(xmlSchemaIDCMatcher)); if (matcher == NULL) { xmlSchemaVErrMemory(vctxt, "allocating an IDC matcher", NULL); return (-1); } memset(matcher, 0, sizeof(xmlSchemaIDCMatcher)); } if (last == NULL) vctxt->inode->idcMatchers = matcher; else last->next = matcher; last = matcher; matcher->type = IDC_MATCHER; matcher->depth = vctxt->depth; matcher->aidc = aidc; matcher->idcType = aidc->def->type; #ifdef DEBUG_IDC xmlGenericError(xmlGenericErrorContext, "IDC: register matcher\n"); #endif /* * Init the automaton state object. */ if (xmlSchemaIDCAddStateObject(vctxt, matcher, idc->selector, XPATH_STATE_OBJ_TYPE_IDC_SELECTOR) == -1) return (-1); idc = idc->next; } while (idc != NULL); return (0); } static int xmlSchemaIDCFillNodeTables(xmlSchemaValidCtxtPtr vctxt, xmlSchemaNodeInfoPtr ielem) { xmlSchemaPSVIIDCBindingPtr bind; int res, i, j, k, nbTargets, nbFields, nbDupls, nbNodeTable; xmlSchemaPSVIIDCKeyPtr *keys, *ntkeys; xmlSchemaPSVIIDCNodePtr *targets, *dupls; xmlSchemaIDCMatcherPtr matcher = ielem->idcMatchers; /* vctxt->createIDCNodeTables */ while (matcher != NULL) { /* * Skip keyref IDCs and empty IDC target-lists. */ if ((matcher->aidc->def->type == XML_SCHEMA_TYPE_IDC_KEYREF) || WXS_ILIST_IS_EMPTY(matcher->targets)) { matcher = matcher->next; continue; } /* * If we _want_ the IDC node-table to be created in any case * then do so. Otherwise create them only if keyrefs need them. */ if ((! vctxt->createIDCNodeTables) && ((matcher->aidc->keyrefDepth == -1) || (matcher->aidc->keyrefDepth > vctxt->depth))) { matcher = matcher->next; continue; } /* * Get/create the IDC binding on this element for the IDC definition. */ bind = xmlSchemaIDCAcquireBinding(vctxt, matcher); if (bind == NULL) goto internal_error; if (! WXS_ILIST_IS_EMPTY(bind->dupls)) { dupls = (xmlSchemaPSVIIDCNodePtr *) bind->dupls->items; nbDupls = bind->dupls->nbItems; } else { dupls = NULL; nbDupls = 0; } if (bind->nodeTable != NULL) { nbNodeTable = bind->nbNodes; } else { nbNodeTable = 0; } if ((nbNodeTable == 0) && (nbDupls == 0)) { /* * Transfer all IDC target-nodes to the IDC node-table. */ bind->nodeTable = (xmlSchemaPSVIIDCNodePtr *) matcher->targets->items; bind->sizeNodes = matcher->targets->sizeItems; bind->nbNodes = matcher->targets->nbItems; matcher->targets->items = NULL; matcher->targets->sizeItems = 0; matcher->targets->nbItems = 0; if (matcher->htab) { xmlHashFree(matcher->htab, xmlFreeIDCHashEntry); matcher->htab = NULL; } } else { /* * Compare the key-sequences and add to the IDC node-table. */ nbTargets = matcher->targets->nbItems; targets = (xmlSchemaPSVIIDCNodePtr *) matcher->targets->items; nbFields = matcher->aidc->def->nbFields; i = 0; do { keys = targets[i]->keys; if (nbDupls) { /* * Search in already found duplicates first. */ j = 0; do { if (nbFields == 1) { res = xmlSchemaAreValuesEqual(keys[0]->val, dupls[j]->keys[0]->val); if (res == -1) goto internal_error; if (res == 1) { /* * Equal key-sequence. */ goto next_target; } } else { res = 0; ntkeys = dupls[j]->keys; for (k = 0; k < nbFields; k++) { res = xmlSchemaAreValuesEqual(keys[k]->val, ntkeys[k]->val); if (res == -1) goto internal_error; if (res == 0) { /* * One of the keys differs. */ break; } } if (res == 1) { /* * Equal key-sequence found. */ goto next_target; } } j++; } while (j < nbDupls); } if (nbNodeTable) { j = 0; do { if (nbFields == 1) { res = xmlSchemaAreValuesEqual(keys[0]->val, bind->nodeTable[j]->keys[0]->val); if (res == -1) goto internal_error; if (res == 0) { /* * The key-sequence differs. */ goto next_node_table_entry; } } else { res = 0; ntkeys = bind->nodeTable[j]->keys; for (k = 0; k < nbFields; k++) { res = xmlSchemaAreValuesEqual(keys[k]->val, ntkeys[k]->val); if (res == -1) goto internal_error; if (res == 0) { /* * One of the keys differs. */ goto next_node_table_entry; } } } /* * Add the duplicate to the list of duplicates. */ if (bind->dupls == NULL) { bind->dupls = xmlSchemaItemListCreate(); if (bind->dupls == NULL) goto internal_error; } if (xmlSchemaItemListAdd(bind->dupls, bind->nodeTable[j]) == -1) goto internal_error; /* * Remove the duplicate entry from the IDC node-table. */ bind->nodeTable[j] = bind->nodeTable[bind->nbNodes -1]; bind->nbNodes--; goto next_target; next_node_table_entry: j++; } while (j < nbNodeTable); } /* * If everything is fine, then add the IDC target-node to * the IDC node-table. */ if (xmlSchemaIDCAppendNodeTableItem(bind, targets[i]) == -1) goto internal_error; next_target: i++; } while (i < nbTargets); } matcher = matcher->next; } return(0); internal_error: return(-1); } /** * xmlSchemaBubbleIDCNodeTables: * @depth: the current tree depth * * Merges IDC bindings of an element at @depth into the corresponding IDC * bindings of its parent element. If a duplicate note-table entry is found, * both, the parent node-table entry and child entry are discarded from the * node-table of the parent. * * Returns 0 if OK and -1 on internal errors. */ static int xmlSchemaBubbleIDCNodeTables(xmlSchemaValidCtxtPtr vctxt) { xmlSchemaPSVIIDCBindingPtr bind; /* IDC bindings of the current node. */ xmlSchemaPSVIIDCBindingPtr *parTable, parBind = NULL; /* parent IDC bindings. */ xmlSchemaPSVIIDCNodePtr node, parNode = NULL, *dupls, *parNodes; /* node-table entries. */ xmlSchemaIDCAugPtr aidc; int i, j, k, ret = 0, nbFields, oldNum, oldDupls; bind = vctxt->inode->idcTable; if (bind == NULL) { /* Fine, no table, no bubbles. */ return (0); } parTable = &(vctxt->elemInfos[vctxt->depth -1]->idcTable); /* * Walk all bindings; create new or add to existing bindings. * Remove duplicate key-sequences. */ while (bind != NULL) { if ((bind->nbNodes == 0) && WXS_ILIST_IS_EMPTY(bind->dupls)) goto next_binding; /* * Check if the key/unique IDC table needs to be bubbled. */ if (! vctxt->createIDCNodeTables) { aidc = vctxt->aidcs; do { if (aidc->def == bind->definition) { if ((aidc->keyrefDepth == -1) || (aidc->keyrefDepth >= vctxt->depth)) { goto next_binding; } break; } aidc = aidc->next; } while (aidc != NULL); } if (parTable != NULL) parBind = *parTable; /* * Search a matching parent binding for the * IDC definition. */ while (parBind != NULL) { if (parBind->definition == bind->definition) break; parBind = parBind->next; } if (parBind != NULL) { /* * Compare every node-table entry of the child node, * i.e. the key-sequence within, ... */ oldNum = parBind->nbNodes; /* Skip newly added items. */ if (! WXS_ILIST_IS_EMPTY(parBind->dupls)) { oldDupls = parBind->dupls->nbItems; dupls = (xmlSchemaPSVIIDCNodePtr *) parBind->dupls->items; } else { dupls = NULL; oldDupls = 0; } parNodes = parBind->nodeTable; nbFields = bind->definition->nbFields; for (i = 0; i < bind->nbNodes; i++) { node = bind->nodeTable[i]; if (node == NULL) continue; /* * ...with every key-sequence of the parent node, already * evaluated to be a duplicate key-sequence. */ if (oldDupls) { j = 0; while (j < oldDupls) { if (nbFields == 1) { ret = xmlSchemaAreValuesEqual( node->keys[0]->val, dupls[j]->keys[0]->val); if (ret == -1) goto internal_error; if (ret == 0) { j++; continue; } } else { parNode = dupls[j]; for (k = 0; k < nbFields; k++) { ret = xmlSchemaAreValuesEqual( node->keys[k]->val, parNode->keys[k]->val); if (ret == -1) goto internal_error; if (ret == 0) break; } } if (ret == 1) /* Duplicate found. */ break; j++; } if (j != oldDupls) { /* Duplicate found. Skip this entry. */ continue; } } /* * ... and with every key-sequence of the parent node. */ if (oldNum) { j = 0; while (j < oldNum) { parNode = parNodes[j]; if (nbFields == 1) { ret = xmlSchemaAreValuesEqual( node->keys[0]->val, parNode->keys[0]->val); if (ret == -1) goto internal_error; if (ret == 0) { j++; continue; } } else { for (k = 0; k < nbFields; k++) { ret = xmlSchemaAreValuesEqual( node->keys[k]->val, parNode->keys[k]->val); if (ret == -1) goto internal_error; if (ret == 0) break; } } if (ret == 1) /* Duplicate found. */ break; j++; } if (j != oldNum) { /* * Handle duplicates. Move the duplicate in * the parent's node-table to the list of * duplicates. */ oldNum--; parBind->nbNodes--; /* * Move last old item to pos of duplicate. */ parNodes[j] = parNodes[oldNum]; if (parBind->nbNodes != oldNum) { /* * If new items exist, move last new item to * last of old items. */ parNodes[oldNum] = parNodes[parBind->nbNodes]; } if (parBind->dupls == NULL) { parBind->dupls = xmlSchemaItemListCreate(); if (parBind->dupls == NULL) goto internal_error; } xmlSchemaItemListAdd(parBind->dupls, parNode); } else { /* * Add the node-table entry (node and key-sequence) of * the child node to the node table of the parent node. */ if (parBind->nodeTable == NULL) { parBind->nodeTable = (xmlSchemaPSVIIDCNodePtr *) xmlMalloc(10 * sizeof(xmlSchemaPSVIIDCNodePtr)); if (parBind->nodeTable == NULL) { xmlSchemaVErrMemory(NULL, "allocating IDC list of node-table items", NULL); goto internal_error; } parBind->sizeNodes = 1; } else if (parBind->nbNodes >= parBind->sizeNodes) { parBind->sizeNodes *= 2; parBind->nodeTable = (xmlSchemaPSVIIDCNodePtr *) xmlRealloc(parBind->nodeTable, parBind->sizeNodes * sizeof(xmlSchemaPSVIIDCNodePtr)); if (parBind->nodeTable == NULL) { xmlSchemaVErrMemory(NULL, "re-allocating IDC list of node-table items", NULL); goto internal_error; } } parNodes = parBind->nodeTable; /* * Append the new node-table entry to the 'new node-table * entries' section. */ parNodes[parBind->nbNodes++] = node; } } } } else { /* * No binding for the IDC was found: create a new one and * copy all node-tables. */ parBind = xmlSchemaIDCNewBinding(bind->definition); if (parBind == NULL) goto internal_error; /* * TODO: Hmm, how to optimize the initial number of * allocated entries? */ if (bind->nbNodes != 0) { /* * Add all IDC node-table entries. */ if (! vctxt->psviExposeIDCNodeTables) { /* * Just move the entries. * NOTE: this is quite save here, since * all the keyref lookups have already been * performed. */ parBind->nodeTable = bind->nodeTable; bind->nodeTable = NULL; parBind->sizeNodes = bind->sizeNodes; bind->sizeNodes = 0; parBind->nbNodes = bind->nbNodes; bind->nbNodes = 0; } else { /* * Copy the entries. */ parBind->nodeTable = (xmlSchemaPSVIIDCNodePtr *) xmlMalloc(bind->nbNodes * sizeof(xmlSchemaPSVIIDCNodePtr)); if (parBind->nodeTable == NULL) { xmlSchemaVErrMemory(NULL, "allocating an array of IDC node-table " "items", NULL); xmlSchemaIDCFreeBinding(parBind); goto internal_error; } parBind->sizeNodes = bind->nbNodes; parBind->nbNodes = bind->nbNodes; memcpy(parBind->nodeTable, bind->nodeTable, bind->nbNodes * sizeof(xmlSchemaPSVIIDCNodePtr)); } } if (bind->dupls) { /* * Move the duplicates. */ if (parBind->dupls != NULL) xmlSchemaItemListFree(parBind->dupls); parBind->dupls = bind->dupls; bind->dupls = NULL; } if (parTable != NULL) { if (*parTable == NULL) *parTable = parBind; else { parBind->next = *parTable; *parTable = parBind; } } } next_binding: bind = bind->next; } return (0); internal_error: return(-1); } /** * xmlSchemaCheckCVCIDCKeyRef: * @vctxt: the WXS validation context * @elemDecl: the element declaration * * Check the cvc-idc-keyref constraints. */ static int xmlSchemaCheckCVCIDCKeyRef(xmlSchemaValidCtxtPtr vctxt) { xmlSchemaIDCMatcherPtr matcher; xmlSchemaPSVIIDCBindingPtr bind; matcher = vctxt->inode->idcMatchers; /* * Find a keyref. */ while (matcher != NULL) { if ((matcher->idcType == XML_SCHEMA_TYPE_IDC_KEYREF) && matcher->targets && matcher->targets->nbItems) { int i, j, k, res, nbFields, hasDupls; xmlSchemaPSVIIDCKeyPtr *refKeys, *keys; xmlSchemaPSVIIDCNodePtr refNode = NULL; xmlHashTablePtr table = NULL; nbFields = matcher->aidc->def->nbFields; /* * Find the IDC node-table for the referenced IDC key/unique. */ bind = vctxt->inode->idcTable; while (bind != NULL) { if ((xmlSchemaIDCPtr) matcher->aidc->def->ref->item == bind->definition) break; bind = bind->next; } hasDupls = (bind && bind->dupls && bind->dupls->nbItems) ? 1 : 0; /* * Search for a matching key-sequences. */ if (bind) { table = xmlHashCreate(bind->nbNodes * 2); for (j = 0; j < bind->nbNodes; j++) { xmlChar *value; xmlIDCHashEntryPtr r, e; keys = bind->nodeTable[j]->keys; xmlSchemaHashKeySequence(vctxt, &value, keys, nbFields); e = xmlMalloc(sizeof *e); e->index = j; r = xmlHashLookup(table, value); if (r) { e->next = r->next; r->next = e; } else { e->next = NULL; xmlHashAddEntry(table, value, e); } FREE_AND_NULL(value); } } for (i = 0; i < matcher->targets->nbItems; i++) { res = 0; refNode = matcher->targets->items[i]; if (bind != NULL) { xmlChar *value; xmlIDCHashEntryPtr e; refKeys = refNode->keys; xmlSchemaHashKeySequence(vctxt, &value, refKeys, nbFields); e = xmlHashLookup(table, value); FREE_AND_NULL(value); res = 0; for (;e; e = e->next) { keys = bind->nodeTable[e->index]->keys; for (k = 0; k < nbFields; k++) { res = xmlSchemaAreValuesEqual(keys[k]->val, refKeys[k]->val); if (res == 0) break; else if (res == -1) { return (-1); } } if (res == 1) { /* * Match found. */ break; } } if ((res == 0) && hasDupls) { /* * Search in duplicates */ for (j = 0; j < bind->dupls->nbItems; j++) { keys = ((xmlSchemaPSVIIDCNodePtr) bind->dupls->items[j])->keys; for (k = 0; k < nbFields; k++) { res = xmlSchemaAreValuesEqual(keys[k]->val, refKeys[k]->val); if (res == 0) break; else if (res == -1) { return (-1); } } if (res == 1) { /* * Match in duplicates found. */ xmlChar *str = NULL, *strB = NULL; xmlSchemaKeyrefErr(vctxt, XML_SCHEMAV_CVC_IDC, refNode, (xmlSchemaTypePtr) matcher->aidc->def, "More than one match found for " "key-sequence %s of keyref '%s'", xmlSchemaFormatIDCKeySequence(vctxt, &str, refNode->keys, nbFields), xmlSchemaGetComponentQName(&strB, matcher->aidc->def)); FREE_AND_NULL(str); FREE_AND_NULL(strB); break; } } } } if (res == 0) { xmlChar *str = NULL, *strB = NULL; xmlSchemaKeyrefErr(vctxt, XML_SCHEMAV_CVC_IDC, refNode, (xmlSchemaTypePtr) matcher->aidc->def, "No match found for key-sequence %s of keyref '%s'", xmlSchemaFormatIDCKeySequence(vctxt, &str, refNode->keys, nbFields), xmlSchemaGetComponentQName(&strB, matcher->aidc->def)); FREE_AND_NULL(str); FREE_AND_NULL(strB); } } if (table) { xmlHashFree(table, xmlFreeIDCHashEntry); } } matcher = matcher->next; } /* TODO: Return an error if any error encountered. */ return (0); } /************************************************************************ * * * XML Reader validation code * * * ************************************************************************/ static xmlSchemaAttrInfoPtr xmlSchemaGetFreshAttrInfo(xmlSchemaValidCtxtPtr vctxt) { xmlSchemaAttrInfoPtr iattr; /* * Grow/create list of attribute infos. */ if (vctxt->attrInfos == NULL) { vctxt->attrInfos = (xmlSchemaAttrInfoPtr *) xmlMalloc(sizeof(xmlSchemaAttrInfoPtr)); vctxt->sizeAttrInfos = 1; if (vctxt->attrInfos == NULL) { xmlSchemaVErrMemory(vctxt, "allocating attribute info list", NULL); return (NULL); } } else if (vctxt->sizeAttrInfos <= vctxt->nbAttrInfos) { vctxt->sizeAttrInfos++; vctxt->attrInfos = (xmlSchemaAttrInfoPtr *) xmlRealloc(vctxt->attrInfos, vctxt->sizeAttrInfos * sizeof(xmlSchemaAttrInfoPtr)); if (vctxt->attrInfos == NULL) { xmlSchemaVErrMemory(vctxt, "re-allocating attribute info list", NULL); return (NULL); } } else { iattr = vctxt->attrInfos[vctxt->nbAttrInfos++]; if (iattr->localName != NULL) { VERROR_INT("xmlSchemaGetFreshAttrInfo", "attr info not cleared"); return (NULL); } iattr->nodeType = XML_ATTRIBUTE_NODE; return (iattr); } /* * Create an attribute info. */ iattr = (xmlSchemaAttrInfoPtr) xmlMalloc(sizeof(xmlSchemaAttrInfo)); if (iattr == NULL) { xmlSchemaVErrMemory(vctxt, "creating new attribute info", NULL); return (NULL); } memset(iattr, 0, sizeof(xmlSchemaAttrInfo)); iattr->nodeType = XML_ATTRIBUTE_NODE; vctxt->attrInfos[vctxt->nbAttrInfos++] = iattr; return (iattr); } static int xmlSchemaValidatorPushAttribute(xmlSchemaValidCtxtPtr vctxt, xmlNodePtr attrNode, int nodeLine, const xmlChar *localName, const xmlChar *nsName, int ownedNames, xmlChar *value, int ownedValue) { xmlSchemaAttrInfoPtr attr; attr = xmlSchemaGetFreshAttrInfo(vctxt); if (attr == NULL) { VERROR_INT("xmlSchemaPushAttribute", "calling xmlSchemaGetFreshAttrInfo()"); return (-1); } attr->node = attrNode; attr->nodeLine = nodeLine; attr->state = XML_SCHEMAS_ATTR_UNKNOWN; attr->localName = localName; attr->nsName = nsName; if (ownedNames) attr->flags |= XML_SCHEMA_NODE_INFO_FLAG_OWNED_NAMES; /* * Evaluate if it's an XSI attribute. */ if (nsName != NULL) { if (xmlStrEqual(localName, BAD_CAST "nil")) { if (xmlStrEqual(attr->nsName, xmlSchemaInstanceNs)) { attr->metaType = XML_SCHEMA_ATTR_INFO_META_XSI_NIL; } } else if (xmlStrEqual(localName, BAD_CAST "type")) { if (xmlStrEqual(attr->nsName, xmlSchemaInstanceNs)) { attr->metaType = XML_SCHEMA_ATTR_INFO_META_XSI_TYPE; } } else if (xmlStrEqual(localName, BAD_CAST "schemaLocation")) { if (xmlStrEqual(attr->nsName, xmlSchemaInstanceNs)) { attr->metaType = XML_SCHEMA_ATTR_INFO_META_XSI_SCHEMA_LOC; } } else if (xmlStrEqual(localName, BAD_CAST "noNamespaceSchemaLocation")) { if (xmlStrEqual(attr->nsName, xmlSchemaInstanceNs)) { attr->metaType = XML_SCHEMA_ATTR_INFO_META_XSI_NO_NS_SCHEMA_LOC; } } else if (xmlStrEqual(attr->nsName, xmlNamespaceNs)) { attr->metaType = XML_SCHEMA_ATTR_INFO_META_XMLNS; } } attr->value = value; if (ownedValue) attr->flags |= XML_SCHEMA_NODE_INFO_FLAG_OWNED_VALUES; if (attr->metaType != 0) attr->state = XML_SCHEMAS_ATTR_META; return (0); } /** * xmlSchemaClearElemInfo: * @vctxt: the WXS validation context * @ielem: the element information item */ static void xmlSchemaClearElemInfo(xmlSchemaValidCtxtPtr vctxt, xmlSchemaNodeInfoPtr ielem) { ielem->hasKeyrefs = 0; ielem->appliedXPath = 0; if (ielem->flags & XML_SCHEMA_NODE_INFO_FLAG_OWNED_NAMES) { FREE_AND_NULL(ielem->localName); FREE_AND_NULL(ielem->nsName); } else { ielem->localName = NULL; ielem->nsName = NULL; } if (ielem->flags & XML_SCHEMA_NODE_INFO_FLAG_OWNED_VALUES) { FREE_AND_NULL(ielem->value); } else { ielem->value = NULL; } if (ielem->val != NULL) { /* * PSVI TODO: Be careful not to free it when the value is * exposed via PSVI. */ xmlSchemaFreeValue(ielem->val); ielem->val = NULL; } if (ielem->idcMatchers != NULL) { /* * REVISIT OPTIMIZE TODO: Use a pool of IDC matchers. * Does it work? */ xmlSchemaIDCReleaseMatcherList(vctxt, ielem->idcMatchers); #if 0 xmlSchemaIDCFreeMatcherList(ielem->idcMatchers); #endif ielem->idcMatchers = NULL; } if (ielem->idcTable != NULL) { /* * OPTIMIZE TODO: Use a pool of IDC tables??. */ xmlSchemaIDCFreeIDCTable(ielem->idcTable); ielem->idcTable = NULL; } if (ielem->regexCtxt != NULL) { xmlRegFreeExecCtxt(ielem->regexCtxt); ielem->regexCtxt = NULL; } if (ielem->nsBindings != NULL) { xmlFree((xmlChar **)ielem->nsBindings); ielem->nsBindings = NULL; ielem->nbNsBindings = 0; ielem->sizeNsBindings = 0; } } /** * xmlSchemaGetFreshElemInfo: * @vctxt: the schema validation context * * Creates/reuses and initializes the element info item for * the current tree depth. * * Returns the element info item or NULL on API or internal errors. */ static xmlSchemaNodeInfoPtr xmlSchemaGetFreshElemInfo(xmlSchemaValidCtxtPtr vctxt) { xmlSchemaNodeInfoPtr info = NULL; if (vctxt->depth > vctxt->sizeElemInfos) { VERROR_INT("xmlSchemaGetFreshElemInfo", "inconsistent depth encountered"); return (NULL); } if (vctxt->elemInfos == NULL) { vctxt->elemInfos = (xmlSchemaNodeInfoPtr *) xmlMalloc(10 * sizeof(xmlSchemaNodeInfoPtr)); if (vctxt->elemInfos == NULL) { xmlSchemaVErrMemory(vctxt, "allocating the element info array", NULL); return (NULL); } memset(vctxt->elemInfos, 0, 10 * sizeof(xmlSchemaNodeInfoPtr)); vctxt->sizeElemInfos = 10; } else if (vctxt->sizeElemInfos <= vctxt->depth) { int i = vctxt->sizeElemInfos; vctxt->sizeElemInfos *= 2; vctxt->elemInfos = (xmlSchemaNodeInfoPtr *) xmlRealloc(vctxt->elemInfos, vctxt->sizeElemInfos * sizeof(xmlSchemaNodeInfoPtr)); if (vctxt->elemInfos == NULL) { xmlSchemaVErrMemory(vctxt, "re-allocating the element info array", NULL); return (NULL); } /* * We need the new memory to be NULLed. * TODO: Use memset instead? */ for (; i < vctxt->sizeElemInfos; i++) vctxt->elemInfos[i] = NULL; } else info = vctxt->elemInfos[vctxt->depth]; if (info == NULL) { info = (xmlSchemaNodeInfoPtr) xmlMalloc(sizeof(xmlSchemaNodeInfo)); if (info == NULL) { xmlSchemaVErrMemory(vctxt, "allocating an element info", NULL); return (NULL); } vctxt->elemInfos[vctxt->depth] = info; } else { if (info->localName != NULL) { VERROR_INT("xmlSchemaGetFreshElemInfo", "elem info has not been cleared"); return (NULL); } } memset(info, 0, sizeof(xmlSchemaNodeInfo)); info->nodeType = XML_ELEMENT_NODE; info->depth = vctxt->depth; return (info); } #define ACTIVATE_ATTRIBUTE(item) vctxt->inode = (xmlSchemaNodeInfoPtr) item; #define ACTIVATE_ELEM vctxt->inode = vctxt->elemInfos[vctxt->depth]; #define ACTIVATE_PARENT_ELEM vctxt->inode = vctxt->elemInfos[vctxt->depth -1]; static int xmlSchemaValidateFacets(xmlSchemaAbstractCtxtPtr actxt, xmlNodePtr node, xmlSchemaTypePtr type, xmlSchemaValType valType, const xmlChar * value, xmlSchemaValPtr val, unsigned long length, int fireErrors) { int ret, error = 0, found; xmlSchemaTypePtr tmpType; xmlSchemaFacetLinkPtr facetLink; xmlSchemaFacetPtr facet; unsigned long len = 0; xmlSchemaWhitespaceValueType ws; /* * In Libxml2, derived built-in types have currently no explicit facets. */ if (type->type == XML_SCHEMA_TYPE_BASIC) return (0); /* * NOTE: Do not jump away, if the facetSet of the given type is * empty: until now, "pattern" and "enumeration" facets of the * *base types* need to be checked as well. */ if (type->facetSet == NULL) goto pattern_and_enum; if (! WXS_IS_ATOMIC(type)) { if (WXS_IS_LIST(type)) goto WXS_IS_LIST; else goto pattern_and_enum; } /* * Whitespace handling is only of importance for string-based * types. */ tmpType = xmlSchemaGetPrimitiveType(type); if ((tmpType->builtInType == XML_SCHEMAS_STRING) || WXS_IS_ANY_SIMPLE_TYPE(tmpType)) { ws = xmlSchemaGetWhiteSpaceFacetValue(type); } else ws = XML_SCHEMA_WHITESPACE_COLLAPSE; /* * If the value was not computed (for string or * anySimpleType based types), then use the provided * type. */ if (val != NULL) valType = xmlSchemaGetValType(val); ret = 0; for (facetLink = type->facetSet; facetLink != NULL; facetLink = facetLink->next) { /* * Skip the pattern "whiteSpace": it is used to * format the character content beforehand. */ switch (facetLink->facet->type) { case XML_SCHEMA_FACET_WHITESPACE: case XML_SCHEMA_FACET_PATTERN: case XML_SCHEMA_FACET_ENUMERATION: continue; case XML_SCHEMA_FACET_LENGTH: case XML_SCHEMA_FACET_MINLENGTH: case XML_SCHEMA_FACET_MAXLENGTH: ret = xmlSchemaValidateLengthFacetWhtsp(facetLink->facet, valType, value, val, &len, ws); break; default: ret = xmlSchemaValidateFacetWhtsp(facetLink->facet, ws, valType, value, val, ws); break; } if (ret < 0) { AERROR_INT("xmlSchemaValidateFacets", "validating against a atomic type facet"); return (-1); } else if (ret > 0) { if (fireErrors) xmlSchemaFacetErr(actxt, ret, node, value, len, type, facetLink->facet, NULL, NULL, NULL); else return (ret); if (error == 0) error = ret; } ret = 0; } WXS_IS_LIST: if (! WXS_IS_LIST(type)) goto pattern_and_enum; /* * "length", "minLength" and "maxLength" of list types. */ ret = 0; for (facetLink = type->facetSet; facetLink != NULL; facetLink = facetLink->next) { switch (facetLink->facet->type) { case XML_SCHEMA_FACET_LENGTH: case XML_SCHEMA_FACET_MINLENGTH: case XML_SCHEMA_FACET_MAXLENGTH: ret = xmlSchemaValidateListSimpleTypeFacet(facetLink->facet, value, length, NULL); break; default: continue; } if (ret < 0) { AERROR_INT("xmlSchemaValidateFacets", "validating against a list type facet"); return (-1); } else if (ret > 0) { if (fireErrors) xmlSchemaFacetErr(actxt, ret, node, value, length, type, facetLink->facet, NULL, NULL, NULL); else return (ret); if (error == 0) error = ret; } ret = 0; } pattern_and_enum: found = 0; /* * Process enumerations. Facet values are in the value space * of the defining type's base type. This seems to be a bug in the * XML Schema 1.0 spec. Use the whitespace type of the base type. * Only the first set of enumerations in the ancestor-or-self axis * is used for validation. */ ret = 0; tmpType = type; do { for (facet = tmpType->facets; facet != NULL; facet = facet->next) { if (facet->type != XML_SCHEMA_FACET_ENUMERATION) continue; found = 1; ret = xmlSchemaAreValuesEqual(facet->val, val); if (ret == 1) break; else if (ret < 0) { AERROR_INT("xmlSchemaValidateFacets", "validating against an enumeration facet"); return (-1); } } if (ret != 0) break; /* * Break on the first set of enumerations. Any additional * enumerations which might be existent on the ancestors * of the current type are restricted by this set; thus * *must* *not* be taken into account. */ if (found) break; tmpType = tmpType->baseType; } while ((tmpType != NULL) && (tmpType->type != XML_SCHEMA_TYPE_BASIC)); if (found && (ret == 0)) { ret = XML_SCHEMAV_CVC_ENUMERATION_VALID; if (fireErrors) { xmlSchemaFacetErr(actxt, ret, node, value, 0, type, NULL, NULL, NULL, NULL); } else return (ret); if (error == 0) error = ret; } /* * Process patters. Pattern facets are ORed at type level * and ANDed if derived. Walk the base type axis. */ tmpType = type; facet = NULL; do { found = 0; for (facetLink = tmpType->facetSet; facetLink != NULL; facetLink = facetLink->next) { if (facetLink->facet->type != XML_SCHEMA_FACET_PATTERN) continue; found = 1; /* * NOTE that for patterns, @value needs to be the * normalized value. */ ret = xmlRegexpExec(facetLink->facet->regexp, value); if (ret == 1) break; else if (ret < 0) { AERROR_INT("xmlSchemaValidateFacets", "validating against a pattern facet"); return (-1); } else { /* * Save the last non-validating facet. */ facet = facetLink->facet; } } if (found && (ret != 1)) { ret = XML_SCHEMAV_CVC_PATTERN_VALID; if (fireErrors) { xmlSchemaFacetErr(actxt, ret, node, value, 0, type, facet, NULL, NULL, NULL); } else return (ret); if (error == 0) error = ret; break; } tmpType = tmpType->baseType; } while ((tmpType != NULL) && (tmpType->type != XML_SCHEMA_TYPE_BASIC)); return (error); } static xmlChar * xmlSchemaNormalizeValue(xmlSchemaTypePtr type, const xmlChar *value) { switch (xmlSchemaGetWhiteSpaceFacetValue(type)) { case XML_SCHEMA_WHITESPACE_COLLAPSE: return (xmlSchemaCollapseString(value)); case XML_SCHEMA_WHITESPACE_REPLACE: return (xmlSchemaWhiteSpaceReplace(value)); default: return (NULL); } } static int xmlSchemaValidateQName(xmlSchemaValidCtxtPtr vctxt, const xmlChar *value, xmlSchemaValPtr *val, int valNeeded) { int ret; const xmlChar *nsName; xmlChar *local, *prefix = NULL; ret = xmlValidateQName(value, 1); if (ret != 0) { if (ret == -1) { VERROR_INT("xmlSchemaValidateQName", "calling xmlValidateQName()"); return (-1); } return( XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1); } /* * NOTE: xmlSplitQName2 will always return a duplicated * strings. */ local = xmlSplitQName2(value, &prefix); if (local == NULL) local = xmlStrdup(value); /* * OPTIMIZE TODO: Use flags for: * - is there any namespace binding? * - is there a default namespace? */ nsName = xmlSchemaLookupNamespace(vctxt, prefix); if (prefix != NULL) { xmlFree(prefix); /* * A namespace must be found if the prefix is * NOT NULL. */ if (nsName == NULL) { ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1; xmlSchemaCustomErr(ACTXT_CAST vctxt, ret, NULL, WXS_BASIC_CAST xmlSchemaGetBuiltInType(XML_SCHEMAS_QNAME), "The QName value '%s' has no " "corresponding namespace declaration in " "scope", value, NULL); if (local != NULL) xmlFree(local); return (ret); } } if (valNeeded && val) { if (nsName != NULL) *val = xmlSchemaNewQNameValue( BAD_CAST xmlStrdup(nsName), BAD_CAST local); else *val = xmlSchemaNewQNameValue(NULL, BAD_CAST local); } else xmlFree(local); return (0); } /* * cvc-simple-type */ static int xmlSchemaVCheckCVCSimpleType(xmlSchemaAbstractCtxtPtr actxt, xmlNodePtr node, xmlSchemaTypePtr type, const xmlChar *value, xmlSchemaValPtr *retVal, int fireErrors, int normalize, int isNormalized) { int ret = 0, valNeeded = (retVal) ? 1 : 0; xmlSchemaValPtr val = NULL; /* xmlSchemaWhitespaceValueType ws; */ xmlChar *normValue = NULL; #define NORMALIZE(atype) \ if ((! isNormalized) && \ (normalize || (type->flags & XML_SCHEMAS_TYPE_NORMVALUENEEDED))) { \ normValue = xmlSchemaNormalizeValue(atype, value); \ if (normValue != NULL) \ value = normValue; \ isNormalized = 1; \ } if ((retVal != NULL) && (*retVal != NULL)) { xmlSchemaFreeValue(*retVal); *retVal = NULL; } /* * 3.14.4 Simple Type Definition Validation Rules * Validation Rule: String Valid */ /* * 1 It is schema-valid with respect to that definition as defined * by Datatype Valid in [XML Schemas: Datatypes]. */ /* * 2.1 If The definition is ENTITY or is validly derived from ENTITY given * the empty set, as defined in Type Derivation OK (Simple) ($3.14.6), then * the string must be a `declared entity name`. */ /* * 2.2 If The definition is ENTITIES or is validly derived from ENTITIES * given the empty set, as defined in Type Derivation OK (Simple) ($3.14.6), * then every whitespace-delimited substring of the string must be a `declared * entity name`. */ /* * 2.3 otherwise no further condition applies. */ if ((! valNeeded) && (type->flags & XML_SCHEMAS_TYPE_FACETSNEEDVALUE)) valNeeded = 1; if (value == NULL) value = BAD_CAST ""; if (WXS_IS_ANY_SIMPLE_TYPE(type) || WXS_IS_ATOMIC(type)) { xmlSchemaTypePtr biType; /* The built-in type. */ /* * SPEC (1.2.1) "if {variety} is `atomic` then the string must `match` * a literal in the `lexical space` of {base type definition}" */ /* * Whitespace-normalize. */ NORMALIZE(type); if (type->type != XML_SCHEMA_TYPE_BASIC) { /* * Get the built-in type. */ biType = type->baseType; while ((biType != NULL) && (biType->type != XML_SCHEMA_TYPE_BASIC)) biType = biType->baseType; if (biType == NULL) { AERROR_INT("xmlSchemaVCheckCVCSimpleType", "could not get the built-in type"); goto internal_error; } } else biType = type; /* * NOTATIONs need to be processed here, since they need * to lookup in the hashtable of NOTATION declarations of the schema. */ if (actxt->type == XML_SCHEMA_CTXT_VALIDATOR) { switch (biType->builtInType) { case XML_SCHEMAS_NOTATION: ret = xmlSchemaValidateNotation( (xmlSchemaValidCtxtPtr) actxt, ((xmlSchemaValidCtxtPtr) actxt)->schema, NULL, value, &val, valNeeded); break; case XML_SCHEMAS_QNAME: ret = xmlSchemaValidateQName((xmlSchemaValidCtxtPtr) actxt, value, &val, valNeeded); break; default: /* ws = xmlSchemaGetWhiteSpaceFacetValue(type); */ if (valNeeded) ret = xmlSchemaValPredefTypeNodeNoNorm(biType, value, &val, node); else ret = xmlSchemaValPredefTypeNodeNoNorm(biType, value, NULL, node); break; } } else if (actxt->type == XML_SCHEMA_CTXT_PARSER) { switch (biType->builtInType) { case XML_SCHEMAS_NOTATION: ret = xmlSchemaValidateNotation(NULL, ((xmlSchemaParserCtxtPtr) actxt)->schema, node, value, &val, valNeeded); break; default: /* ws = xmlSchemaGetWhiteSpaceFacetValue(type); */ if (valNeeded) ret = xmlSchemaValPredefTypeNodeNoNorm(biType, value, &val, node); else ret = xmlSchemaValPredefTypeNodeNoNorm(biType, value, NULL, node); break; } } else { /* * Validation via a public API is not implemented yet. */ TODO goto internal_error; } if (ret != 0) { if (ret < 0) { AERROR_INT("xmlSchemaVCheckCVCSimpleType", "validating against a built-in type"); goto internal_error; } if (WXS_IS_LIST(type)) ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_2; else ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1; } if ((ret == 0) && (type->flags & XML_SCHEMAS_TYPE_HAS_FACETS)) { /* * Check facets. */ ret = xmlSchemaValidateFacets(actxt, node, type, (xmlSchemaValType) biType->builtInType, value, val, 0, fireErrors); if (ret != 0) { if (ret < 0) { AERROR_INT("xmlSchemaVCheckCVCSimpleType", "validating facets of atomic simple type"); goto internal_error; } if (WXS_IS_LIST(type)) ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_2; else ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1; } } else if (fireErrors && (ret > 0)) xmlSchemaSimpleTypeErr(actxt, ret, node, value, type, 1); } else if (WXS_IS_LIST(type)) { xmlSchemaTypePtr itemType; const xmlChar *cur, *end; xmlChar *tmpValue = NULL; unsigned long len = 0; xmlSchemaValPtr prevVal = NULL, curVal = NULL; /* 1.2.2 if {variety} is `list` then the string must be a sequence * of white space separated tokens, each of which `match`es a literal * in the `lexical space` of {item type definition} */ /* * Note that XML_SCHEMAS_TYPE_NORMVALUENEEDED will be set if * the list type has an enum or pattern facet. */ NORMALIZE(type); /* * VAL TODO: Optimize validation of empty values. * VAL TODO: We do not have computed values for lists. */ itemType = WXS_LIST_ITEMTYPE(type); cur = value; do { while (IS_BLANK_CH(*cur)) cur++; end = cur; while ((*end != 0) && (!(IS_BLANK_CH(*end)))) end++; if (end == cur) break; tmpValue = xmlStrndup(cur, end - cur); len++; if (valNeeded) ret = xmlSchemaVCheckCVCSimpleType(actxt, node, itemType, tmpValue, &curVal, fireErrors, 0, 1); else ret = xmlSchemaVCheckCVCSimpleType(actxt, node, itemType, tmpValue, NULL, fireErrors, 0, 1); FREE_AND_NULL(tmpValue); if (curVal != NULL) { /* * Add to list of computed values. */ if (val == NULL) val = curVal; else xmlSchemaValueAppend(prevVal, curVal); prevVal = curVal; curVal = NULL; } if (ret != 0) { if (ret < 0) { AERROR_INT("xmlSchemaVCheckCVCSimpleType", "validating an item of list simple type"); goto internal_error; } ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_2; break; } cur = end; } while (*cur != 0); FREE_AND_NULL(tmpValue); if ((ret == 0) && (type->flags & XML_SCHEMAS_TYPE_HAS_FACETS)) { /* * Apply facets (pattern, enumeration). */ ret = xmlSchemaValidateFacets(actxt, node, type, XML_SCHEMAS_UNKNOWN, value, val, len, fireErrors); if (ret != 0) { if (ret < 0) { AERROR_INT("xmlSchemaVCheckCVCSimpleType", "validating facets of list simple type"); goto internal_error; } ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_2; } } if (fireErrors && (ret > 0)) { /* * Report the normalized value. */ normalize = 1; NORMALIZE(type); xmlSchemaSimpleTypeErr(actxt, ret, node, value, type, 1); } } else if (WXS_IS_UNION(type)) { xmlSchemaTypeLinkPtr memberLink; /* * TODO: For all datatypes `derived` by `union` whiteSpace does * not apply directly; however, the normalization behavior of `union` * types is controlled by the value of whiteSpace on that one of the * `memberTypes` against which the `union` is successfully validated. * * This means that the value is normalized by the first validating * member type, then the facets of the union type are applied. This * needs changing of the value! */ /* * 1.2.3 if {variety} is `union` then the string must `match` a * literal in the `lexical space` of at least one member of * {member type definitions} */ memberLink = xmlSchemaGetUnionSimpleTypeMemberTypes(type); if (memberLink == NULL) { AERROR_INT("xmlSchemaVCheckCVCSimpleType", "union simple type has no member types"); goto internal_error; } /* * Always normalize union type values, since we currently * cannot store the whitespace information with the value * itself; otherwise a later value-comparison would be * not possible. */ while (memberLink != NULL) { if (valNeeded) ret = xmlSchemaVCheckCVCSimpleType(actxt, node, memberLink->type, value, &val, 0, 1, 0); else ret = xmlSchemaVCheckCVCSimpleType(actxt, node, memberLink->type, value, NULL, 0, 1, 0); if (ret <= 0) break; memberLink = memberLink->next; } if (ret != 0) { if (ret < 0) { AERROR_INT("xmlSchemaVCheckCVCSimpleType", "validating members of union simple type"); goto internal_error; } ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_3; } /* * Apply facets (pattern, enumeration). */ if ((ret == 0) && (type->flags & XML_SCHEMAS_TYPE_HAS_FACETS)) { /* * The normalization behavior of `union` types is controlled by * the value of whiteSpace on that one of the `memberTypes` * against which the `union` is successfully validated. */ NORMALIZE(memberLink->type); ret = xmlSchemaValidateFacets(actxt, node, type, XML_SCHEMAS_UNKNOWN, value, val, 0, fireErrors); if (ret != 0) { if (ret < 0) { AERROR_INT("xmlSchemaVCheckCVCSimpleType", "validating facets of union simple type"); goto internal_error; } ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_3; } } if (fireErrors && (ret > 0)) xmlSchemaSimpleTypeErr(actxt, ret, node, value, type, 1); } if (normValue != NULL) xmlFree(normValue); if (ret == 0) { if (retVal != NULL) *retVal = val; else if (val != NULL) xmlSchemaFreeValue(val); } else if (val != NULL) xmlSchemaFreeValue(val); return (ret); internal_error: if (normValue != NULL) xmlFree(normValue); if (val != NULL) xmlSchemaFreeValue(val); return (-1); } static int xmlSchemaVExpandQName(xmlSchemaValidCtxtPtr vctxt, const xmlChar *value, const xmlChar **nsName, const xmlChar **localName) { int ret = 0; if ((nsName == NULL) || (localName == NULL)) return (-1); *nsName = NULL; *localName = NULL; ret = xmlValidateQName(value, 1); if (ret == -1) return (-1); if (ret > 0) { xmlSchemaSimpleTypeErr(ACTXT_CAST vctxt, XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1, NULL, value, xmlSchemaGetBuiltInType(XML_SCHEMAS_QNAME), 1); return (1); } { xmlChar *local = NULL; xmlChar *prefix; /* * NOTE: xmlSplitQName2 will return a duplicated * string. */ local = xmlSplitQName2(value, &prefix); if (local == NULL) *localName = xmlDictLookup(vctxt->dict, value, -1); else { *localName = xmlDictLookup(vctxt->dict, local, -1); xmlFree(local); } *nsName = xmlSchemaLookupNamespace(vctxt, prefix); if (prefix != NULL) { xmlFree(prefix); /* * A namespace must be found if the prefix is NOT NULL. */ if (*nsName == NULL) { xmlSchemaCustomErr(ACTXT_CAST vctxt, XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1, NULL, WXS_BASIC_CAST xmlSchemaGetBuiltInType(XML_SCHEMAS_QNAME), "The QName value '%s' has no " "corresponding namespace declaration in scope", value, NULL); return (2); } } } return (0); } static int xmlSchemaProcessXSIType(xmlSchemaValidCtxtPtr vctxt, xmlSchemaAttrInfoPtr iattr, xmlSchemaTypePtr *localType, xmlSchemaElementPtr elemDecl) { int ret = 0; /* * cvc-elt (3.3.4) : (4) * AND * Schema-Validity Assessment (Element) (cvc-assess-elt) * (1.2.1.2.1) - (1.2.1.2.4) * Handle 'xsi:type'. */ if (localType == NULL) return (-1); *localType = NULL; if (iattr == NULL) return (0); else { const xmlChar *nsName = NULL, *local = NULL; /* * TODO: We should report a *warning* that the type was overridden * by the instance. */ ACTIVATE_ATTRIBUTE(iattr); /* * (cvc-elt) (3.3.4) : (4.1) * (cvc-assess-elt) (1.2.1.2.2) */ ret = xmlSchemaVExpandQName(vctxt, iattr->value, &nsName, &local); if (ret != 0) { if (ret < 0) { VERROR_INT("xmlSchemaValidateElementByDeclaration", "calling xmlSchemaQNameExpand() to validate the " "attribute 'xsi:type'"); goto internal_error; } goto exit; } /* * (cvc-elt) (3.3.4) : (4.2) * (cvc-assess-elt) (1.2.1.2.3) */ *localType = xmlSchemaGetType(vctxt->schema, local, nsName); if (*localType == NULL) { xmlChar *str = NULL; xmlSchemaCustomErr(ACTXT_CAST vctxt, XML_SCHEMAV_CVC_ELT_4_2, NULL, WXS_BASIC_CAST xmlSchemaGetBuiltInType(XML_SCHEMAS_QNAME), "The QName value '%s' of the xsi:type attribute does not " "resolve to a type definition", xmlSchemaFormatQName(&str, nsName, local), NULL); FREE_AND_NULL(str); ret = vctxt->err; goto exit; } if (elemDecl != NULL) { int set = 0; /* * SPEC cvc-elt (3.3.4) : (4.3) (Type Derivation OK) * "The `local type definition` must be validly * derived from the {type definition} given the union of * the {disallowed substitutions} and the {type definition}'s * {prohibited substitutions}, as defined in * Type Derivation OK (Complex) ($3.4.6) * (if it is a complex type definition), * or given {disallowed substitutions} as defined in Type * Derivation OK (Simple) ($3.14.6) (if it is a simple type * definition)." * * {disallowed substitutions}: the "block" on the element decl. * {prohibited substitutions}: the "block" on the type def. */ /* * OPTIMIZE TODO: We could map types already evaluated * to be validly derived from other types to avoid checking * this over and over for the same types. */ if ((elemDecl->flags & XML_SCHEMAS_ELEM_BLOCK_EXTENSION) || (elemDecl->subtypes->flags & XML_SCHEMAS_TYPE_BLOCK_EXTENSION)) set |= SUBSET_EXTENSION; if ((elemDecl->flags & XML_SCHEMAS_ELEM_BLOCK_RESTRICTION) || (elemDecl->subtypes->flags & XML_SCHEMAS_TYPE_BLOCK_RESTRICTION)) set |= SUBSET_RESTRICTION; /* * REMOVED and CHANGED since this produced a parser context * which adds to the string dict of the schema. So this would * change the schema and we don't want this. We don't need * the parser context anymore. * * if ((vctxt->pctxt == NULL) && * (xmlSchemaCreatePCtxtOnVCtxt(vctxt) == -1)) * return (-1); */ if (xmlSchemaCheckCOSDerivedOK(ACTXT_CAST vctxt, *localType, elemDecl->subtypes, set) != 0) { xmlChar *str = NULL; xmlSchemaCustomErr(ACTXT_CAST vctxt, XML_SCHEMAV_CVC_ELT_4_3, NULL, NULL, "The type definition '%s', specified by xsi:type, is " "blocked or not validly derived from the type definition " "of the element declaration", xmlSchemaFormatQName(&str, (*localType)->targetNamespace, (*localType)->name), NULL); FREE_AND_NULL(str); ret = vctxt->err; *localType = NULL; } } } exit: ACTIVATE_ELEM; return (ret); internal_error: ACTIVATE_ELEM; return (-1); } static int xmlSchemaValidateElemDecl(xmlSchemaValidCtxtPtr vctxt) { xmlSchemaElementPtr elemDecl = vctxt->inode->decl; xmlSchemaTypePtr actualType; /* * cvc-elt (3.3.4) : 1 */ if (elemDecl == NULL) { VERROR(XML_SCHEMAV_CVC_ELT_1, NULL, "No matching declaration available"); return (vctxt->err); } actualType = WXS_ELEM_TYPEDEF(elemDecl); /* * cvc-elt (3.3.4) : 2 */ if (elemDecl->flags & XML_SCHEMAS_ELEM_ABSTRACT) { VERROR(XML_SCHEMAV_CVC_ELT_2, NULL, "The element declaration is abstract"); return (vctxt->err); } if (actualType == NULL) { VERROR(XML_SCHEMAV_CVC_TYPE_1, NULL, "The type definition is absent"); return (XML_SCHEMAV_CVC_TYPE_1); } if (vctxt->nbAttrInfos != 0) { int ret; xmlSchemaAttrInfoPtr iattr; /* * cvc-elt (3.3.4) : 3 * Handle 'xsi:nil'. */ iattr = xmlSchemaGetMetaAttrInfo(vctxt, XML_SCHEMA_ATTR_INFO_META_XSI_NIL); if (iattr) { ACTIVATE_ATTRIBUTE(iattr); /* * Validate the value. */ ret = xmlSchemaVCheckCVCSimpleType( ACTXT_CAST vctxt, NULL, xmlSchemaGetBuiltInType(XML_SCHEMAS_BOOLEAN), iattr->value, &(iattr->val), 1, 0, 0); ACTIVATE_ELEM; if (ret < 0) { VERROR_INT("xmlSchemaValidateElemDecl", "calling xmlSchemaVCheckCVCSimpleType() to " "validate the attribute 'xsi:nil'"); return (-1); } if (ret == 0) { if ((elemDecl->flags & XML_SCHEMAS_ELEM_NILLABLE) == 0) { /* * cvc-elt (3.3.4) : 3.1 */ VERROR(XML_SCHEMAV_CVC_ELT_3_1, NULL, "The element is not 'nillable'"); /* Does not return an error on purpose. */ } else { if (xmlSchemaValueGetAsBoolean(iattr->val)) { /* * cvc-elt (3.3.4) : 3.2.2 */ if ((elemDecl->flags & XML_SCHEMAS_ELEM_FIXED) && (elemDecl->value != NULL)) { VERROR(XML_SCHEMAV_CVC_ELT_3_2_2, NULL, "The element cannot be 'nilled' because " "there is a fixed value constraint defined " "for it"); /* Does not return an error on purpose. */ } else vctxt->inode->flags |= XML_SCHEMA_ELEM_INFO_NILLED; } } } } /* * cvc-elt (3.3.4) : 4 * Handle 'xsi:type'. */ iattr = xmlSchemaGetMetaAttrInfo(vctxt, XML_SCHEMA_ATTR_INFO_META_XSI_TYPE); if (iattr) { xmlSchemaTypePtr localType = NULL; ret = xmlSchemaProcessXSIType(vctxt, iattr, &localType, elemDecl); if (ret != 0) { if (ret == -1) { VERROR_INT("xmlSchemaValidateElemDecl", "calling xmlSchemaProcessXSIType() to " "process the attribute 'xsi:type'"); return (-1); } /* Does not return an error on purpose. */ } if (localType != NULL) { vctxt->inode->flags |= XML_SCHEMA_ELEM_INFO_LOCAL_TYPE; actualType = localType; } } } /* * IDC: Register identity-constraint XPath matchers. */ if ((elemDecl->idcs != NULL) && (xmlSchemaIDCRegisterMatchers(vctxt, elemDecl) == -1)) return (-1); /* * No actual type definition. */ if (actualType == NULL) { VERROR(XML_SCHEMAV_CVC_TYPE_1, NULL, "The type definition is absent"); return (XML_SCHEMAV_CVC_TYPE_1); } /* * Remember the actual type definition. */ vctxt->inode->typeDef = actualType; return (0); } static int xmlSchemaVAttributesSimple(xmlSchemaValidCtxtPtr vctxt) { xmlSchemaAttrInfoPtr iattr; int ret = 0, i; /* * SPEC cvc-type (3.1.1) * "The attributes of must be empty, excepting those whose namespace * name is identical to http://www.w3.org/2001/XMLSchema-instance and * whose local name is one of type, nil, schemaLocation or * noNamespaceSchemaLocation." */ if (vctxt->nbAttrInfos == 0) return (0); for (i = 0; i < vctxt->nbAttrInfos; i++) { iattr = vctxt->attrInfos[i]; if (! iattr->metaType) { ACTIVATE_ATTRIBUTE(iattr) xmlSchemaIllegalAttrErr(ACTXT_CAST vctxt, XML_SCHEMAV_CVC_TYPE_3_1_1, iattr, NULL); ret = XML_SCHEMAV_CVC_TYPE_3_1_1; } } ACTIVATE_ELEM return (ret); } /* * Cleanup currently used attribute infos. */ static void xmlSchemaClearAttrInfos(xmlSchemaValidCtxtPtr vctxt) { int i; xmlSchemaAttrInfoPtr attr; if (vctxt->nbAttrInfos == 0) return; for (i = 0; i < vctxt->nbAttrInfos; i++) { attr = vctxt->attrInfos[i]; if (attr->flags & XML_SCHEMA_NODE_INFO_FLAG_OWNED_NAMES) { if (attr->localName != NULL) xmlFree((xmlChar *) attr->localName); if (attr->nsName != NULL) xmlFree((xmlChar *) attr->nsName); } if (attr->flags & XML_SCHEMA_NODE_INFO_FLAG_OWNED_VALUES) { if (attr->value != NULL) xmlFree((xmlChar *) attr->value); } if (attr->val != NULL) { xmlSchemaFreeValue(attr->val); attr->val = NULL; } memset(attr, 0, sizeof(xmlSchemaAttrInfo)); } vctxt->nbAttrInfos = 0; } /* * 3.4.4 Complex Type Definition Validation Rules * Element Locally Valid (Complex Type) (cvc-complex-type) * 3.2.4 Attribute Declaration Validation Rules * Validation Rule: Attribute Locally Valid (cvc-attribute) * Attribute Locally Valid (Use) (cvc-au) * * Only "assessed" attribute information items will be visible to * IDCs. I.e. not "lax" (without declaration) and "skip" wild attributes. */ static int xmlSchemaVAttributesComplex(xmlSchemaValidCtxtPtr vctxt) { xmlSchemaTypePtr type = vctxt->inode->typeDef; xmlSchemaItemListPtr attrUseList; xmlSchemaAttributeUsePtr attrUse = NULL; xmlSchemaAttributePtr attrDecl = NULL; xmlSchemaAttrInfoPtr iattr, tmpiattr; int i, j, found, nbAttrs, nbUses; int xpathRes = 0, res, wildIDs = 0, fixed; xmlNodePtr defAttrOwnerElem = NULL; /* * SPEC (cvc-attribute) * (1) "The declaration must not be `absent` (see Missing * Sub-components ($5.3) for how this can fail to be * the case)." * (2) "Its {type definition} must not be absent." * * NOTE (1) + (2): This is not handled here, since we currently do not * allow validation against schemas which have missing sub-components. * * SPEC (cvc-complex-type) * (3) "For each attribute information item in the element information * item's [attributes] excepting those whose [namespace name] is * identical to http://www.w3.org/2001/XMLSchema-instance and whose * [local name] is one of type, nil, schemaLocation or * noNamespaceSchemaLocation, the appropriate case among the following * must be true: * */ attrUseList = (xmlSchemaItemListPtr) type->attrUses; /* * @nbAttrs is the number of attributes present in the instance. */ nbAttrs = vctxt->nbAttrInfos; if (attrUseList != NULL) nbUses = attrUseList->nbItems; else nbUses = 0; for (i = 0; i < nbUses; i++) { found = 0; attrUse = attrUseList->items[i]; attrDecl = WXS_ATTRUSE_DECL(attrUse); for (j = 0; j < nbAttrs; j++) { iattr = vctxt->attrInfos[j]; /* * SPEC (cvc-complex-type) (3) * Skip meta attributes. */ if (iattr->metaType) continue; if (iattr->localName[0] != attrDecl->name[0]) continue; if (!xmlStrEqual(iattr->localName, attrDecl->name)) continue; if (!xmlStrEqual(iattr->nsName, attrDecl->targetNamespace)) continue; found = 1; /* * SPEC (cvc-complex-type) * (3.1) "If there is among the {attribute uses} an attribute * use with an {attribute declaration} whose {name} matches * the attribute information item's [local name] and whose * {target namespace} is identical to the attribute information * item's [namespace name] (where an `absent` {target namespace} * is taken to be identical to a [namespace name] with no value), * then the attribute information must be `valid` with respect * to that attribute use as per Attribute Locally Valid (Use) * ($3.5.4). In this case the {attribute declaration} of that * attribute use is the `context-determined declaration` for the * attribute information item with respect to Schema-Validity * Assessment (Attribute) ($3.2.4) and * Assessment Outcome (Attribute) ($3.2.5). */ iattr->state = XML_SCHEMAS_ATTR_ASSESSED; iattr->use = attrUse; /* * Context-determined declaration. */ iattr->decl = attrDecl; iattr->typeDef = attrDecl->subtypes; break; } if (found) continue; if (attrUse->occurs == XML_SCHEMAS_ATTR_USE_REQUIRED) { /* * Handle non-existent, required attributes. * * SPEC (cvc-complex-type) * (4) "The {attribute declaration} of each attribute use in * the {attribute uses} whose {required} is true matches one * of the attribute information items in the element information * item's [attributes] as per clause 3.1 above." */ tmpiattr = xmlSchemaGetFreshAttrInfo(vctxt); if (tmpiattr == NULL) { VERROR_INT( "xmlSchemaVAttributesComplex", "calling xmlSchemaGetFreshAttrInfo()"); return (-1); } tmpiattr->state = XML_SCHEMAS_ATTR_ERR_MISSING; tmpiattr->use = attrUse; tmpiattr->decl = attrDecl; } else if ((attrUse->occurs == XML_SCHEMAS_ATTR_USE_OPTIONAL) && ((attrUse->defValue != NULL) || (attrDecl->defValue != NULL))) { /* * Handle non-existent, optional, default/fixed attributes. */ tmpiattr = xmlSchemaGetFreshAttrInfo(vctxt); if (tmpiattr == NULL) { VERROR_INT( "xmlSchemaVAttributesComplex", "calling xmlSchemaGetFreshAttrInfo()"); return (-1); } tmpiattr->state = XML_SCHEMAS_ATTR_DEFAULT; tmpiattr->use = attrUse; tmpiattr->decl = attrDecl; tmpiattr->typeDef = attrDecl->subtypes; tmpiattr->localName = attrDecl->name; tmpiattr->nsName = attrDecl->targetNamespace; } } if (vctxt->nbAttrInfos == 0) return (0); /* * Validate against the wildcard. */ if (type->attributeWildcard != NULL) { /* * SPEC (cvc-complex-type) * (3.2.1) "There must be an {attribute wildcard}." */ for (i = 0; i < nbAttrs; i++) { iattr = vctxt->attrInfos[i]; /* * SPEC (cvc-complex-type) (3) * Skip meta attributes. */ if (iattr->state != XML_SCHEMAS_ATTR_UNKNOWN) continue; /* * SPEC (cvc-complex-type) * (3.2.2) "The attribute information item must be `valid` with * respect to it as defined in Item Valid (Wildcard) ($3.10.4)." * * SPEC Item Valid (Wildcard) (cvc-wildcard) * "... its [namespace name] must be `valid` with respect to * the wildcard constraint, as defined in Wildcard allows * Namespace Name ($3.10.4)." */ if (xmlSchemaCheckCVCWildcardNamespace(type->attributeWildcard, iattr->nsName) == 0) { /* * Handle processContents. * * SPEC (cvc-wildcard): * processContents | context-determined declaration: * "strict" "mustFind" * "lax" "none" * "skip" "skip" */ if (type->attributeWildcard->processContents == XML_SCHEMAS_ANY_SKIP) { /* * context-determined declaration = "skip" * * SPEC PSVI Assessment Outcome (Attribute) * [validity] = "notKnown" * [validation attempted] = "none" */ iattr->state = XML_SCHEMAS_ATTR_WILD_SKIP; continue; } /* * Find an attribute declaration. */ iattr->decl = xmlSchemaGetAttributeDecl(vctxt->schema, iattr->localName, iattr->nsName); if (iattr->decl != NULL) { iattr->state = XML_SCHEMAS_ATTR_ASSESSED; /* * SPEC (cvc-complex-type) * (5) "Let [Definition:] the wild IDs be the set of * all attribute information item to which clause 3.2 * applied and whose `validation` resulted in a * `context-determined declaration` of mustFind or no * `context-determined declaration` at all, and whose * [local name] and [namespace name] resolve (as * defined by QName resolution (Instance) ($3.15.4)) to * an attribute declaration whose {type definition} is * or is derived from ID. Then all of the following * must be true:" */ iattr->typeDef = WXS_ATTR_TYPEDEF(iattr->decl); if (xmlSchemaIsDerivedFromBuiltInType( iattr->typeDef, XML_SCHEMAS_ID)) { /* * SPEC (5.1) "There must be no more than one * item in `wild IDs`." */ if (wildIDs != 0) { /* VAL TODO */ iattr->state = XML_SCHEMAS_ATTR_ERR_WILD_DUPLICATE_ID; TODO continue; } wildIDs++; /* * SPEC (cvc-complex-type) * (5.2) "If `wild IDs` is non-empty, there must not * be any attribute uses among the {attribute uses} * whose {attribute declaration}'s {type definition} * is or is derived from ID." */ if (attrUseList != NULL) { for (j = 0; j < attrUseList->nbItems; j++) { if (xmlSchemaIsDerivedFromBuiltInType( WXS_ATTRUSE_TYPEDEF(attrUseList->items[j]), XML_SCHEMAS_ID)) { /* URGENT VAL TODO: implement */ iattr->state = XML_SCHEMAS_ATTR_ERR_WILD_AND_USE_ID; TODO break; } } } } } else if (type->attributeWildcard->processContents == XML_SCHEMAS_ANY_LAX) { iattr->state = XML_SCHEMAS_ATTR_WILD_LAX_NO_DECL; /* * SPEC PSVI Assessment Outcome (Attribute) * [validity] = "notKnown" * [validation attempted] = "none" */ } else { iattr->state = XML_SCHEMAS_ATTR_ERR_WILD_STRICT_NO_DECL; } } } } if (vctxt->nbAttrInfos == 0) return (0); /* * Get the owner element; needed for creation of default attributes. * This fixes bug #341337, reported by David Grohmann. */ if (vctxt->options & XML_SCHEMA_VAL_VC_I_CREATE) { xmlSchemaNodeInfoPtr ielem = vctxt->elemInfos[vctxt->depth]; if (ielem && ielem->node && ielem->node->doc) defAttrOwnerElem = ielem->node; } /* * Validate values, create default attributes, evaluate IDCs. */ for (i = 0; i < vctxt->nbAttrInfos; i++) { iattr = vctxt->attrInfos[i]; /* * VAL TODO: Note that we won't try to resolve IDCs to * "lax" and "skip" validated attributes. Check what to * do in this case. */ if ((iattr->state != XML_SCHEMAS_ATTR_ASSESSED) && (iattr->state != XML_SCHEMAS_ATTR_DEFAULT)) continue; /* * VAL TODO: What to do if the type definition is missing? */ if (iattr->typeDef == NULL) { iattr->state = XML_SCHEMAS_ATTR_ERR_NO_TYPE; continue; } ACTIVATE_ATTRIBUTE(iattr); fixed = 0; xpathRes = 0; if (vctxt->xpathStates != NULL) { /* * Evaluate IDCs. */ xpathRes = xmlSchemaXPathEvaluate(vctxt, XML_ATTRIBUTE_NODE); if (xpathRes == -1) { VERROR_INT("xmlSchemaVAttributesComplex", "calling xmlSchemaXPathEvaluate()"); goto internal_error; } } if (iattr->state == XML_SCHEMAS_ATTR_DEFAULT) { /* * Default/fixed attributes. * We need the value only if we need to resolve IDCs or * will create default attributes. */ if ((xpathRes) || (defAttrOwnerElem)) { if (iattr->use->defValue != NULL) { iattr->value = (xmlChar *) iattr->use->defValue; iattr->val = iattr->use->defVal; } else { iattr->value = (xmlChar *) iattr->decl->defValue; iattr->val = iattr->decl->defVal; } /* * IDCs will consume the precomputed default value, * so we need to clone it. */ if (iattr->val == NULL) { VERROR_INT("xmlSchemaVAttributesComplex", "default/fixed value on an attribute use was " "not precomputed"); goto internal_error; } iattr->val = xmlSchemaCopyValue(iattr->val); if (iattr->val == NULL) { VERROR_INT("xmlSchemaVAttributesComplex", "calling xmlSchemaCopyValue()"); goto internal_error; } } /* * PSVI: Add the default attribute to the current element. * VAL TODO: Should we use the *normalized* value? This currently * uses the *initial* value. */ if (defAttrOwnerElem) { xmlChar *normValue; const xmlChar *value; value = iattr->value; /* * Normalize the value. */ normValue = xmlSchemaNormalizeValue(iattr->typeDef, iattr->value); if (normValue != NULL) value = BAD_CAST normValue; if (iattr->nsName == NULL) { if (xmlNewProp(defAttrOwnerElem, iattr->localName, value) == NULL) { VERROR_INT("xmlSchemaVAttributesComplex", "calling xmlNewProp()"); if (normValue != NULL) xmlFree(normValue); goto internal_error; } } else { xmlNsPtr ns; ns = xmlSearchNsByHref(defAttrOwnerElem->doc, defAttrOwnerElem, iattr->nsName); if (ns == NULL) { xmlChar prefix[12]; int counter = 0; /* * Create a namespace declaration on the validation * root node if no namespace declaration is in scope. */ do { snprintf((char *) prefix, 12, "p%d", counter++); ns = xmlSearchNs(defAttrOwnerElem->doc, defAttrOwnerElem, BAD_CAST prefix); if (counter > 1000) { VERROR_INT( "xmlSchemaVAttributesComplex", "could not compute a ns prefix for a " "default/fixed attribute"); if (normValue != NULL) xmlFree(normValue); goto internal_error; } } while (ns != NULL); ns = xmlNewNs(vctxt->validationRoot, iattr->nsName, BAD_CAST prefix); } /* * TODO: * http://lists.w3.org/Archives/Public/www-xml-schema-comments/2005JulSep/0406.html * If we have QNames: do we need to ensure there's a * prefix defined for the QName? */ xmlNewNsProp(defAttrOwnerElem, ns, iattr->localName, value); } if (normValue != NULL) xmlFree(normValue); } /* * Go directly to IDC evaluation. */ goto eval_idcs; } /* * Validate the value. */ if (vctxt->value != NULL) { /* * Free last computed value; just for safety reasons. */ xmlSchemaFreeValue(vctxt->value); vctxt->value = NULL; } /* * Note that the attribute *use* can be unavailable, if * the attribute was a wild attribute. */ if ((iattr->decl->flags & XML_SCHEMAS_ATTR_FIXED) || ((iattr->use != NULL) && (iattr->use->flags & XML_SCHEMAS_ATTR_FIXED))) fixed = 1; else fixed = 0; /* * SPEC (cvc-attribute) * (3) "The item's `normalized value` must be locally `valid` * with respect to that {type definition} as per * String Valid ($3.14.4)." * * VAL TODO: Do we already have the * "normalized attribute value" here? */ if (xpathRes || fixed) { iattr->flags |= XML_SCHEMA_NODE_INFO_VALUE_NEEDED; /* * Request a computed value. */ res = xmlSchemaVCheckCVCSimpleType( ACTXT_CAST vctxt, iattr->node, iattr->typeDef, iattr->value, &(iattr->val), 1, 1, 0); } else { res = xmlSchemaVCheckCVCSimpleType( ACTXT_CAST vctxt, iattr->node, iattr->typeDef, iattr->value, NULL, 1, 0, 0); } if (res != 0) { if (res == -1) { VERROR_INT("xmlSchemaVAttributesComplex", "calling xmlSchemaStreamValidateSimpleTypeValue()"); goto internal_error; } iattr->state = XML_SCHEMAS_ATTR_INVALID_VALUE; /* * SPEC PSVI Assessment Outcome (Attribute) * [validity] = "invalid" */ goto eval_idcs; } if (fixed) { /* * SPEC Attribute Locally Valid (Use) (cvc-au) * "For an attribute information item to be `valid` * with respect to an attribute use its *normalized* * value must match the *canonical* lexical * representation of the attribute use's {value * constraint}value, if it is present and fixed." * * VAL TODO: The requirement for the *canonical* value * will be removed in XML Schema 1.1. */ /* * SPEC Attribute Locally Valid (cvc-attribute) * (4) "The item's *actual* value must match the *value* of * the {value constraint}, if it is present and fixed." */ if (iattr->val == NULL) { /* VAL TODO: A value was not precomputed. */ TODO goto eval_idcs; } if ((iattr->use != NULL) && (iattr->use->defValue != NULL)) { if (iattr->use->defVal == NULL) { /* VAL TODO: A default value was not precomputed. */ TODO goto eval_idcs; } iattr->vcValue = iattr->use->defValue; /* if (xmlSchemaCompareValuesWhtsp(attr->val, (xmlSchemaWhitespaceValueType) ws, attr->use->defVal, (xmlSchemaWhitespaceValueType) ws) != 0) { */ if (! xmlSchemaAreValuesEqual(iattr->val, iattr->use->defVal)) iattr->state = XML_SCHEMAS_ATTR_ERR_FIXED_VALUE; } else { if (iattr->decl->defVal == NULL) { /* VAL TODO: A default value was not precomputed. */ TODO goto eval_idcs; } iattr->vcValue = iattr->decl->defValue; /* if (xmlSchemaCompareValuesWhtsp(attr->val, (xmlSchemaWhitespaceValueType) ws, attrDecl->defVal, (xmlSchemaWhitespaceValueType) ws) != 0) { */ if (! xmlSchemaAreValuesEqual(iattr->val, iattr->decl->defVal)) iattr->state = XML_SCHEMAS_ATTR_ERR_FIXED_VALUE; } /* * [validity] = "valid" */ } eval_idcs: /* * Evaluate IDCs. */ if (xpathRes) { if (xmlSchemaXPathProcessHistory(vctxt, vctxt->depth +1) == -1) { VERROR_INT("xmlSchemaVAttributesComplex", "calling xmlSchemaXPathEvaluate()"); goto internal_error; } } else if (vctxt->xpathStates != NULL) xmlSchemaXPathPop(vctxt); } /* * Report errors. */ for (i = 0; i < vctxt->nbAttrInfos; i++) { iattr = vctxt->attrInfos[i]; if ((iattr->state == XML_SCHEMAS_ATTR_META) || (iattr->state == XML_SCHEMAS_ATTR_ASSESSED) || (iattr->state == XML_SCHEMAS_ATTR_WILD_SKIP) || (iattr->state == XML_SCHEMAS_ATTR_WILD_LAX_NO_DECL)) continue; ACTIVATE_ATTRIBUTE(iattr); switch (iattr->state) { case XML_SCHEMAS_ATTR_ERR_MISSING: { xmlChar *str = NULL; ACTIVATE_ELEM; xmlSchemaCustomErr(ACTXT_CAST vctxt, XML_SCHEMAV_CVC_COMPLEX_TYPE_4, NULL, NULL, "The attribute '%s' is required but missing", xmlSchemaFormatQName(&str, iattr->decl->targetNamespace, iattr->decl->name), NULL); FREE_AND_NULL(str) break; } case XML_SCHEMAS_ATTR_ERR_NO_TYPE: VERROR(XML_SCHEMAV_CVC_ATTRIBUTE_2, NULL, "The type definition is absent"); break; case XML_SCHEMAS_ATTR_ERR_FIXED_VALUE: xmlSchemaCustomErr(ACTXT_CAST vctxt, XML_SCHEMAV_CVC_AU, NULL, NULL, "The value '%s' does not match the fixed " "value constraint '%s'", iattr->value, iattr->vcValue); break; case XML_SCHEMAS_ATTR_ERR_WILD_STRICT_NO_DECL: VERROR(XML_SCHEMAV_CVC_WILDCARD, NULL, "No matching global attribute declaration available, but " "demanded by the strict wildcard"); break; case XML_SCHEMAS_ATTR_UNKNOWN: if (iattr->metaType) break; /* * MAYBE VAL TODO: One might report different error messages * for the following errors. */ if (type->attributeWildcard == NULL) { xmlSchemaIllegalAttrErr(ACTXT_CAST vctxt, XML_SCHEMAV_CVC_COMPLEX_TYPE_3_2_1, iattr, NULL); } else { xmlSchemaIllegalAttrErr(ACTXT_CAST vctxt, XML_SCHEMAV_CVC_COMPLEX_TYPE_3_2_2, iattr, NULL); } break; default: break; } } ACTIVATE_ELEM; return (0); internal_error: ACTIVATE_ELEM; return (-1); } static int xmlSchemaValidateElemWildcard(xmlSchemaValidCtxtPtr vctxt, int *skip) { xmlSchemaWildcardPtr wild = (xmlSchemaWildcardPtr) vctxt->inode->decl; /* * The namespace of the element was already identified to be * matching the wildcard. */ if ((skip == NULL) || (wild == NULL) || (wild->type != XML_SCHEMA_TYPE_ANY)) { VERROR_INT("xmlSchemaValidateElemWildcard", "bad arguments"); return (-1); } *skip = 0; if (wild->processContents == XML_SCHEMAS_ANY_SKIP) { /* * URGENT VAL TODO: Either we need to position the stream to the * next sibling, or walk the whole subtree. */ *skip = 1; return (0); } { xmlSchemaElementPtr decl = NULL; decl = xmlSchemaGetElem(vctxt->schema, vctxt->inode->localName, vctxt->inode->nsName); if (decl != NULL) { vctxt->inode->decl = decl; return (0); } } if (wild->processContents == XML_SCHEMAS_ANY_STRICT) { /* VAL TODO: Change to proper error code. */ VERROR(XML_SCHEMAV_CVC_ELT_1, NULL, /* WXS_BASIC_CAST wild */ "No matching global element declaration available, but " "demanded by the strict wildcard"); return (vctxt->err); } if (vctxt->nbAttrInfos != 0) { xmlSchemaAttrInfoPtr iattr; /* * SPEC Validation Rule: Schema-Validity Assessment (Element) * (1.2.1.2.1) - (1.2.1.2.3 ) * * Use the xsi:type attribute for the type definition. */ iattr = xmlSchemaGetMetaAttrInfo(vctxt, XML_SCHEMA_ATTR_INFO_META_XSI_TYPE); if (iattr != NULL) { if (xmlSchemaProcessXSIType(vctxt, iattr, &(vctxt->inode->typeDef), NULL) == -1) { VERROR_INT("xmlSchemaValidateElemWildcard", "calling xmlSchemaProcessXSIType() to " "process the attribute 'xsi:nil'"); return (-1); } /* * Don't return an error on purpose. */ return (0); } } /* * SPEC Validation Rule: Schema-Validity Assessment (Element) * * Fallback to "anyType". */ vctxt->inode->typeDef = xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYTYPE); return (0); } /* * xmlSchemaCheckCOSValidDefault: * * This will be called if: not nilled, no content and a default/fixed * value is provided. */ static int xmlSchemaCheckCOSValidDefault(xmlSchemaValidCtxtPtr vctxt, const xmlChar *value, xmlSchemaValPtr *val) { int ret = 0; xmlSchemaNodeInfoPtr inode = vctxt->inode; /* * cos-valid-default: * Schema Component Constraint: Element Default Valid (Immediate) * For a string to be a valid default with respect to a type * definition the appropriate case among the following must be true: */ if WXS_IS_COMPLEX(inode->typeDef) { /* * Complex type. * * SPEC (2.1) "its {content type} must be a simple type definition * or mixed." * SPEC (2.2.2) "If the {content type} is mixed, then the {content * type}'s particle must be `emptiable` as defined by * Particle Emptiable ($3.9.6)." */ if ((! WXS_HAS_SIMPLE_CONTENT(inode->typeDef)) && ((! WXS_HAS_MIXED_CONTENT(inode->typeDef)) || (! WXS_EMPTIABLE(inode->typeDef)))) { ret = XML_SCHEMAP_COS_VALID_DEFAULT_2_1; /* NOTE that this covers (2.2.2) as well. */ VERROR(ret, NULL, "For a string to be a valid default, the type definition " "must be a simple type or a complex type with simple content " "or mixed content and a particle emptiable"); return(ret); } } /* * 1 If the type definition is a simple type definition, then the string * must be `valid` with respect to that definition as defined by String * Valid ($3.14.4). * * AND * * 2.2.1 If the {content type} is a simple type definition, then the * string must be `valid` with respect to that simple type definition * as defined by String Valid ($3.14.4). */ if (WXS_IS_SIMPLE(inode->typeDef)) { ret = xmlSchemaVCheckCVCSimpleType(ACTXT_CAST vctxt, NULL, inode->typeDef, value, val, 1, 1, 0); } else if (WXS_HAS_SIMPLE_CONTENT(inode->typeDef)) { ret = xmlSchemaVCheckCVCSimpleType(ACTXT_CAST vctxt, NULL, inode->typeDef->contentTypeDef, value, val, 1, 1, 0); } if (ret < 0) { VERROR_INT("xmlSchemaCheckCOSValidDefault", "calling xmlSchemaVCheckCVCSimpleType()"); } return (ret); } static void xmlSchemaVContentModelCallback(xmlRegExecCtxtPtr exec ATTRIBUTE_UNUSED, const xmlChar * name ATTRIBUTE_UNUSED, void *transdata, void *inputdata) { xmlSchemaElementPtr item = (xmlSchemaElementPtr) transdata; xmlSchemaNodeInfoPtr inode = (xmlSchemaNodeInfoPtr) inputdata; inode->decl = item; #ifdef DEBUG_CONTENT { xmlChar *str = NULL; if (item->type == XML_SCHEMA_TYPE_ELEMENT) { xmlGenericError(xmlGenericErrorContext, "AUTOMATON callback for '%s' [declaration]\n", xmlSchemaFormatQName(&str, inode->localName, inode->nsName)); } else { xmlGenericError(xmlGenericErrorContext, "AUTOMATON callback for '%s' [wildcard]\n", xmlSchemaFormatQName(&str, inode->localName, inode->nsName)); } FREE_AND_NULL(str) } #endif } static int xmlSchemaValidatorPushElem(xmlSchemaValidCtxtPtr vctxt) { vctxt->inode = xmlSchemaGetFreshElemInfo(vctxt); if (vctxt->inode == NULL) { VERROR_INT("xmlSchemaValidatorPushElem", "calling xmlSchemaGetFreshElemInfo()"); return (-1); } vctxt->nbAttrInfos = 0; return (0); } static int xmlSchemaVCheckINodeDataType(xmlSchemaValidCtxtPtr vctxt, xmlSchemaNodeInfoPtr inode, xmlSchemaTypePtr type, const xmlChar *value) { if (inode->flags & XML_SCHEMA_NODE_INFO_VALUE_NEEDED) return (xmlSchemaVCheckCVCSimpleType( ACTXT_CAST vctxt, NULL, type, value, &(inode->val), 1, 1, 0)); else return (xmlSchemaVCheckCVCSimpleType( ACTXT_CAST vctxt, NULL, type, value, NULL, 1, 0, 0)); } /* * Process END of element. */ static int xmlSchemaValidatorPopElem(xmlSchemaValidCtxtPtr vctxt) { int ret = 0; xmlSchemaNodeInfoPtr inode = vctxt->inode; if (vctxt->nbAttrInfos != 0) xmlSchemaClearAttrInfos(vctxt); if (inode->flags & XML_SCHEMA_NODE_INFO_ERR_NOT_EXPECTED) { /* * This element was not expected; * we will not validate child elements of broken parents. * Skip validation of all content of the parent. */ vctxt->skipDepth = vctxt->depth -1; goto end_elem; } if ((inode->typeDef == NULL) || (inode->flags & XML_SCHEMA_NODE_INFO_ERR_BAD_TYPE)) { /* * 1. the type definition might be missing if the element was * error prone * 2. it might be abstract. */ goto end_elem; } /* * Check the content model. */ if ((inode->typeDef->contentType == XML_SCHEMA_CONTENT_MIXED) || (inode->typeDef->contentType == XML_SCHEMA_CONTENT_ELEMENTS)) { /* * Workaround for "anyType". */ if (inode->typeDef->builtInType == XML_SCHEMAS_ANYTYPE) goto character_content; if ((inode->flags & XML_SCHEMA_ELEM_INFO_ERR_BAD_CONTENT) == 0) { xmlChar *values[10]; int terminal, nbval = 10, nbneg; if (inode->regexCtxt == NULL) { /* * Create the regex context. */ inode->regexCtxt = xmlRegNewExecCtxt(inode->typeDef->contModel, xmlSchemaVContentModelCallback, vctxt); if (inode->regexCtxt == NULL) { VERROR_INT("xmlSchemaValidatorPopElem", "failed to create a regex context"); goto internal_error; } #ifdef DEBUG_AUTOMATA xmlGenericError(xmlGenericErrorContext, "AUTOMATON create on '%s'\n", inode->localName); #endif } /* * Do not check further content if the node has been nilled */ if (INODE_NILLED(inode)) { ret = 0; #ifdef DEBUG_AUTOMATA xmlGenericError(xmlGenericErrorContext, "AUTOMATON succeeded on nilled '%s'\n", inode->localName); #endif goto skip_nilled; } /* * Get hold of the still expected content, since a further * call to xmlRegExecPushString() will lose this information. */ xmlRegExecNextValues(inode->regexCtxt, &nbval, &nbneg, &values[0], &terminal); ret = xmlRegExecPushString(inode->regexCtxt, NULL, NULL); if ((ret<0) || ((ret==0) && (!INODE_NILLED(inode)))) { /* * Still missing something. */ ret = 1; inode->flags |= XML_SCHEMA_ELEM_INFO_ERR_BAD_CONTENT; xmlSchemaComplexTypeErr(ACTXT_CAST vctxt, XML_SCHEMAV_ELEMENT_CONTENT, NULL, NULL, "Missing child element(s)", nbval, nbneg, values); #ifdef DEBUG_AUTOMATA xmlGenericError(xmlGenericErrorContext, "AUTOMATON missing ERROR on '%s'\n", inode->localName); #endif } else { /* * Content model is satisfied. */ ret = 0; #ifdef DEBUG_AUTOMATA xmlGenericError(xmlGenericErrorContext, "AUTOMATON succeeded on '%s'\n", inode->localName); #endif } } } skip_nilled: if (inode->typeDef->contentType == XML_SCHEMA_CONTENT_ELEMENTS) goto end_elem; character_content: if (vctxt->value != NULL) { xmlSchemaFreeValue(vctxt->value); vctxt->value = NULL; } /* * Check character content. */ if (inode->decl == NULL) { /* * Speedup if no declaration exists. */ if (WXS_IS_SIMPLE(inode->typeDef)) { ret = xmlSchemaVCheckINodeDataType(vctxt, inode, inode->typeDef, inode->value); } else if (WXS_HAS_SIMPLE_CONTENT(inode->typeDef)) { ret = xmlSchemaVCheckINodeDataType(vctxt, inode, inode->typeDef->contentTypeDef, inode->value); } if (ret < 0) { VERROR_INT("xmlSchemaValidatorPopElem", "calling xmlSchemaVCheckCVCSimpleType()"); goto internal_error; } goto end_elem; } /* * cvc-elt (3.3.4) : 5 * The appropriate case among the following must be true: */ /* * cvc-elt (3.3.4) : 5.1 * If the declaration has a {value constraint}, * the item has neither element nor character [children] and * clause 3.2 has not applied, then all of the following must be true: */ if ((inode->decl->value != NULL) && (inode->flags & XML_SCHEMA_ELEM_INFO_EMPTY) && (! INODE_NILLED(inode))) { /* * cvc-elt (3.3.4) : 5.1.1 * If the `actual type definition` is a `local type definition` * then the canonical lexical representation of the {value constraint} * value must be a valid default for the `actual type definition` as * defined in Element Default Valid (Immediate) ($3.3.6). */ /* * NOTE: 'local' above means types acquired by xsi:type. * NOTE: Although the *canonical* value is stated, it is not * relevant if canonical or not. Additionally XML Schema 1.1 * will removed this requirement as well. */ if (inode->flags & XML_SCHEMA_ELEM_INFO_LOCAL_TYPE) { ret = xmlSchemaCheckCOSValidDefault(vctxt, inode->decl->value, &(inode->val)); if (ret != 0) { if (ret < 0) { VERROR_INT("xmlSchemaValidatorPopElem", "calling xmlSchemaCheckCOSValidDefault()"); goto internal_error; } goto end_elem; } /* * Stop here, to avoid redundant validation of the value * (see following). */ goto default_psvi; } /* * cvc-elt (3.3.4) : 5.1.2 * The element information item with the canonical lexical * representation of the {value constraint} value used as its * `normalized value` must be `valid` with respect to the * `actual type definition` as defined by Element Locally Valid (Type) * ($3.3.4). */ if (WXS_IS_SIMPLE(inode->typeDef)) { ret = xmlSchemaVCheckINodeDataType(vctxt, inode, inode->typeDef, inode->decl->value); } else if (WXS_HAS_SIMPLE_CONTENT(inode->typeDef)) { ret = xmlSchemaVCheckINodeDataType(vctxt, inode, inode->typeDef->contentTypeDef, inode->decl->value); } if (ret != 0) { if (ret < 0) { VERROR_INT("xmlSchemaValidatorPopElem", "calling xmlSchemaVCheckCVCSimpleType()"); goto internal_error; } goto end_elem; } default_psvi: /* * PSVI: Create a text node on the instance element. */ if ((vctxt->options & XML_SCHEMA_VAL_VC_I_CREATE) && (inode->node != NULL)) { xmlNodePtr textChild; xmlChar *normValue; /* * VAL TODO: Normalize the value. */ normValue = xmlSchemaNormalizeValue(inode->typeDef, inode->decl->value); if (normValue != NULL) { textChild = xmlNewText(BAD_CAST normValue); xmlFree(normValue); } else textChild = xmlNewText(inode->decl->value); if (textChild == NULL) { VERROR_INT("xmlSchemaValidatorPopElem", "calling xmlNewText()"); goto internal_error; } else xmlAddChild(inode->node, textChild); } } else if (! INODE_NILLED(inode)) { /* * 5.2.1 The element information item must be `valid` with respect * to the `actual type definition` as defined by Element Locally * Valid (Type) ($3.3.4). */ if (WXS_IS_SIMPLE(inode->typeDef)) { /* * SPEC (cvc-type) (3.1) * "If the type definition is a simple type definition, ..." * (3.1.3) "If clause 3.2 of Element Locally Valid * (Element) ($3.3.4) did not apply, then the `normalized value` * must be `valid` with respect to the type definition as defined * by String Valid ($3.14.4). */ ret = xmlSchemaVCheckINodeDataType(vctxt, inode, inode->typeDef, inode->value); } else if (WXS_HAS_SIMPLE_CONTENT(inode->typeDef)) { /* * SPEC (cvc-type) (3.2) "If the type definition is a complex type * definition, then the element information item must be * `valid` with respect to the type definition as per * Element Locally Valid (Complex Type) ($3.4.4);" * * SPEC (cvc-complex-type) (2.2) * "If the {content type} is a simple type definition, ... * the `normalized value` of the element information item is * `valid` with respect to that simple type definition as * defined by String Valid ($3.14.4)." */ ret = xmlSchemaVCheckINodeDataType(vctxt, inode, inode->typeDef->contentTypeDef, inode->value); } if (ret != 0) { if (ret < 0) { VERROR_INT("xmlSchemaValidatorPopElem", "calling xmlSchemaVCheckCVCSimpleType()"); goto internal_error; } goto end_elem; } /* * 5.2.2 If there is a fixed {value constraint} and clause 3.2 has * not applied, all of the following must be true: */ if ((inode->decl->value != NULL) && (inode->decl->flags & XML_SCHEMAS_ELEM_FIXED)) { /* * TODO: We will need a computed value, when comparison is * done on computed values. */ /* * 5.2.2.1 The element information item must have no element * information item [children]. */ if (inode->flags & XML_SCHEMA_ELEM_INFO_HAS_ELEM_CONTENT) { ret = XML_SCHEMAV_CVC_ELT_5_2_2_1; VERROR(ret, NULL, "The content must not contain element nodes since " "there is a fixed value constraint"); goto end_elem; } else { /* * 5.2.2.2 The appropriate case among the following must * be true: */ if (WXS_HAS_MIXED_CONTENT(inode->typeDef)) { /* * 5.2.2.2.1 If the {content type} of the `actual type * definition` is mixed, then the *initial value* of the * item must match the canonical lexical representation * of the {value constraint} value. * * ... the *initial value* of an element information * item is the string composed of, in order, the * [character code] of each character information item in * the [children] of that element information item. */ if (! xmlStrEqual(inode->value, inode->decl->value)){ /* * VAL TODO: Report invalid & expected values as well. * VAL TODO: Implement the canonical stuff. */ ret = XML_SCHEMAV_CVC_ELT_5_2_2_2_1; xmlSchemaCustomErr(ACTXT_CAST vctxt, ret, NULL, NULL, "The initial value '%s' does not match the fixed " "value constraint '%s'", inode->value, inode->decl->value); goto end_elem; } } else if (WXS_HAS_SIMPLE_CONTENT(inode->typeDef)) { /* * 5.2.2.2.2 If the {content type} of the `actual type * definition` is a simple type definition, then the * *actual value* of the item must match the canonical * lexical representation of the {value constraint} value. */ /* * VAL TODO: *actual value* is the normalized value, impl. * this. * VAL TODO: Report invalid & expected values as well. * VAL TODO: Implement a comparison with the computed values. */ if (! xmlStrEqual(inode->value, inode->decl->value)) { ret = XML_SCHEMAV_CVC_ELT_5_2_2_2_2; xmlSchemaCustomErr(ACTXT_CAST vctxt, ret, NULL, NULL, "The actual value '%s' does not match the fixed " "value constraint '%s'", inode->value, inode->decl->value); goto end_elem; } } } } } end_elem: if (vctxt->depth < 0) { /* TODO: raise error? */ return (0); } if (vctxt->depth == vctxt->skipDepth) vctxt->skipDepth = -1; /* * Evaluate the history of XPath state objects. */ if (inode->appliedXPath && (xmlSchemaXPathProcessHistory(vctxt, vctxt->depth) == -1)) goto internal_error; /* * MAYBE TODO: * SPEC (6) "The element information item must be `valid` with * respect to each of the {identity-constraint definitions} as per * Identity-constraint Satisfied ($3.11.4)." */ /* * PSVI TODO: If we expose IDC node-tables via PSVI then the tables * need to be built in any case. * We will currently build IDC node-tables and bubble them only if * keyrefs do exist. */ /* * Add the current IDC target-nodes to the IDC node-tables. */ if ((inode->idcMatchers != NULL) && (vctxt->hasKeyrefs || vctxt->createIDCNodeTables)) { if (xmlSchemaIDCFillNodeTables(vctxt, inode) == -1) goto internal_error; } /* * Validate IDC keyrefs. */ if (vctxt->inode->hasKeyrefs) if (xmlSchemaCheckCVCIDCKeyRef(vctxt) == -1) goto internal_error; /* * Merge/free the IDC table. */ if (inode->idcTable != NULL) { #ifdef DEBUG_IDC_NODE_TABLE xmlSchemaDebugDumpIDCTable(stdout, inode->nsName, inode->localName, inode->idcTable); #endif if ((vctxt->depth > 0) && (vctxt->hasKeyrefs || vctxt->createIDCNodeTables)) { /* * Merge the IDC node table with the table of the parent node. */ if (xmlSchemaBubbleIDCNodeTables(vctxt) == -1) goto internal_error; } } /* * Clear the current ielem. * VAL TODO: Don't free the PSVI IDC tables if they are * requested for the PSVI. */ xmlSchemaClearElemInfo(vctxt, inode); /* * Skip further processing if we are on the validation root. */ if (vctxt->depth == 0) { vctxt->depth--; vctxt->inode = NULL; return (0); } /* * Reset the keyrefDepth if needed. */ if (vctxt->aidcs != NULL) { xmlSchemaIDCAugPtr aidc = vctxt->aidcs; do { if (aidc->keyrefDepth == vctxt->depth) { /* * A 'keyrefDepth' of a key/unique IDC matches the current * depth, this means that we are leaving the scope of the * top-most keyref IDC which refers to this IDC. */ aidc->keyrefDepth = -1; } aidc = aidc->next; } while (aidc != NULL); } vctxt->depth--; vctxt->inode = vctxt->elemInfos[vctxt->depth]; /* * VAL TODO: 7 If the element information item is the `validation root`, it must be * `valid` per Validation Root Valid (ID/IDREF) ($3.3.4). */ return (ret); internal_error: vctxt->err = -1; return (-1); } /* * 3.4.4 Complex Type Definition Validation Rules * Validation Rule: Element Locally Valid (Complex Type) (cvc-complex-type) */ static int xmlSchemaValidateChildElem(xmlSchemaValidCtxtPtr vctxt) { xmlSchemaNodeInfoPtr pielem; xmlSchemaTypePtr ptype; int ret = 0; if (vctxt->depth <= 0) { VERROR_INT("xmlSchemaValidateChildElem", "not intended for the validation root"); return (-1); } pielem = vctxt->elemInfos[vctxt->depth -1]; if (pielem->flags & XML_SCHEMA_ELEM_INFO_EMPTY) pielem->flags ^= XML_SCHEMA_ELEM_INFO_EMPTY; /* * Handle 'nilled' elements. */ if (INODE_NILLED(pielem)) { /* * SPEC (cvc-elt) (3.3.4) : (3.2.1) */ ACTIVATE_PARENT_ELEM; ret = XML_SCHEMAV_CVC_ELT_3_2_1; VERROR(ret, NULL, "Neither character nor element content is allowed, " "because the element was 'nilled'"); ACTIVATE_ELEM; goto unexpected_elem; } ptype = pielem->typeDef; if (ptype->builtInType == XML_SCHEMAS_ANYTYPE) { /* * Workaround for "anyType": we have currently no content model * assigned for "anyType", so handle it explicitly. * "anyType" has an unbounded, lax "any" wildcard. */ vctxt->inode->decl = xmlSchemaGetElem(vctxt->schema, vctxt->inode->localName, vctxt->inode->nsName); if (vctxt->inode->decl == NULL) { xmlSchemaAttrInfoPtr iattr; /* * Process "xsi:type". * SPEC (cvc-assess-elt) (1.2.1.2.1) - (1.2.1.2.3) */ iattr = xmlSchemaGetMetaAttrInfo(vctxt, XML_SCHEMA_ATTR_INFO_META_XSI_TYPE); if (iattr != NULL) { ret = xmlSchemaProcessXSIType(vctxt, iattr, &(vctxt->inode->typeDef), NULL); if (ret != 0) { if (ret == -1) { VERROR_INT("xmlSchemaValidateChildElem", "calling xmlSchemaProcessXSIType() to " "process the attribute 'xsi:nil'"); return (-1); } return (ret); } } else { /* * Fallback to "anyType". * * SPEC (cvc-assess-elt) * "If the item cannot be `strictly assessed`, [...] * an element information item's schema validity may be laxly * assessed if its `context-determined declaration` is not * skip by `validating` with respect to the `ur-type * definition` as per Element Locally Valid (Type) ($3.3.4)." */ vctxt->inode->typeDef = xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYTYPE); } } return (0); } switch (ptype->contentType) { case XML_SCHEMA_CONTENT_EMPTY: /* * SPEC (2.1) "If the {content type} is empty, then the * element information item has no character or element * information item [children]." */ ACTIVATE_PARENT_ELEM ret = XML_SCHEMAV_CVC_COMPLEX_TYPE_2_1; VERROR(ret, NULL, "Element content is not allowed, " "because the content type is empty"); ACTIVATE_ELEM goto unexpected_elem; break; case XML_SCHEMA_CONTENT_MIXED: case XML_SCHEMA_CONTENT_ELEMENTS: { xmlRegExecCtxtPtr regexCtxt; xmlChar *values[10]; int terminal, nbval = 10, nbneg; /* VAL TODO: Optimized "anyType" validation.*/ if (ptype->contModel == NULL) { VERROR_INT("xmlSchemaValidateChildElem", "type has elem content but no content model"); return (-1); } /* * Safety belt for evaluation if the cont. model was already * examined to be invalid. */ if (pielem->flags & XML_SCHEMA_ELEM_INFO_ERR_BAD_CONTENT) { VERROR_INT("xmlSchemaValidateChildElem", "validating elem, but elem content is already invalid"); return (-1); } regexCtxt = pielem->regexCtxt; if (regexCtxt == NULL) { /* * Create the regex context. */ regexCtxt = xmlRegNewExecCtxt(ptype->contModel, xmlSchemaVContentModelCallback, vctxt); if (regexCtxt == NULL) { VERROR_INT("xmlSchemaValidateChildElem", "failed to create a regex context"); return (-1); } pielem->regexCtxt = regexCtxt; #ifdef DEBUG_AUTOMATA xmlGenericError(xmlGenericErrorContext, "AUTOMATA create on '%s'\n", pielem->localName); #endif } /* * SPEC (2.4) "If the {content type} is element-only or mixed, * then the sequence of the element information item's * element information item [children], if any, taken in * order, is `valid` with respect to the {content type}'s * particle, as defined in Element Sequence Locally Valid * (Particle) ($3.9.4)." */ ret = xmlRegExecPushString2(regexCtxt, vctxt->inode->localName, vctxt->inode->nsName, vctxt->inode); #ifdef DEBUG_AUTOMATA if (ret < 0) xmlGenericError(xmlGenericErrorContext, "AUTOMATON push ERROR for '%s' on '%s'\n", vctxt->inode->localName, pielem->localName); else xmlGenericError(xmlGenericErrorContext, "AUTOMATON push OK for '%s' on '%s'\n", vctxt->inode->localName, pielem->localName); #endif if (vctxt->err == XML_SCHEMAV_INTERNAL) { VERROR_INT("xmlSchemaValidateChildElem", "calling xmlRegExecPushString2()"); return (-1); } if (ret < 0) { xmlRegExecErrInfo(regexCtxt, NULL, &nbval, &nbneg, &values[0], &terminal); xmlSchemaComplexTypeErr(ACTXT_CAST vctxt, XML_SCHEMAV_ELEMENT_CONTENT, NULL,NULL, "This element is not expected", nbval, nbneg, values); ret = vctxt->err; goto unexpected_elem; } else ret = 0; } break; case XML_SCHEMA_CONTENT_SIMPLE: case XML_SCHEMA_CONTENT_BASIC: ACTIVATE_PARENT_ELEM if (WXS_IS_COMPLEX(ptype)) { /* * SPEC (cvc-complex-type) (2.2) * "If the {content type} is a simple type definition, then * the element information item has no element information * item [children], ..." */ ret = XML_SCHEMAV_CVC_COMPLEX_TYPE_2_2; VERROR(ret, NULL, "Element content is not allowed, " "because the content type is a simple type definition"); } else { /* * SPEC (cvc-type) (3.1.2) "The element information item must * have no element information item [children]." */ ret = XML_SCHEMAV_CVC_TYPE_3_1_2; VERROR(ret, NULL, "Element content is not allowed, " "because the type definition is simple"); } ACTIVATE_ELEM ret = vctxt->err; goto unexpected_elem; break; default: break; } return (ret); unexpected_elem: /* * Pop this element and set the skipDepth to skip * all further content of the parent element. */ vctxt->skipDepth = vctxt->depth; vctxt->inode->flags |= XML_SCHEMA_NODE_INFO_ERR_NOT_EXPECTED; pielem->flags |= XML_SCHEMA_ELEM_INFO_ERR_BAD_CONTENT; return (ret); } #define XML_SCHEMA_PUSH_TEXT_PERSIST 1 #define XML_SCHEMA_PUSH_TEXT_CREATED 2 #define XML_SCHEMA_PUSH_TEXT_VOLATILE 3 static int xmlSchemaVPushText(xmlSchemaValidCtxtPtr vctxt, int nodeType, const xmlChar *value, int len, int mode, int *consumed) { /* * Unfortunately we have to duplicate the text sometimes. * OPTIMIZE: Maybe we could skip it, if: * 1. content type is simple * 2. whitespace is "collapse" * 3. it consists of whitespace only * * Process character content. */ if (consumed != NULL) *consumed = 0; if (INODE_NILLED(vctxt->inode)) { /* * SPEC cvc-elt (3.3.4 - 3.2.1) * "The element information item must have no character or * element information item [children]." */ VERROR(XML_SCHEMAV_CVC_ELT_3_2_1, NULL, "Neither character nor element content is allowed " "because the element is 'nilled'"); return (vctxt->err); } /* * SPEC (2.1) "If the {content type} is empty, then the * element information item has no character or element * information item [children]." */ if (vctxt->inode->typeDef->contentType == XML_SCHEMA_CONTENT_EMPTY) { VERROR(XML_SCHEMAV_CVC_COMPLEX_TYPE_2_1, NULL, "Character content is not allowed, " "because the content type is empty"); return (vctxt->err); } if (vctxt->inode->typeDef->contentType == XML_SCHEMA_CONTENT_ELEMENTS) { if ((nodeType != XML_TEXT_NODE) || (! xmlSchemaIsBlank((xmlChar *) value, len))) { /* * SPEC cvc-complex-type (2.3) * "If the {content type} is element-only, then the * element information item has no character information * item [children] other than those whose [character * code] is defined as a white space in [XML 1.0 (Second * Edition)]." */ VERROR(XML_SCHEMAV_CVC_COMPLEX_TYPE_2_3, NULL, "Character content other than whitespace is not allowed " "because the content type is 'element-only'"); return (vctxt->err); } return (0); } if ((value == NULL) || (value[0] == 0)) return (0); /* * Save the value. * NOTE that even if the content type is *mixed*, we need the * *initial value* for default/fixed value constraints. */ if ((vctxt->inode->typeDef->contentType == XML_SCHEMA_CONTENT_MIXED) && ((vctxt->inode->decl == NULL) || (vctxt->inode->decl->value == NULL))) return (0); if (vctxt->inode->value == NULL) { /* * Set the value. */ switch (mode) { case XML_SCHEMA_PUSH_TEXT_PERSIST: /* * When working on a tree. */ vctxt->inode->value = value; break; case XML_SCHEMA_PUSH_TEXT_CREATED: /* * When working with the reader. * The value will be freed by the element info. */ vctxt->inode->value = value; if (consumed != NULL) *consumed = 1; vctxt->inode->flags |= XML_SCHEMA_NODE_INFO_FLAG_OWNED_VALUES; break; case XML_SCHEMA_PUSH_TEXT_VOLATILE: /* * When working with SAX. * The value will be freed by the element info. */ if (len != -1) vctxt->inode->value = BAD_CAST xmlStrndup(value, len); else vctxt->inode->value = BAD_CAST xmlStrdup(value); vctxt->inode->flags |= XML_SCHEMA_NODE_INFO_FLAG_OWNED_VALUES; break; default: break; } } else { if (len < 0) len = xmlStrlen(value); /* * Concat the value. */ if (vctxt->inode->flags & XML_SCHEMA_NODE_INFO_FLAG_OWNED_VALUES) { vctxt->inode->value = BAD_CAST xmlStrncat( (xmlChar *) vctxt->inode->value, value, len); } else { vctxt->inode->value = BAD_CAST xmlStrncatNew(vctxt->inode->value, value, len); vctxt->inode->flags |= XML_SCHEMA_NODE_INFO_FLAG_OWNED_VALUES; } } return (0); } static int xmlSchemaValidateElem(xmlSchemaValidCtxtPtr vctxt) { int ret = 0; if ((vctxt->skipDepth != -1) && (vctxt->depth >= vctxt->skipDepth)) { VERROR_INT("xmlSchemaValidateElem", "in skip-state"); goto internal_error; } if (vctxt->xsiAssemble) { /* * We will stop validation if there was an error during * dynamic schema construction. * Note that we simply set @skipDepth to 0, this could * mean that a streaming document via SAX would be * still read to the end but it won't be validated any more. * TODO: If we are sure how to stop the validation at once * for all input scenarios, then this should be changed to * instantly stop the validation. */ ret = xmlSchemaAssembleByXSI(vctxt); if (ret != 0) { if (ret == -1) goto internal_error; vctxt->skipDepth = 0; return(ret); } /* * Augment the IDC definitions for the main schema and all imported ones * NOTE: main schema is the first in the imported list */ xmlHashScan(vctxt->schema->schemasImports, xmlSchemaAugmentImportedIDC, vctxt); } if (vctxt->depth > 0) { /* * Validate this element against the content model * of the parent. */ ret = xmlSchemaValidateChildElem(vctxt); if (ret != 0) { if (ret < 0) { VERROR_INT("xmlSchemaValidateElem", "calling xmlSchemaStreamValidateChildElement()"); goto internal_error; } goto exit; } if (vctxt->depth == vctxt->skipDepth) goto exit; if ((vctxt->inode->decl == NULL) && (vctxt->inode->typeDef == NULL)) { VERROR_INT("xmlSchemaValidateElem", "the child element was valid but neither the " "declaration nor the type was set"); goto internal_error; } } else { /* * Get the declaration of the validation root. */ vctxt->inode->decl = xmlSchemaGetElem(vctxt->schema, vctxt->inode->localName, vctxt->inode->nsName); if (vctxt->inode->decl == NULL) { ret = XML_SCHEMAV_CVC_ELT_1; VERROR(ret, NULL, "No matching global declaration available " "for the validation root"); goto exit; } } if (vctxt->inode->decl == NULL) goto type_validation; if (vctxt->inode->decl->type == XML_SCHEMA_TYPE_ANY) { int skip; /* * Wildcards. */ ret = xmlSchemaValidateElemWildcard(vctxt, &skip); if (ret != 0) { if (ret < 0) { VERROR_INT("xmlSchemaValidateElem", "calling xmlSchemaValidateElemWildcard()"); goto internal_error; } goto exit; } if (skip) { vctxt->skipDepth = vctxt->depth; goto exit; } /* * The declaration might be set by the wildcard validation, * when the processContents is "lax" or "strict". */ if (vctxt->inode->decl->type != XML_SCHEMA_TYPE_ELEMENT) { /* * Clear the "decl" field to not confuse further processing. */ vctxt->inode->decl = NULL; goto type_validation; } } /* * Validate against the declaration. */ ret = xmlSchemaValidateElemDecl(vctxt); if (ret != 0) { if (ret < 0) { VERROR_INT("xmlSchemaValidateElem", "calling xmlSchemaValidateElemDecl()"); goto internal_error; } goto exit; } /* * Validate against the type definition. */ type_validation: if (vctxt->inode->typeDef == NULL) { vctxt->inode->flags |= XML_SCHEMA_NODE_INFO_ERR_BAD_TYPE; ret = XML_SCHEMAV_CVC_TYPE_1; VERROR(ret, NULL, "The type definition is absent"); goto exit; } if (vctxt->inode->typeDef->flags & XML_SCHEMAS_TYPE_ABSTRACT) { vctxt->inode->flags |= XML_SCHEMA_NODE_INFO_ERR_BAD_TYPE; ret = XML_SCHEMAV_CVC_TYPE_2; VERROR(ret, NULL, "The type definition is abstract"); goto exit; } /* * Evaluate IDCs. Do it here, since new IDC matchers are registered * during validation against the declaration. This must be done * _before_ attribute validation. */ if (vctxt->xpathStates != NULL) { ret = xmlSchemaXPathEvaluate(vctxt, XML_ELEMENT_NODE); vctxt->inode->appliedXPath = 1; if (ret == -1) { VERROR_INT("xmlSchemaValidateElem", "calling xmlSchemaXPathEvaluate()"); goto internal_error; } } /* * Validate attributes. */ if (WXS_IS_COMPLEX(vctxt->inode->typeDef)) { if ((vctxt->nbAttrInfos != 0) || (vctxt->inode->typeDef->attrUses != NULL)) { ret = xmlSchemaVAttributesComplex(vctxt); } } else if (vctxt->nbAttrInfos != 0) { ret = xmlSchemaVAttributesSimple(vctxt); } /* * Clear registered attributes. */ if (vctxt->nbAttrInfos != 0) xmlSchemaClearAttrInfos(vctxt); if (ret == -1) { VERROR_INT("xmlSchemaValidateElem", "calling attributes validation"); goto internal_error; } /* * Don't return an error if attributes are invalid on purpose. */ ret = 0; exit: if (ret != 0) vctxt->skipDepth = vctxt->depth; return (ret); internal_error: return (-1); } #ifdef XML_SCHEMA_READER_ENABLED static int xmlSchemaVReaderWalk(xmlSchemaValidCtxtPtr vctxt) { const int WHTSP = 13, SIGN_WHTSP = 14, END_ELEM = 15; int depth, nodeType, ret = 0, consumed; xmlSchemaNodeInfoPtr ielem; vctxt->depth = -1; ret = xmlTextReaderRead(vctxt->reader); /* * Move to the document element. */ while (ret == 1) { nodeType = xmlTextReaderNodeType(vctxt->reader); if (nodeType == XML_ELEMENT_NODE) goto root_found; ret = xmlTextReaderRead(vctxt->reader); } goto exit; root_found: do { depth = xmlTextReaderDepth(vctxt->reader); nodeType = xmlTextReaderNodeType(vctxt->reader); if (nodeType == XML_ELEMENT_NODE) { vctxt->depth++; if (xmlSchemaValidatorPushElem(vctxt) == -1) { VERROR_INT("xmlSchemaVReaderWalk", "calling xmlSchemaValidatorPushElem()"); goto internal_error; } ielem = vctxt->inode; ielem->localName = xmlTextReaderLocalName(vctxt->reader); ielem->nsName = xmlTextReaderNamespaceUri(vctxt->reader); ielem->flags |= XML_SCHEMA_NODE_INFO_FLAG_OWNED_NAMES; /* * Is the element empty? */ ret = xmlTextReaderIsEmptyElement(vctxt->reader); if (ret == -1) { VERROR_INT("xmlSchemaVReaderWalk", "calling xmlTextReaderIsEmptyElement()"); goto internal_error; } if (ret) { ielem->flags |= XML_SCHEMA_ELEM_INFO_EMPTY; } /* * Register attributes. */ vctxt->nbAttrInfos = 0; ret = xmlTextReaderMoveToFirstAttribute(vctxt->reader); if (ret == -1) { VERROR_INT("xmlSchemaVReaderWalk", "calling xmlTextReaderMoveToFirstAttribute()"); goto internal_error; } if (ret == 1) { do { /* * VAL TODO: How do we know that the reader works on a * node tree, to be able to pass a node here? */ if (xmlSchemaValidatorPushAttribute(vctxt, NULL, (const xmlChar *) xmlTextReaderLocalName(vctxt->reader), xmlTextReaderNamespaceUri(vctxt->reader), 1, xmlTextReaderValue(vctxt->reader), 1) == -1) { VERROR_INT("xmlSchemaVReaderWalk", "calling xmlSchemaValidatorPushAttribute()"); goto internal_error; } ret = xmlTextReaderMoveToNextAttribute(vctxt->reader); if (ret == -1) { VERROR_INT("xmlSchemaVReaderWalk", "calling xmlTextReaderMoveToFirstAttribute()"); goto internal_error; } } while (ret == 1); /* * Back to element position. */ ret = xmlTextReaderMoveToElement(vctxt->reader); if (ret == -1) { VERROR_INT("xmlSchemaVReaderWalk", "calling xmlTextReaderMoveToElement()"); goto internal_error; } } /* * Validate the element. */ ret= xmlSchemaValidateElem(vctxt); if (ret != 0) { if (ret == -1) { VERROR_INT("xmlSchemaVReaderWalk", "calling xmlSchemaValidateElem()"); goto internal_error; } goto exit; } if (vctxt->depth == vctxt->skipDepth) { int curDepth; /* * Skip all content. */ if ((ielem->flags & XML_SCHEMA_ELEM_INFO_EMPTY) == 0) { ret = xmlTextReaderRead(vctxt->reader); curDepth = xmlTextReaderDepth(vctxt->reader); while ((ret == 1) && (curDepth != depth)) { ret = xmlTextReaderRead(vctxt->reader); curDepth = xmlTextReaderDepth(vctxt->reader); } if (ret < 0) { /* * VAL TODO: A reader error occurred; what to do here? */ ret = 1; goto exit; } } goto leave_elem; } /* * READER VAL TODO: Is an END_ELEM really never called * if the elem is empty? */ if (ielem->flags & XML_SCHEMA_ELEM_INFO_EMPTY) goto leave_elem; } else if (nodeType == END_ELEM) { /* * Process END of element. */ leave_elem: ret = xmlSchemaValidatorPopElem(vctxt); if (ret != 0) { if (ret < 0) { VERROR_INT("xmlSchemaVReaderWalk", "calling xmlSchemaValidatorPopElem()"); goto internal_error; } goto exit; } if (vctxt->depth >= 0) ielem = vctxt->inode; else ielem = NULL; } else if ((nodeType == XML_TEXT_NODE) || (nodeType == XML_CDATA_SECTION_NODE) || (nodeType == WHTSP) || (nodeType == SIGN_WHTSP)) { /* * Process character content. */ xmlChar *value; if ((nodeType == WHTSP) || (nodeType == SIGN_WHTSP)) nodeType = XML_TEXT_NODE; value = xmlTextReaderValue(vctxt->reader); ret = xmlSchemaVPushText(vctxt, nodeType, BAD_CAST value, -1, XML_SCHEMA_PUSH_TEXT_CREATED, &consumed); if (! consumed) xmlFree(value); if (ret == -1) { VERROR_INT("xmlSchemaVReaderWalk", "calling xmlSchemaVPushText()"); goto internal_error; } } else if ((nodeType == XML_ENTITY_NODE) || (nodeType == XML_ENTITY_REF_NODE)) { /* * VAL TODO: What to do with entities? */ TODO } /* * Read next node. */ ret = xmlTextReaderRead(vctxt->reader); } while (ret == 1); exit: return (ret); internal_error: return (-1); } #endif /************************************************************************ * * * SAX validation handlers * * * ************************************************************************/ /* * Process text content. */ static void xmlSchemaSAXHandleText(void *ctx, const xmlChar * ch, int len) { xmlSchemaValidCtxtPtr vctxt = (xmlSchemaValidCtxtPtr) ctx; if (vctxt->depth < 0) return; if ((vctxt->skipDepth != -1) && (vctxt->depth >= vctxt->skipDepth)) return; if (vctxt->inode->flags & XML_SCHEMA_ELEM_INFO_EMPTY) vctxt->inode->flags ^= XML_SCHEMA_ELEM_INFO_EMPTY; if (xmlSchemaVPushText(vctxt, XML_TEXT_NODE, ch, len, XML_SCHEMA_PUSH_TEXT_VOLATILE, NULL) == -1) { VERROR_INT("xmlSchemaSAXHandleCDataSection", "calling xmlSchemaVPushText()"); vctxt->err = -1; xmlStopParser(vctxt->parserCtxt); } } /* * Process CDATA content. */ static void xmlSchemaSAXHandleCDataSection(void *ctx, const xmlChar * ch, int len) { xmlSchemaValidCtxtPtr vctxt = (xmlSchemaValidCtxtPtr) ctx; if (vctxt->depth < 0) return; if ((vctxt->skipDepth != -1) && (vctxt->depth >= vctxt->skipDepth)) return; if (vctxt->inode->flags & XML_SCHEMA_ELEM_INFO_EMPTY) vctxt->inode->flags ^= XML_SCHEMA_ELEM_INFO_EMPTY; if (xmlSchemaVPushText(vctxt, XML_CDATA_SECTION_NODE, ch, len, XML_SCHEMA_PUSH_TEXT_VOLATILE, NULL) == -1) { VERROR_INT("xmlSchemaSAXHandleCDataSection", "calling xmlSchemaVPushText()"); vctxt->err = -1; xmlStopParser(vctxt->parserCtxt); } } static void xmlSchemaSAXHandleReference(void *ctx ATTRIBUTE_UNUSED, const xmlChar * name ATTRIBUTE_UNUSED) { xmlSchemaValidCtxtPtr vctxt = (xmlSchemaValidCtxtPtr) ctx; if (vctxt->depth < 0) return; if ((vctxt->skipDepth != -1) && (vctxt->depth >= vctxt->skipDepth)) return; /* SAX VAL TODO: What to do here? */ TODO } static void xmlSchemaSAXHandleStartElementNs(void *ctx, const xmlChar * localname, const xmlChar * prefix ATTRIBUTE_UNUSED, const xmlChar * URI, int nb_namespaces, const xmlChar ** namespaces, int nb_attributes, int nb_defaulted ATTRIBUTE_UNUSED, const xmlChar ** attributes) { xmlSchemaValidCtxtPtr vctxt = (xmlSchemaValidCtxtPtr) ctx; int ret; xmlSchemaNodeInfoPtr ielem; int i, j; /* * SAX VAL TODO: What to do with nb_defaulted? */ /* * Skip elements if inside a "skip" wildcard or invalid. */ vctxt->depth++; if ((vctxt->skipDepth != -1) && (vctxt->depth >= vctxt->skipDepth)) return; /* * Push the element. */ if (xmlSchemaValidatorPushElem(vctxt) == -1) { VERROR_INT("xmlSchemaSAXHandleStartElementNs", "calling xmlSchemaValidatorPushElem()"); goto internal_error; } ielem = vctxt->inode; /* * TODO: Is this OK? */ ielem->nodeLine = xmlSAX2GetLineNumber(vctxt->parserCtxt); ielem->localName = localname; ielem->nsName = URI; ielem->flags |= XML_SCHEMA_ELEM_INFO_EMPTY; /* * Register namespaces on the elem info. */ if (nb_namespaces != 0) { /* * Although the parser builds its own namespace list, * we have no access to it, so we'll use an own one. */ for (i = 0, j = 0; i < nb_namespaces; i++, j += 2) { /* * Store prefix and namespace name. */ if (ielem->nsBindings == NULL) { ielem->nsBindings = (const xmlChar **) xmlMalloc(10 * sizeof(const xmlChar *)); if (ielem->nsBindings == NULL) { xmlSchemaVErrMemory(vctxt, "allocating namespace bindings for SAX validation", NULL); goto internal_error; } ielem->nbNsBindings = 0; ielem->sizeNsBindings = 5; } else if (ielem->sizeNsBindings <= ielem->nbNsBindings) { ielem->sizeNsBindings *= 2; ielem->nsBindings = (const xmlChar **) xmlRealloc( (void *) ielem->nsBindings, ielem->sizeNsBindings * 2 * sizeof(const xmlChar *)); if (ielem->nsBindings == NULL) { xmlSchemaVErrMemory(vctxt, "re-allocating namespace bindings for SAX validation", NULL); goto internal_error; } } ielem->nsBindings[ielem->nbNsBindings * 2] = namespaces[j]; if (namespaces[j+1][0] == 0) { /* * Handle xmlns="". */ ielem->nsBindings[ielem->nbNsBindings * 2 + 1] = NULL; } else ielem->nsBindings[ielem->nbNsBindings * 2 + 1] = namespaces[j+1]; ielem->nbNsBindings++; } } /* * Register attributes. * SAX VAL TODO: We are not adding namespace declaration * attributes yet. */ if (nb_attributes != 0) { int valueLen, k, l; xmlChar *value; for (j = 0, i = 0; i < nb_attributes; i++, j += 5) { /* * Duplicate the value, changing any &#38; to a literal ampersand. * * libxml2 differs from normal SAX here in that it escapes all ampersands * as &#38; instead of delivering the raw converted string. Changing the * behavior at this point would break applications that use this API, so * we are forced to work around it. */ valueLen = attributes[j+4] - attributes[j+3]; value = xmlMallocAtomic(valueLen + 1); if (value == NULL) { xmlSchemaVErrMemory(vctxt, "allocating string for decoded attribute", NULL); goto internal_error; } for (k = 0, l = 0; k < valueLen; l++) { if (k < valueLen - 4 && attributes[j+3][k+0] == '&' && attributes[j+3][k+1] == '#' && attributes[j+3][k+2] == '3' && attributes[j+3][k+3] == '8' && attributes[j+3][k+4] == ';') { value[l] = '&'; k += 5; } else { value[l] = attributes[j+3][k]; k++; } } value[l] = '\0'; /* * TODO: Set the node line. */ ret = xmlSchemaValidatorPushAttribute(vctxt, NULL, ielem->nodeLine, attributes[j], attributes[j+2], 0, value, 1); if (ret == -1) { VERROR_INT("xmlSchemaSAXHandleStartElementNs", "calling xmlSchemaValidatorPushAttribute()"); goto internal_error; } } } /* * Validate the element. */ ret = xmlSchemaValidateElem(vctxt); if (ret != 0) { if (ret == -1) { VERROR_INT("xmlSchemaSAXHandleStartElementNs", "calling xmlSchemaValidateElem()"); goto internal_error; } goto exit; } exit: return; internal_error: vctxt->err = -1; xmlStopParser(vctxt->parserCtxt); return; } static void xmlSchemaSAXHandleEndElementNs(void *ctx, const xmlChar * localname ATTRIBUTE_UNUSED, const xmlChar * prefix ATTRIBUTE_UNUSED, const xmlChar * URI ATTRIBUTE_UNUSED) { xmlSchemaValidCtxtPtr vctxt = (xmlSchemaValidCtxtPtr) ctx; int res; /* * Skip elements if inside a "skip" wildcard or if invalid. */ if (vctxt->skipDepth != -1) { if (vctxt->depth > vctxt->skipDepth) { vctxt->depth--; return; } else vctxt->skipDepth = -1; } /* * SAX VAL TODO: Just a temporary check. */ if ((!xmlStrEqual(vctxt->inode->localName, localname)) || (!xmlStrEqual(vctxt->inode->nsName, URI))) { VERROR_INT("xmlSchemaSAXHandleEndElementNs", "elem pop mismatch"); } res = xmlSchemaValidatorPopElem(vctxt); if (res != 0) { if (res < 0) { VERROR_INT("xmlSchemaSAXHandleEndElementNs", "calling xmlSchemaValidatorPopElem()"); goto internal_error; } goto exit; } exit: return; internal_error: vctxt->err = -1; xmlStopParser(vctxt->parserCtxt); return; } /************************************************************************ * * * Validation interfaces * * * ************************************************************************/ /** * xmlSchemaNewValidCtxt: * @schema: a precompiled XML Schemas * * Create an XML Schemas validation context based on the given schema. * * Returns the validation context or NULL in case of error */ xmlSchemaValidCtxtPtr xmlSchemaNewValidCtxt(xmlSchemaPtr schema) { xmlSchemaValidCtxtPtr ret; ret = (xmlSchemaValidCtxtPtr) xmlMalloc(sizeof(xmlSchemaValidCtxt)); if (ret == NULL) { xmlSchemaVErrMemory(NULL, "allocating validation context", NULL); return (NULL); } memset(ret, 0, sizeof(xmlSchemaValidCtxt)); ret->type = XML_SCHEMA_CTXT_VALIDATOR; ret->dict = xmlDictCreate(); ret->nodeQNames = xmlSchemaItemListCreate(); ret->schema = schema; return (ret); } /** * xmlSchemaValidateSetFilename: * @vctxt: the schema validation context * @filename: the file name * * Workaround to provide file error reporting information when this is * not provided by current APIs */ void xmlSchemaValidateSetFilename(xmlSchemaValidCtxtPtr vctxt, const char *filename) { if (vctxt == NULL) return; if (vctxt->filename != NULL) xmlFree(vctxt->filename); if (filename != NULL) vctxt->filename = (char *) xmlStrdup((const xmlChar *) filename); else vctxt->filename = NULL; } /** * xmlSchemaClearValidCtxt: * @vctxt: the schema validation context * * Free the resources associated to the schema validation context; * leaves some fields alive intended for reuse of the context. */ static void xmlSchemaClearValidCtxt(xmlSchemaValidCtxtPtr vctxt) { if (vctxt == NULL) return; /* * TODO: Should we clear the flags? * Might be problematic if one reuses the context * and assumes that the options remain the same. */ vctxt->flags = 0; vctxt->validationRoot = NULL; vctxt->doc = NULL; #ifdef LIBXML_READER_ENABLED vctxt->reader = NULL; #endif vctxt->hasKeyrefs = 0; if (vctxt->value != NULL) { xmlSchemaFreeValue(vctxt->value); vctxt->value = NULL; } /* * Augmented IDC information. */ if (vctxt->aidcs != NULL) { xmlSchemaIDCAugPtr cur = vctxt->aidcs, next; do { next = cur->next; xmlFree(cur); cur = next; } while (cur != NULL); vctxt->aidcs = NULL; } if (vctxt->idcMatcherCache != NULL) { xmlSchemaIDCMatcherPtr matcher = vctxt->idcMatcherCache, tmp; while (matcher) { tmp = matcher; matcher = matcher->nextCached; xmlSchemaIDCFreeMatcherList(tmp); } vctxt->idcMatcherCache = NULL; } if (vctxt->idcNodes != NULL) { int i; xmlSchemaPSVIIDCNodePtr item; for (i = 0; i < vctxt->nbIdcNodes; i++) { item = vctxt->idcNodes[i]; xmlFree(item->keys); xmlFree(item); } xmlFree(vctxt->idcNodes); vctxt->idcNodes = NULL; vctxt->nbIdcNodes = 0; vctxt->sizeIdcNodes = 0; } if (vctxt->idcKeys != NULL) { int i; for (i = 0; i < vctxt->nbIdcKeys; i++) xmlSchemaIDCFreeKey(vctxt->idcKeys[i]); xmlFree(vctxt->idcKeys); vctxt->idcKeys = NULL; vctxt->nbIdcKeys = 0; vctxt->sizeIdcKeys = 0; } /* * Note that we won't delete the XPath state pool here. */ if (vctxt->xpathStates != NULL) { xmlSchemaFreeIDCStateObjList(vctxt->xpathStates); vctxt->xpathStates = NULL; } /* * Attribute info. */ if (vctxt->nbAttrInfos != 0) { xmlSchemaClearAttrInfos(vctxt); } /* * Element info. */ if (vctxt->elemInfos != NULL) { int i; xmlSchemaNodeInfoPtr ei; for (i = 0; i < vctxt->sizeElemInfos; i++) { ei = vctxt->elemInfos[i]; if (ei == NULL) break; xmlSchemaClearElemInfo(vctxt, ei); } } xmlSchemaItemListClear(vctxt->nodeQNames); /* Recreate the dict. */ xmlDictFree(vctxt->dict); /* * TODO: Is is save to recreate it? Do we have a scenario * where the user provides the dict? */ vctxt->dict = xmlDictCreate(); if (vctxt->filename != NULL) { xmlFree(vctxt->filename); vctxt->filename = NULL; } } /** * xmlSchemaFreeValidCtxt: * @ctxt: the schema validation context * * Free the resources associated to the schema validation context */ void xmlSchemaFreeValidCtxt(xmlSchemaValidCtxtPtr ctxt) { if (ctxt == NULL) return; if (ctxt->value != NULL) xmlSchemaFreeValue(ctxt->value); if (ctxt->pctxt != NULL) xmlSchemaFreeParserCtxt(ctxt->pctxt); if (ctxt->idcNodes != NULL) { int i; xmlSchemaPSVIIDCNodePtr item; for (i = 0; i < ctxt->nbIdcNodes; i++) { item = ctxt->idcNodes[i]; xmlFree(item->keys); xmlFree(item); } xmlFree(ctxt->idcNodes); } if (ctxt->idcKeys != NULL) { int i; for (i = 0; i < ctxt->nbIdcKeys; i++) xmlSchemaIDCFreeKey(ctxt->idcKeys[i]); xmlFree(ctxt->idcKeys); } if (ctxt->xpathStates != NULL) { xmlSchemaFreeIDCStateObjList(ctxt->xpathStates); ctxt->xpathStates = NULL; } if (ctxt->xpathStatePool != NULL) { xmlSchemaFreeIDCStateObjList(ctxt->xpathStatePool); ctxt->xpathStatePool = NULL; } /* * Augmented IDC information. */ if (ctxt->aidcs != NULL) { xmlSchemaIDCAugPtr cur = ctxt->aidcs, next; do { next = cur->next; xmlFree(cur); cur = next; } while (cur != NULL); } if (ctxt->attrInfos != NULL) { int i; xmlSchemaAttrInfoPtr attr; /* Just a paranoid call to the cleanup. */ if (ctxt->nbAttrInfos != 0) xmlSchemaClearAttrInfos(ctxt); for (i = 0; i < ctxt->sizeAttrInfos; i++) { attr = ctxt->attrInfos[i]; xmlFree(attr); } xmlFree(ctxt->attrInfos); } if (ctxt->elemInfos != NULL) { int i; xmlSchemaNodeInfoPtr ei; for (i = 0; i < ctxt->sizeElemInfos; i++) { ei = ctxt->elemInfos[i]; if (ei == NULL) break; xmlSchemaClearElemInfo(ctxt, ei); xmlFree(ei); } xmlFree(ctxt->elemInfos); } if (ctxt->nodeQNames != NULL) xmlSchemaItemListFree(ctxt->nodeQNames); if (ctxt->dict != NULL) xmlDictFree(ctxt->dict); if (ctxt->filename != NULL) xmlFree(ctxt->filename); xmlFree(ctxt); } /** * xmlSchemaIsValid: * @ctxt: the schema validation context * * Check if any error was detected during validation. * * Returns 1 if valid so far, 0 if errors were detected, and -1 in case * of internal error. */ int xmlSchemaIsValid(xmlSchemaValidCtxtPtr ctxt) { if (ctxt == NULL) return(-1); return(ctxt->err == 0); } /** * xmlSchemaSetValidErrors: * @ctxt: a schema validation context * @err: the error function * @warn: the warning function * @ctx: the functions context * * Set the error and warning callback information */ void xmlSchemaSetValidErrors(xmlSchemaValidCtxtPtr ctxt, xmlSchemaValidityErrorFunc err, xmlSchemaValidityWarningFunc warn, void *ctx) { if (ctxt == NULL) return; ctxt->error = err; ctxt->warning = warn; ctxt->errCtxt = ctx; if (ctxt->pctxt != NULL) xmlSchemaSetParserErrors(ctxt->pctxt, err, warn, ctx); } /** * xmlSchemaSetValidStructuredErrors: * @ctxt: a schema validation context * @serror: the structured error function * @ctx: the functions context * * Set the structured error callback */ void xmlSchemaSetValidStructuredErrors(xmlSchemaValidCtxtPtr ctxt, xmlStructuredErrorFunc serror, void *ctx) { if (ctxt == NULL) return; ctxt->serror = serror; ctxt->error = NULL; ctxt->warning = NULL; ctxt->errCtxt = ctx; if (ctxt->pctxt != NULL) xmlSchemaSetParserStructuredErrors(ctxt->pctxt, serror, ctx); } /** * xmlSchemaGetValidErrors: * @ctxt: a XML-Schema validation context * @err: the error function result * @warn: the warning function result * @ctx: the functions context result * * Get the error and warning callback information * * Returns -1 in case of error and 0 otherwise */ int xmlSchemaGetValidErrors(xmlSchemaValidCtxtPtr ctxt, xmlSchemaValidityErrorFunc * err, xmlSchemaValidityWarningFunc * warn, void **ctx) { if (ctxt == NULL) return (-1); if (err != NULL) *err = ctxt->error; if (warn != NULL) *warn = ctxt->warning; if (ctx != NULL) *ctx = ctxt->errCtxt; return (0); } /** * xmlSchemaSetValidOptions: * @ctxt: a schema validation context * @options: a combination of xmlSchemaValidOption * * Sets the options to be used during the validation. * * Returns 0 in case of success, -1 in case of an * API error. */ int xmlSchemaSetValidOptions(xmlSchemaValidCtxtPtr ctxt, int options) { int i; if (ctxt == NULL) return (-1); /* * WARNING: Change the start value if adding to the * xmlSchemaValidOption. * TODO: Is there an other, more easy to maintain, * way? */ for (i = 1; i < (int) sizeof(int) * 8; i++) { if (options & 1<<i) return (-1); } ctxt->options = options; return (0); } /** * xmlSchemaValidCtxtGetOptions: * @ctxt: a schema validation context * * Get the validation context options. * * Returns the option combination or -1 on error. */ int xmlSchemaValidCtxtGetOptions(xmlSchemaValidCtxtPtr ctxt) { if (ctxt == NULL) return (-1); else return (ctxt->options); } static int xmlSchemaVDocWalk(xmlSchemaValidCtxtPtr vctxt) { xmlAttrPtr attr; int ret = 0; xmlSchemaNodeInfoPtr ielem = NULL; xmlNodePtr node, valRoot; const xmlChar *nsName; /* DOC VAL TODO: Move this to the start function. */ if (vctxt->validationRoot != NULL) valRoot = vctxt->validationRoot; else valRoot = xmlDocGetRootElement(vctxt->doc); if (valRoot == NULL) { /* VAL TODO: Error code? */ VERROR(1, NULL, "The document has no document element"); return (1); } for (node = valRoot->next; node != NULL; node = node->next) { if (node->type == XML_ELEMENT_NODE) VERROR(1, NULL, "The document has more than one top element"); } vctxt->depth = -1; vctxt->validationRoot = valRoot; node = valRoot; while (node != NULL) { if ((vctxt->skipDepth != -1) && (vctxt->depth >= vctxt->skipDepth)) goto next_sibling; if (node->type == XML_ELEMENT_NODE) { /* * Init the node-info. */ vctxt->depth++; if (xmlSchemaValidatorPushElem(vctxt) == -1) goto internal_error; ielem = vctxt->inode; ielem->node = node; ielem->nodeLine = node->line; ielem->localName = node->name; if (node->ns != NULL) ielem->nsName = node->ns->href; ielem->flags |= XML_SCHEMA_ELEM_INFO_EMPTY; /* * Register attributes. * DOC VAL TODO: We do not register namespace declaration * attributes yet. */ vctxt->nbAttrInfos = 0; if (node->properties != NULL) { attr = node->properties; do { if (attr->ns != NULL) nsName = attr->ns->href; else nsName = NULL; ret = xmlSchemaValidatorPushAttribute(vctxt, (xmlNodePtr) attr, /* * Note that we give it the line number of the * parent element. */ ielem->nodeLine, attr->name, nsName, 0, xmlNodeListGetString(attr->doc, attr->children, 1), 1); if (ret == -1) { VERROR_INT("xmlSchemaDocWalk", "calling xmlSchemaValidatorPushAttribute()"); goto internal_error; } attr = attr->next; } while (attr); } /* * Validate the element. */ ret = xmlSchemaValidateElem(vctxt); if (ret != 0) { if (ret == -1) { VERROR_INT("xmlSchemaDocWalk", "calling xmlSchemaValidateElem()"); goto internal_error; } /* * Don't stop validation; just skip the content * of this element. */ goto leave_node; } if ((vctxt->skipDepth != -1) && (vctxt->depth >= vctxt->skipDepth)) goto leave_node; } else if ((node->type == XML_TEXT_NODE) || (node->type == XML_CDATA_SECTION_NODE)) { /* * Process character content. */ if ((ielem != NULL) && (ielem->flags & XML_SCHEMA_ELEM_INFO_EMPTY)) ielem->flags ^= XML_SCHEMA_ELEM_INFO_EMPTY; ret = xmlSchemaVPushText(vctxt, node->type, node->content, -1, XML_SCHEMA_PUSH_TEXT_PERSIST, NULL); if (ret < 0) { VERROR_INT("xmlSchemaVDocWalk", "calling xmlSchemaVPushText()"); goto internal_error; } /* * DOC VAL TODO: Should we skip further validation of the * element content here? */ } else if ((node->type == XML_ENTITY_NODE) || (node->type == XML_ENTITY_REF_NODE)) { /* * DOC VAL TODO: What to do with entities? */ VERROR_INT("xmlSchemaVDocWalk", "there is at least one entity reference in the node-tree " "currently being validated. Processing of entities with " "this XML Schema processor is not supported (yet). Please " "substitute entities before validation."); goto internal_error; } else { goto leave_node; /* * DOC VAL TODO: XInclude nodes, etc. */ } /* * Walk the doc. */ if (node->children != NULL) { node = node->children; continue; } leave_node: if (node->type == XML_ELEMENT_NODE) { /* * Leaving the scope of an element. */ if (node != vctxt->inode->node) { VERROR_INT("xmlSchemaVDocWalk", "element position mismatch"); goto internal_error; } ret = xmlSchemaValidatorPopElem(vctxt); if (ret != 0) { if (ret < 0) { VERROR_INT("xmlSchemaVDocWalk", "calling xmlSchemaValidatorPopElem()"); goto internal_error; } } if (node == valRoot) goto exit; } next_sibling: if (node->next != NULL) node = node->next; else { node = node->parent; goto leave_node; } } exit: return (ret); internal_error: return (-1); } static int xmlSchemaPreRun(xmlSchemaValidCtxtPtr vctxt) { /* * Some initialization. */ vctxt->err = 0; vctxt->nberrors = 0; vctxt->depth = -1; vctxt->skipDepth = -1; vctxt->hasKeyrefs = 0; #ifdef ENABLE_IDC_NODE_TABLES_TEST vctxt->createIDCNodeTables = 1; #else vctxt->createIDCNodeTables = 0; #endif /* * Create a schema + parser if necessary. */ if (vctxt->schema == NULL) { xmlSchemaParserCtxtPtr pctxt; vctxt->xsiAssemble = 1; /* * If not schema was given then we will create a schema * dynamically using XSI schema locations. * * Create the schema parser context. */ if ((vctxt->pctxt == NULL) && (xmlSchemaCreatePCtxtOnVCtxt(vctxt) == -1)) return (-1); pctxt = vctxt->pctxt; pctxt->xsiAssemble = 1; /* * Create the schema. */ vctxt->schema = xmlSchemaNewSchema(pctxt); if (vctxt->schema == NULL) return (-1); /* * Create the schema construction context. */ pctxt->constructor = xmlSchemaConstructionCtxtCreate(pctxt->dict); if (pctxt->constructor == NULL) return(-1); pctxt->constructor->mainSchema = vctxt->schema; /* * Take ownership of the constructor to be able to free it. */ pctxt->ownsConstructor = 1; } /* * Augment the IDC definitions for the main schema and all imported ones * NOTE: main schema if the first in the imported list */ xmlHashScan(vctxt->schema->schemasImports, xmlSchemaAugmentImportedIDC, vctxt); return(0); } static void xmlSchemaPostRun(xmlSchemaValidCtxtPtr vctxt) { if (vctxt->xsiAssemble) { if (vctxt->schema != NULL) { xmlSchemaFree(vctxt->schema); vctxt->schema = NULL; } } xmlSchemaClearValidCtxt(vctxt); } static int xmlSchemaVStart(xmlSchemaValidCtxtPtr vctxt) { int ret = 0; if (xmlSchemaPreRun(vctxt) < 0) return(-1); if (vctxt->doc != NULL) { /* * Tree validation. */ ret = xmlSchemaVDocWalk(vctxt); #ifdef LIBXML_READER_ENABLED } else if (vctxt->reader != NULL) { /* * XML Reader validation. */ #ifdef XML_SCHEMA_READER_ENABLED ret = xmlSchemaVReaderWalk(vctxt); #endif #endif } else if ((vctxt->sax != NULL) && (vctxt->parserCtxt != NULL)) { /* * SAX validation. */ ret = xmlParseDocument(vctxt->parserCtxt); } else { VERROR_INT("xmlSchemaVStart", "no instance to validate"); ret = -1; } xmlSchemaPostRun(vctxt); if (ret == 0) ret = vctxt->err; return (ret); } /** * xmlSchemaValidateOneElement: * @ctxt: a schema validation context * @elem: an element node * * Validate a branch of a tree, starting with the given @elem. * * Returns 0 if the element and its subtree is valid, a positive error * code number otherwise and -1 in case of an internal or API error. */ int xmlSchemaValidateOneElement(xmlSchemaValidCtxtPtr ctxt, xmlNodePtr elem) { if ((ctxt == NULL) || (elem == NULL) || (elem->type != XML_ELEMENT_NODE)) return (-1); if (ctxt->schema == NULL) return (-1); ctxt->doc = elem->doc; ctxt->node = elem; ctxt->validationRoot = elem; return(xmlSchemaVStart(ctxt)); } /** * xmlSchemaValidateDoc: * @ctxt: a schema validation context * @doc: a parsed document tree * * Validate a document tree in memory. * * Returns 0 if the document is schemas valid, a positive error code * number otherwise and -1 in case of internal or API error. */ int xmlSchemaValidateDoc(xmlSchemaValidCtxtPtr ctxt, xmlDocPtr doc) { if ((ctxt == NULL) || (doc == NULL)) return (-1); ctxt->doc = doc; ctxt->node = xmlDocGetRootElement(doc); if (ctxt->node == NULL) { xmlSchemaCustomErr(ACTXT_CAST ctxt, XML_SCHEMAV_DOCUMENT_ELEMENT_MISSING, (xmlNodePtr) doc, NULL, "The document has no document element", NULL, NULL); return (ctxt->err); } ctxt->validationRoot = ctxt->node; return (xmlSchemaVStart(ctxt)); } /************************************************************************ * * * Function and data for SAX streaming API * * * ************************************************************************/ typedef struct _xmlSchemaSplitSAXData xmlSchemaSplitSAXData; typedef xmlSchemaSplitSAXData *xmlSchemaSplitSAXDataPtr; struct _xmlSchemaSplitSAXData { xmlSAXHandlerPtr user_sax; void *user_data; xmlSchemaValidCtxtPtr ctxt; xmlSAXHandlerPtr schemas_sax; }; #define XML_SAX_PLUG_MAGIC 0xdc43ba21 struct _xmlSchemaSAXPlug { unsigned int magic; /* the original callbacks information */ xmlSAXHandlerPtr *user_sax_ptr; xmlSAXHandlerPtr user_sax; void **user_data_ptr; void *user_data; /* the block plugged back and validation information */ xmlSAXHandler schemas_sax; xmlSchemaValidCtxtPtr ctxt; }; /* All those functions just bounces to the user provided SAX handlers */ static void internalSubsetSplit(void *ctx, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if ((ctxt != NULL) && (ctxt->user_sax != NULL) && (ctxt->user_sax->internalSubset != NULL)) ctxt->user_sax->internalSubset(ctxt->user_data, name, ExternalID, SystemID); } static int isStandaloneSplit(void *ctx) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if ((ctxt != NULL) && (ctxt->user_sax != NULL) && (ctxt->user_sax->isStandalone != NULL)) return(ctxt->user_sax->isStandalone(ctxt->user_data)); return(0); } static int hasInternalSubsetSplit(void *ctx) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if ((ctxt != NULL) && (ctxt->user_sax != NULL) && (ctxt->user_sax->hasInternalSubset != NULL)) return(ctxt->user_sax->hasInternalSubset(ctxt->user_data)); return(0); } static int hasExternalSubsetSplit(void *ctx) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if ((ctxt != NULL) && (ctxt->user_sax != NULL) && (ctxt->user_sax->hasExternalSubset != NULL)) return(ctxt->user_sax->hasExternalSubset(ctxt->user_data)); return(0); } static void externalSubsetSplit(void *ctx, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if ((ctxt != NULL) && (ctxt->user_sax != NULL) && (ctxt->user_sax->externalSubset != NULL)) ctxt->user_sax->externalSubset(ctxt->user_data, name, ExternalID, SystemID); } static xmlParserInputPtr resolveEntitySplit(void *ctx, const xmlChar *publicId, const xmlChar *systemId) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if ((ctxt != NULL) && (ctxt->user_sax != NULL) && (ctxt->user_sax->resolveEntity != NULL)) return(ctxt->user_sax->resolveEntity(ctxt->user_data, publicId, systemId)); return(NULL); } static xmlEntityPtr getEntitySplit(void *ctx, const xmlChar *name) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if ((ctxt != NULL) && (ctxt->user_sax != NULL) && (ctxt->user_sax->getEntity != NULL)) return(ctxt->user_sax->getEntity(ctxt->user_data, name)); return(NULL); } static xmlEntityPtr getParameterEntitySplit(void *ctx, const xmlChar *name) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if ((ctxt != NULL) && (ctxt->user_sax != NULL) && (ctxt->user_sax->getParameterEntity != NULL)) return(ctxt->user_sax->getParameterEntity(ctxt->user_data, name)); return(NULL); } static void entityDeclSplit(void *ctx, const xmlChar *name, int type, const xmlChar *publicId, const xmlChar *systemId, xmlChar *content) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if ((ctxt != NULL) && (ctxt->user_sax != NULL) && (ctxt->user_sax->entityDecl != NULL)) ctxt->user_sax->entityDecl(ctxt->user_data, name, type, publicId, systemId, content); } static void attributeDeclSplit(void *ctx, const xmlChar * elem, const xmlChar * name, int type, int def, const xmlChar * defaultValue, xmlEnumerationPtr tree) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if ((ctxt != NULL) && (ctxt->user_sax != NULL) && (ctxt->user_sax->attributeDecl != NULL)) { ctxt->user_sax->attributeDecl(ctxt->user_data, elem, name, type, def, defaultValue, tree); } else { xmlFreeEnumeration(tree); } } static void elementDeclSplit(void *ctx, const xmlChar *name, int type, xmlElementContentPtr content) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if ((ctxt != NULL) && (ctxt->user_sax != NULL) && (ctxt->user_sax->elementDecl != NULL)) ctxt->user_sax->elementDecl(ctxt->user_data, name, type, content); } static void notationDeclSplit(void *ctx, const xmlChar *name, const xmlChar *publicId, const xmlChar *systemId) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if ((ctxt != NULL) && (ctxt->user_sax != NULL) && (ctxt->user_sax->notationDecl != NULL)) ctxt->user_sax->notationDecl(ctxt->user_data, name, publicId, systemId); } static void unparsedEntityDeclSplit(void *ctx, const xmlChar *name, const xmlChar *publicId, const xmlChar *systemId, const xmlChar *notationName) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if ((ctxt != NULL) && (ctxt->user_sax != NULL) && (ctxt->user_sax->unparsedEntityDecl != NULL)) ctxt->user_sax->unparsedEntityDecl(ctxt->user_data, name, publicId, systemId, notationName); } static void setDocumentLocatorSplit(void *ctx, xmlSAXLocatorPtr loc) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if ((ctxt != NULL) && (ctxt->user_sax != NULL) && (ctxt->user_sax->setDocumentLocator != NULL)) ctxt->user_sax->setDocumentLocator(ctxt->user_data, loc); } static void startDocumentSplit(void *ctx) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if ((ctxt != NULL) && (ctxt->user_sax != NULL) && (ctxt->user_sax->startDocument != NULL)) ctxt->user_sax->startDocument(ctxt->user_data); } static void endDocumentSplit(void *ctx) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if ((ctxt != NULL) && (ctxt->user_sax != NULL) && (ctxt->user_sax->endDocument != NULL)) ctxt->user_sax->endDocument(ctxt->user_data); } static void processingInstructionSplit(void *ctx, const xmlChar *target, const xmlChar *data) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if ((ctxt != NULL) && (ctxt->user_sax != NULL) && (ctxt->user_sax->processingInstruction != NULL)) ctxt->user_sax->processingInstruction(ctxt->user_data, target, data); } static void commentSplit(void *ctx, const xmlChar *value) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if ((ctxt != NULL) && (ctxt->user_sax != NULL) && (ctxt->user_sax->comment != NULL)) ctxt->user_sax->comment(ctxt->user_data, value); } /* * Varargs error callbacks to the user application, harder ... */ static void XMLCDECL warningSplit(void *ctx, const char *msg ATTRIBUTE_UNUSED, ...) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if ((ctxt != NULL) && (ctxt->user_sax != NULL) && (ctxt->user_sax->warning != NULL)) { TODO } } static void XMLCDECL errorSplit(void *ctx, const char *msg ATTRIBUTE_UNUSED, ...) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if ((ctxt != NULL) && (ctxt->user_sax != NULL) && (ctxt->user_sax->error != NULL)) { TODO } } static void XMLCDECL fatalErrorSplit(void *ctx, const char *msg ATTRIBUTE_UNUSED, ...) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if ((ctxt != NULL) && (ctxt->user_sax != NULL) && (ctxt->user_sax->fatalError != NULL)) { TODO } } /* * Those are function where both the user handler and the schemas handler * need to be called. */ static void charactersSplit(void *ctx, const xmlChar *ch, int len) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if (ctxt == NULL) return; if ((ctxt->user_sax != NULL) && (ctxt->user_sax->characters != NULL)) ctxt->user_sax->characters(ctxt->user_data, ch, len); if (ctxt->ctxt != NULL) xmlSchemaSAXHandleText(ctxt->ctxt, ch, len); } static void ignorableWhitespaceSplit(void *ctx, const xmlChar *ch, int len) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if (ctxt == NULL) return; if ((ctxt->user_sax != NULL) && (ctxt->user_sax->ignorableWhitespace != NULL)) ctxt->user_sax->ignorableWhitespace(ctxt->user_data, ch, len); if (ctxt->ctxt != NULL) xmlSchemaSAXHandleText(ctxt->ctxt, ch, len); } static void cdataBlockSplit(void *ctx, const xmlChar *value, int len) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if (ctxt == NULL) return; if ((ctxt->user_sax != NULL) && (ctxt->user_sax->cdataBlock != NULL)) ctxt->user_sax->cdataBlock(ctxt->user_data, value, len); if (ctxt->ctxt != NULL) xmlSchemaSAXHandleCDataSection(ctxt->ctxt, value, len); } static void referenceSplit(void *ctx, const xmlChar *name) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if (ctxt == NULL) return; if ((ctxt != NULL) && (ctxt->user_sax != NULL) && (ctxt->user_sax->reference != NULL)) ctxt->user_sax->reference(ctxt->user_data, name); if (ctxt->ctxt != NULL) xmlSchemaSAXHandleReference(ctxt->user_data, name); } static void startElementNsSplit(void *ctx, const xmlChar * localname, const xmlChar * prefix, const xmlChar * URI, int nb_namespaces, const xmlChar ** namespaces, int nb_attributes, int nb_defaulted, const xmlChar ** attributes) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if (ctxt == NULL) return; if ((ctxt->user_sax != NULL) && (ctxt->user_sax->startElementNs != NULL)) ctxt->user_sax->startElementNs(ctxt->user_data, localname, prefix, URI, nb_namespaces, namespaces, nb_attributes, nb_defaulted, attributes); if (ctxt->ctxt != NULL) xmlSchemaSAXHandleStartElementNs(ctxt->ctxt, localname, prefix, URI, nb_namespaces, namespaces, nb_attributes, nb_defaulted, attributes); } static void endElementNsSplit(void *ctx, const xmlChar * localname, const xmlChar * prefix, const xmlChar * URI) { xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx; if (ctxt == NULL) return; if ((ctxt->user_sax != NULL) && (ctxt->user_sax->endElementNs != NULL)) ctxt->user_sax->endElementNs(ctxt->user_data, localname, prefix, URI); if (ctxt->ctxt != NULL) xmlSchemaSAXHandleEndElementNs(ctxt->ctxt, localname, prefix, URI); } /** * xmlSchemaSAXPlug: * @ctxt: a schema validation context * @sax: a pointer to the original xmlSAXHandlerPtr * @user_data: a pointer to the original SAX user data pointer * * Plug a SAX based validation layer in a SAX parsing event flow. * The original @saxptr and @dataptr data are replaced by new pointers * but the calls to the original will be maintained. * * Returns a pointer to a data structure needed to unplug the validation layer * or NULL in case of errors. */ xmlSchemaSAXPlugPtr xmlSchemaSAXPlug(xmlSchemaValidCtxtPtr ctxt, xmlSAXHandlerPtr *sax, void **user_data) { xmlSchemaSAXPlugPtr ret; xmlSAXHandlerPtr old_sax; if ((ctxt == NULL) || (sax == NULL) || (user_data == NULL)) return(NULL); /* * We only allow to plug into SAX2 event streams */ old_sax = *sax; if ((old_sax != NULL) && (old_sax->initialized != XML_SAX2_MAGIC)) return(NULL); if ((old_sax != NULL) && (old_sax->startElementNs == NULL) && (old_sax->endElementNs == NULL) && ((old_sax->startElement != NULL) || (old_sax->endElement != NULL))) return(NULL); /* * everything seems right allocate the local data needed for that layer */ ret = (xmlSchemaSAXPlugPtr) xmlMalloc(sizeof(xmlSchemaSAXPlugStruct)); if (ret == NULL) { return(NULL); } memset(ret, 0, sizeof(xmlSchemaSAXPlugStruct)); ret->magic = XML_SAX_PLUG_MAGIC; ret->schemas_sax.initialized = XML_SAX2_MAGIC; ret->ctxt = ctxt; ret->user_sax_ptr = sax; ret->user_sax = old_sax; if (old_sax == NULL) { /* * go direct, no need for the split block and functions. */ ret->schemas_sax.startElementNs = xmlSchemaSAXHandleStartElementNs; ret->schemas_sax.endElementNs = xmlSchemaSAXHandleEndElementNs; /* * Note that we use the same text-function for both, to prevent * the parser from testing for ignorable whitespace. */ ret->schemas_sax.ignorableWhitespace = xmlSchemaSAXHandleText; ret->schemas_sax.characters = xmlSchemaSAXHandleText; ret->schemas_sax.cdataBlock = xmlSchemaSAXHandleCDataSection; ret->schemas_sax.reference = xmlSchemaSAXHandleReference; ret->user_data = ctxt; *user_data = ctxt; } else { /* * for each callback unused by Schemas initialize it to the Split * routine only if non NULL in the user block, this can speed up * things at the SAX level. */ if (old_sax->internalSubset != NULL) ret->schemas_sax.internalSubset = internalSubsetSplit; if (old_sax->isStandalone != NULL) ret->schemas_sax.isStandalone = isStandaloneSplit; if (old_sax->hasInternalSubset != NULL) ret->schemas_sax.hasInternalSubset = hasInternalSubsetSplit; if (old_sax->hasExternalSubset != NULL) ret->schemas_sax.hasExternalSubset = hasExternalSubsetSplit; if (old_sax->resolveEntity != NULL) ret->schemas_sax.resolveEntity = resolveEntitySplit; if (old_sax->getEntity != NULL) ret->schemas_sax.getEntity = getEntitySplit; if (old_sax->entityDecl != NULL) ret->schemas_sax.entityDecl = entityDeclSplit; if (old_sax->notationDecl != NULL) ret->schemas_sax.notationDecl = notationDeclSplit; if (old_sax->attributeDecl != NULL) ret->schemas_sax.attributeDecl = attributeDeclSplit; if (old_sax->elementDecl != NULL) ret->schemas_sax.elementDecl = elementDeclSplit; if (old_sax->unparsedEntityDecl != NULL) ret->schemas_sax.unparsedEntityDecl = unparsedEntityDeclSplit; if (old_sax->setDocumentLocator != NULL) ret->schemas_sax.setDocumentLocator = setDocumentLocatorSplit; if (old_sax->startDocument != NULL) ret->schemas_sax.startDocument = startDocumentSplit; if (old_sax->endDocument != NULL) ret->schemas_sax.endDocument = endDocumentSplit; if (old_sax->processingInstruction != NULL) ret->schemas_sax.processingInstruction = processingInstructionSplit; if (old_sax->comment != NULL) ret->schemas_sax.comment = commentSplit; if (old_sax->warning != NULL) ret->schemas_sax.warning = warningSplit; if (old_sax->error != NULL) ret->schemas_sax.error = errorSplit; if (old_sax->fatalError != NULL) ret->schemas_sax.fatalError = fatalErrorSplit; if (old_sax->getParameterEntity != NULL) ret->schemas_sax.getParameterEntity = getParameterEntitySplit; if (old_sax->externalSubset != NULL) ret->schemas_sax.externalSubset = externalSubsetSplit; /* * the 6 schemas callback have to go to the splitter functions * Note that we use the same text-function for ignorableWhitespace * if possible, to prevent the parser from testing for ignorable * whitespace. */ ret->schemas_sax.characters = charactersSplit; if ((old_sax->ignorableWhitespace != NULL) && (old_sax->ignorableWhitespace != old_sax->characters)) ret->schemas_sax.ignorableWhitespace = ignorableWhitespaceSplit; else ret->schemas_sax.ignorableWhitespace = charactersSplit; ret->schemas_sax.cdataBlock = cdataBlockSplit; ret->schemas_sax.reference = referenceSplit; ret->schemas_sax.startElementNs = startElementNsSplit; ret->schemas_sax.endElementNs = endElementNsSplit; ret->user_data_ptr = user_data; ret->user_data = *user_data; *user_data = ret; } /* * plug the pointers back. */ *sax = &(ret->schemas_sax); ctxt->sax = *sax; ctxt->flags |= XML_SCHEMA_VALID_CTXT_FLAG_STREAM; xmlSchemaPreRun(ctxt); return(ret); } /** * xmlSchemaSAXUnplug: * @plug: a data structure returned by xmlSchemaSAXPlug * * Unplug a SAX based validation layer in a SAX parsing event flow. * The original pointers used in the call are restored. * * Returns 0 in case of success and -1 in case of failure. */ int xmlSchemaSAXUnplug(xmlSchemaSAXPlugPtr plug) { xmlSAXHandlerPtr *sax; void **user_data; if ((plug == NULL) || (plug->magic != XML_SAX_PLUG_MAGIC)) return(-1); plug->magic = 0; xmlSchemaPostRun(plug->ctxt); /* restore the data */ sax = plug->user_sax_ptr; *sax = plug->user_sax; if (plug->user_sax != NULL) { user_data = plug->user_data_ptr; *user_data = plug->user_data; } /* free and return */ xmlFree(plug); return(0); } /** * xmlSchemaValidateSetLocator: * @vctxt: a schema validation context * @f: the locator function pointer * @ctxt: the locator context * * Allows to set a locator function to the validation context, * which will be used to provide file and line information since * those are not provided as part of the SAX validation flow * Setting @f to NULL disable the locator. */ void xmlSchemaValidateSetLocator(xmlSchemaValidCtxtPtr vctxt, xmlSchemaValidityLocatorFunc f, void *ctxt) { if (vctxt == NULL) return; vctxt->locFunc = f; vctxt->locCtxt = ctxt; } /** * xmlSchemaValidateStreamLocator: * @ctx: the xmlTextReaderPtr used * @file: returned file information * @line: returned line information * * Internal locator function for the readers * * Returns 0 in case the Schema validation could be (de)activated and * -1 in case of error. */ static int xmlSchemaValidateStreamLocator(void *ctx, const char **file, unsigned long *line) { xmlParserCtxtPtr ctxt; if ((ctx == NULL) || ((file == NULL) && (line == NULL))) return(-1); if (file != NULL) *file = NULL; if (line != NULL) *line = 0; ctxt = (xmlParserCtxtPtr) ctx; if (ctxt->input != NULL) { if (file != NULL) *file = ctxt->input->filename; if (line != NULL) *line = ctxt->input->line; return(0); } return(-1); } /** * xmlSchemaValidateStream: * @ctxt: a schema validation context * @input: the input to use for reading the data * @enc: an optional encoding information * @sax: a SAX handler for the resulting events * @user_data: the context to provide to the SAX handler. * * Validate an input based on a flow of SAX event from the parser * and forward the events to the @sax handler with the provided @user_data * the user provided @sax handler must be a SAX2 one. * * Returns 0 if the document is schemas valid, a positive error code * number otherwise and -1 in case of internal or API error. */ int xmlSchemaValidateStream(xmlSchemaValidCtxtPtr ctxt, xmlParserInputBufferPtr input, xmlCharEncoding enc, xmlSAXHandlerPtr sax, void *user_data) { xmlSchemaSAXPlugPtr plug = NULL; xmlSAXHandlerPtr old_sax = NULL; xmlParserCtxtPtr pctxt = NULL; xmlParserInputPtr inputStream = NULL; int ret; if ((ctxt == NULL) || (input == NULL)) return (-1); /* * prepare the parser */ pctxt = xmlNewParserCtxt(); if (pctxt == NULL) return (-1); old_sax = pctxt->sax; pctxt->sax = sax; pctxt->userData = user_data; #if 0 if (options) xmlCtxtUseOptions(pctxt, options); #endif pctxt->linenumbers = 1; xmlSchemaValidateSetLocator(ctxt, xmlSchemaValidateStreamLocator, pctxt); inputStream = xmlNewIOInputStream(pctxt, input, enc);; if (inputStream == NULL) { ret = -1; goto done; } inputPush(pctxt, inputStream); ctxt->parserCtxt = pctxt; ctxt->input = input; /* * Plug the validation and launch the parsing */ plug = xmlSchemaSAXPlug(ctxt, &(pctxt->sax), &(pctxt->userData)); if (plug == NULL) { ret = -1; goto done; } ctxt->input = input; ctxt->enc = enc; ctxt->sax = pctxt->sax; ctxt->flags |= XML_SCHEMA_VALID_CTXT_FLAG_STREAM; ret = xmlSchemaVStart(ctxt); if ((ret == 0) && (! ctxt->parserCtxt->wellFormed)) { ret = ctxt->parserCtxt->errNo; if (ret == 0) ret = 1; } done: ctxt->parserCtxt = NULL; ctxt->sax = NULL; ctxt->input = NULL; if (plug != NULL) { xmlSchemaSAXUnplug(plug); } /* cleanup */ if (pctxt != NULL) { pctxt->sax = old_sax; xmlFreeParserCtxt(pctxt); } return (ret); } /** * xmlSchemaValidateFile: * @ctxt: a schema validation context * @filename: the URI of the instance * @options: a future set of options, currently unused * * Do a schemas validation of the given resource, it will use the * SAX streamable validation internally. * * Returns 0 if the document is valid, a positive error code * number otherwise and -1 in case of an internal or API error. */ int xmlSchemaValidateFile(xmlSchemaValidCtxtPtr ctxt, const char * filename, int options ATTRIBUTE_UNUSED) { int ret; xmlParserInputBufferPtr input; if ((ctxt == NULL) || (filename == NULL)) return (-1); input = xmlParserInputBufferCreateFilename(filename, XML_CHAR_ENCODING_NONE); if (input == NULL) return (-1); ret = xmlSchemaValidateStream(ctxt, input, XML_CHAR_ENCODING_NONE, NULL, NULL); return (ret); } /** * xmlSchemaValidCtxtGetParserCtxt: * @ctxt: a schema validation context * * allow access to the parser context of the schema validation context * * Returns the parser context of the schema validation context or NULL * in case of error. */ xmlParserCtxtPtr xmlSchemaValidCtxtGetParserCtxt(xmlSchemaValidCtxtPtr ctxt) { if (ctxt == NULL) return(NULL); return (ctxt->parserCtxt); } #define bottom_xmlschemas #include "elfgcchack.h" #endif /* LIBXML_SCHEMAS_ENABLED */
29.516076
113
0.626394
[ "object", "model" ]
b1032cc7b8e9d054cf9c63c5ef1730cdfd3a1bb6
1,714
h
C
src/kernel/include/vmm.h
EIRNf/twizzler
794383026ce605789c6cfc62093d79f0b01fe1d5
[ "BSD-3-Clause" ]
23
2021-07-09T22:11:58.000Z
2022-03-24T04:19:44.000Z
src/kernel/include/vmm.h
EIRNf/twizzler
794383026ce605789c6cfc62093d79f0b01fe1d5
[ "BSD-3-Clause" ]
38
2021-07-10T02:50:30.000Z
2022-03-16T01:22:46.000Z
src/kernel/include/vmm.h
EIRNf/twizzler
794383026ce605789c6cfc62093d79f0b01fe1d5
[ "BSD-3-Clause" ]
6
2021-07-03T04:15:06.000Z
2022-03-15T00:33:32.000Z
#pragma once #include <__mm_bits.h> #include <krc.h> #include <lib/list.h> #include <lib/rb.h> #include <twz/sys/view.h> struct object; struct omap; struct vm_context { struct arch_vm_context arch; struct object *viewobj; struct rbroot root; struct spinlock lock; struct list entry; }; void arch_mm_switch_context(struct vm_context *vm); void arch_vm_context_init(struct vm_context *ctx); void arch_vm_context_dtor(struct vm_context *ctx); void arch_mm_context_destroy(struct vm_context *ctx); void vm_context_destroy(struct vm_context *v); struct vm_context *vm_context_create(void); void vm_context_free(struct vm_context *ctx); void arch_mm_print_ctx(struct vm_context *ctx); void arch_mm_virtual_invalidate(struct vm_context *ctx, uintptr_t virt, size_t len); extern struct vm_context kernel_ctx; struct vmap { struct omap *omap; struct object *obj; size_t slot; uint32_t flags; struct rbnode node; }; void kso_view_write(struct object *obj, size_t slot, struct viewentry *v); bool vm_setview(struct thread *, struct object *viewobj); struct object *vm_vaddr_lookup_obj(void *addr, uint64_t *off); void vm_context_fault(uintptr_t ip, uintptr_t addr, int flags); struct object *vm_context_lookup_object(struct vm_context *ctx, uintptr_t virt); #define FAULT_EXEC 0x1 #define FAULT_WRITE 0x2 #define FAULT_USER 0x4 #define FAULT_ERROR_PERM 0x10 #define FAULT_ERROR_PRES 0x20 void kernel_fault_entry(uintptr_t ip, uintptr_t addr, int flags); void arch_mm_unmap(struct vm_context *ctx, uintptr_t virt, size_t len); void mm_map(uintptr_t addr, uintptr_t oaddr, size_t len, int flags); int arch_mm_map(struct vm_context *ctx, uintptr_t virt, uintptr_t phys, size_t len, uint64_t mapflags);
29.050847
84
0.793466
[ "object" ]
b1052990812a54360324200d22a31897c547055a
65,036
c
C
av1/encoder/encodeframe.c
liuyanmin120/aom
75a47cc1865d9fb2a7c56389fa772bcbb0e62eeb
[ "BSD-2-Clause" ]
null
null
null
av1/encoder/encodeframe.c
liuyanmin120/aom
75a47cc1865d9fb2a7c56389fa772bcbb0e62eeb
[ "BSD-2-Clause" ]
null
null
null
av1/encoder/encodeframe.c
liuyanmin120/aom
75a47cc1865d9fb2a7c56389fa772bcbb0e62eeb
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2016, Alliance for Open Media. All rights reserved * * This source code is subject to the terms of the BSD 2 Clause License and * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License * was not distributed with this source code in the LICENSE file, you can * obtain it at www.aomedia.org/license/software. If the Alliance for Open * Media Patent License 1.0 was not distributed with this source code in the * PATENTS file, you can obtain it at www.aomedia.org/license/patent. */ #include <limits.h> #include <float.h> #include <math.h> #include <stdbool.h> #include <stdio.h> #include "config/aom_config.h" #include "config/aom_dsp_rtcd.h" #include "config/av1_rtcd.h" #include "aom_dsp/aom_dsp_common.h" #include "aom_dsp/binary_codes_writer.h" #include "aom_ports/mem.h" #include "aom_ports/aom_timer.h" #include "aom_ports/system_state.h" #if CONFIG_MISMATCH_DEBUG #include "aom_util/debug_util.h" #endif // CONFIG_MISMATCH_DEBUG #include "av1/common/cfl.h" #include "av1/common/common.h" #include "av1/common/entropy.h" #include "av1/common/entropymode.h" #include "av1/common/idct.h" #include "av1/common/mv.h" #include "av1/common/mvref_common.h" #include "av1/common/pred_common.h" #include "av1/common/quant_common.h" #include "av1/common/reconintra.h" #include "av1/common/reconinter.h" #include "av1/common/seg_common.h" #include "av1/common/tile_common.h" #include "av1/common/warped_motion.h" #include "av1/encoder/aq_complexity.h" #include "av1/encoder/aq_cyclicrefresh.h" #include "av1/encoder/aq_variance.h" #include "av1/encoder/global_motion_facade.h" #include "av1/encoder/encodeframe.h" #include "av1/encoder/encodeframe_utils.h" #include "av1/encoder/encodemb.h" #include "av1/encoder/encodemv.h" #include "av1/encoder/encodetxb.h" #include "av1/encoder/ethread.h" #include "av1/encoder/extend.h" #include "av1/encoder/ml.h" #include "av1/encoder/motion_search_facade.h" #include "av1/encoder/partition_strategy.h" #if !CONFIG_REALTIME_ONLY #include "av1/encoder/partition_model_weights.h" #endif #include "av1/encoder/partition_search.h" #include "av1/encoder/rd.h" #include "av1/encoder/rdopt.h" #include "av1/encoder/reconinter_enc.h" #include "av1/encoder/segmentation.h" #include "av1/encoder/tokenize.h" #include "av1/encoder/tpl_model.h" #include "av1/encoder/var_based_part.h" #if CONFIG_TUNE_VMAF #include "av1/encoder/tune_vmaf.h" #endif /*!\cond */ // This is used as a reference when computing the source variance for the // purposes of activity masking. // Eventually this should be replaced by custom no-reference routines, // which will be faster. const uint8_t AV1_VAR_OFFS[MAX_SB_SIZE] = { 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 }; static const uint16_t AV1_HIGH_VAR_OFFS_8[MAX_SB_SIZE] = { 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 }; static const uint16_t AV1_HIGH_VAR_OFFS_10[MAX_SB_SIZE] = { 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4, 128 * 4 }; static const uint16_t AV1_HIGH_VAR_OFFS_12[MAX_SB_SIZE] = { 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16, 128 * 16 }; /*!\endcond */ unsigned int av1_get_sby_perpixel_variance(const AV1_COMP *cpi, const struct buf_2d *ref, BLOCK_SIZE bs) { unsigned int sse; const unsigned int var = cpi->fn_ptr[bs].vf(ref->buf, ref->stride, AV1_VAR_OFFS, 0, &sse); return ROUND_POWER_OF_TWO(var, num_pels_log2_lookup[bs]); } unsigned int av1_high_get_sby_perpixel_variance(const AV1_COMP *cpi, const struct buf_2d *ref, BLOCK_SIZE bs, int bd) { unsigned int var, sse; assert(bd == 8 || bd == 10 || bd == 12); const int off_index = (bd - 8) >> 1; const uint16_t *high_var_offs[3] = { AV1_HIGH_VAR_OFFS_8, AV1_HIGH_VAR_OFFS_10, AV1_HIGH_VAR_OFFS_12 }; var = cpi->fn_ptr[bs].vf(ref->buf, ref->stride, CONVERT_TO_BYTEPTR(high_var_offs[off_index]), 0, &sse); return ROUND_POWER_OF_TWO(var, num_pels_log2_lookup[bs]); } static unsigned int get_sby_perpixel_diff_variance(const AV1_COMP *const cpi, const struct buf_2d *ref, int mi_row, int mi_col, BLOCK_SIZE bs) { unsigned int sse, var; uint8_t *last_y; const YV12_BUFFER_CONFIG *last = get_ref_frame_yv12_buf(&cpi->common, LAST_FRAME); assert(last != NULL); last_y = &last->y_buffer[mi_row * MI_SIZE * last->y_stride + mi_col * MI_SIZE]; var = cpi->fn_ptr[bs].vf(ref->buf, ref->stride, last_y, last->y_stride, &sse); return ROUND_POWER_OF_TWO(var, num_pels_log2_lookup[bs]); } static BLOCK_SIZE get_rd_var_based_fixed_partition(AV1_COMP *cpi, MACROBLOCK *x, int mi_row, int mi_col) { unsigned int var = get_sby_perpixel_diff_variance( cpi, &x->plane[0].src, mi_row, mi_col, BLOCK_64X64); if (var < 8) return BLOCK_64X64; else if (var < 128) return BLOCK_32X32; else if (var < 2048) return BLOCK_16X16; else return BLOCK_8X8; } void av1_setup_src_planes(MACROBLOCK *x, const YV12_BUFFER_CONFIG *src, int mi_row, int mi_col, const int num_planes, BLOCK_SIZE bsize) { // Set current frame pointer. x->e_mbd.cur_buf = src; // We use AOMMIN(num_planes, MAX_MB_PLANE) instead of num_planes to quiet // the static analysis warnings. for (int i = 0; i < AOMMIN(num_planes, MAX_MB_PLANE); i++) { const int is_uv = i > 0; setup_pred_plane( &x->plane[i].src, bsize, src->buffers[i], src->crop_widths[is_uv], src->crop_heights[is_uv], src->strides[is_uv], mi_row, mi_col, NULL, x->e_mbd.plane[i].subsampling_x, x->e_mbd.plane[i].subsampling_y); } } #if !CONFIG_REALTIME_ONLY /*!\brief Assigns different quantization parameters to each super * block based on its TPL weight. * * \ingroup tpl_modelling * * \param[in] cpi Top level encoder instance structure * \param[in,out] td Thread data structure * \param[in,out] x Macro block level data for this block. * \param[in] tile_info Tile infromation / identification * \param[in] mi_row Block row (in "MI_SIZE" units) index * \param[in] mi_col Block column (in "MI_SIZE" units) index * \param[out] num_planes Number of image planes (e.g. Y,U,V) * * \return No return value but updates macroblock and thread data * related to the q / q delta to be used. */ static AOM_INLINE void setup_delta_q(AV1_COMP *const cpi, ThreadData *td, MACROBLOCK *const x, const TileInfo *const tile_info, int mi_row, int mi_col, int num_planes) { AV1_COMMON *const cm = &cpi->common; const CommonModeInfoParams *const mi_params = &cm->mi_params; const DeltaQInfo *const delta_q_info = &cm->delta_q_info; assert(delta_q_info->delta_q_present_flag); const BLOCK_SIZE sb_size = cm->seq_params.sb_size; // Delta-q modulation based on variance av1_setup_src_planes(x, cpi->source, mi_row, mi_col, num_planes, sb_size); int current_qindex = cm->quant_params.base_qindex; if (cpi->oxcf.q_cfg.deltaq_mode == DELTA_Q_PERCEPTUAL) { if (DELTA_Q_PERCEPTUAL_MODULATION == 1) { const int block_wavelet_energy_level = av1_block_wavelet_energy_level(cpi, x, sb_size); x->sb_energy_level = block_wavelet_energy_level; current_qindex = av1_compute_q_from_energy_level_deltaq_mode( cpi, block_wavelet_energy_level); } else { const int block_var_level = av1_log_block_var(cpi, x, sb_size); x->sb_energy_level = block_var_level; current_qindex = av1_compute_q_from_energy_level_deltaq_mode(cpi, block_var_level); } } else if (cpi->oxcf.q_cfg.deltaq_mode == DELTA_Q_OBJECTIVE && cpi->oxcf.algo_cfg.enable_tpl_model) { // Setup deltaq based on tpl stats current_qindex = av1_get_q_for_deltaq_objective(cpi, sb_size, mi_row, mi_col); } const int delta_q_res = delta_q_info->delta_q_res; // Right now deltaq only works with tpl model. So if tpl is disabled, we set // the current_qindex to base_qindex. if (cpi->oxcf.algo_cfg.enable_tpl_model && cpi->oxcf.q_cfg.deltaq_mode != NO_DELTA_Q) { current_qindex = clamp(current_qindex, delta_q_res, 256 - delta_q_info->delta_q_res); } else { current_qindex = cm->quant_params.base_qindex; } MACROBLOCKD *const xd = &x->e_mbd; const int sign_deltaq_index = current_qindex - xd->current_base_qindex >= 0 ? 1 : -1; const int deltaq_deadzone = delta_q_res / 4; const int qmask = ~(delta_q_res - 1); int abs_deltaq_index = abs(current_qindex - xd->current_base_qindex); abs_deltaq_index = (abs_deltaq_index + deltaq_deadzone) & qmask; current_qindex = xd->current_base_qindex + sign_deltaq_index * abs_deltaq_index; current_qindex = AOMMAX(current_qindex, MINQ + 1); assert(current_qindex > 0); x->delta_qindex = current_qindex - cm->quant_params.base_qindex; av1_set_offsets(cpi, tile_info, x, mi_row, mi_col, sb_size); xd->mi[0]->current_qindex = current_qindex; av1_init_plane_quantizers(cpi, x, xd->mi[0]->segment_id); // keep track of any non-zero delta-q used td->deltaq_used |= (x->delta_qindex != 0); if (cpi->oxcf.tool_cfg.enable_deltalf_mode) { const int delta_lf_res = delta_q_info->delta_lf_res; const int lfmask = ~(delta_lf_res - 1); const int delta_lf_from_base = ((x->delta_qindex / 2 + delta_lf_res / 2) & lfmask); const int8_t delta_lf = (int8_t)clamp(delta_lf_from_base, -MAX_LOOP_FILTER, MAX_LOOP_FILTER); const int frame_lf_count = av1_num_planes(cm) > 1 ? FRAME_LF_COUNT : FRAME_LF_COUNT - 2; const int mib_size = cm->seq_params.mib_size; // pre-set the delta lf for loop filter. Note that this value is set // before mi is assigned for each block in current superblock for (int j = 0; j < AOMMIN(mib_size, mi_params->mi_rows - mi_row); j++) { for (int k = 0; k < AOMMIN(mib_size, mi_params->mi_cols - mi_col); k++) { const int grid_idx = get_mi_grid_idx(mi_params, mi_row + j, mi_col + k); mi_params->mi_grid_base[grid_idx]->delta_lf_from_base = delta_lf; for (int lf_id = 0; lf_id < frame_lf_count; ++lf_id) { mi_params->mi_grid_base[grid_idx]->delta_lf[lf_id] = delta_lf; } } } } } static void init_ref_frame_space(AV1_COMP *cpi, ThreadData *td, int mi_row, int mi_col) { const AV1_COMMON *cm = &cpi->common; const GF_GROUP *const gf_group = &cpi->gf_group; const CommonModeInfoParams *const mi_params = &cm->mi_params; MACROBLOCK *x = &td->mb; const int frame_idx = cpi->gf_group.index; TplParams *const tpl_data = &cpi->tpl_data; TplDepFrame *tpl_frame = &tpl_data->tpl_frame[frame_idx]; const uint8_t block_mis_log2 = tpl_data->tpl_stats_block_mis_log2; av1_zero(x->tpl_keep_ref_frame); if (tpl_frame->is_valid == 0) return; if (!is_frame_tpl_eligible(gf_group, gf_group->index)) return; if (frame_idx >= MAX_TPL_FRAME_IDX) return; if (cpi->superres_mode != AOM_SUPERRES_NONE) return; if (cpi->oxcf.q_cfg.aq_mode != NO_AQ) return; const int is_overlay = cpi->gf_group.update_type[frame_idx] == OVERLAY_UPDATE; if (is_overlay) { memset(x->tpl_keep_ref_frame, 1, sizeof(x->tpl_keep_ref_frame)); return; } TplDepStats *tpl_stats = tpl_frame->tpl_stats_ptr; const int tpl_stride = tpl_frame->stride; int64_t inter_cost[INTER_REFS_PER_FRAME] = { 0 }; const int step = 1 << block_mis_log2; const BLOCK_SIZE sb_size = cm->seq_params.sb_size; const int mi_row_end = AOMMIN(mi_size_high[sb_size] + mi_row, mi_params->mi_rows); const int mi_col_end = AOMMIN(mi_size_wide[sb_size] + mi_col, mi_params->mi_cols); for (int row = mi_row; row < mi_row_end; row += step) { for (int col = mi_col; col < mi_col_end; col += step) { const TplDepStats *this_stats = &tpl_stats[av1_tpl_ptr_pos(row, col, tpl_stride, block_mis_log2)]; int64_t tpl_pred_error[INTER_REFS_PER_FRAME] = { 0 }; // Find the winner ref frame idx for the current block int64_t best_inter_cost = this_stats->pred_error[0]; int best_rf_idx = 0; for (int idx = 1; idx < INTER_REFS_PER_FRAME; ++idx) { if ((this_stats->pred_error[idx] < best_inter_cost) && (this_stats->pred_error[idx] != 0)) { best_inter_cost = this_stats->pred_error[idx]; best_rf_idx = idx; } } // tpl_pred_error is the pred_error reduction of best_ref w.r.t. // LAST_FRAME. tpl_pred_error[best_rf_idx] = this_stats->pred_error[best_rf_idx] - this_stats->pred_error[LAST_FRAME - 1]; for (int rf_idx = 1; rf_idx < INTER_REFS_PER_FRAME; ++rf_idx) inter_cost[rf_idx] += tpl_pred_error[rf_idx]; } } int rank_index[INTER_REFS_PER_FRAME - 1]; for (int idx = 0; idx < INTER_REFS_PER_FRAME - 1; ++idx) { rank_index[idx] = idx + 1; for (int i = idx; i > 0; --i) { if (inter_cost[rank_index[i - 1]] > inter_cost[rank_index[i]]) { const int tmp = rank_index[i - 1]; rank_index[i - 1] = rank_index[i]; rank_index[i] = tmp; } } } x->tpl_keep_ref_frame[INTRA_FRAME] = 1; x->tpl_keep_ref_frame[LAST_FRAME] = 1; int cutoff_ref = 0; for (int idx = 0; idx < INTER_REFS_PER_FRAME - 1; ++idx) { x->tpl_keep_ref_frame[rank_index[idx] + LAST_FRAME] = 1; if (idx > 2) { if (!cutoff_ref) { // If the predictive coding gains are smaller than the previous more // relevant frame over certain amount, discard this frame and all the // frames afterwards. if (llabs(inter_cost[rank_index[idx]]) < llabs(inter_cost[rank_index[idx - 1]]) / 8 || inter_cost[rank_index[idx]] == 0) cutoff_ref = 1; } if (cutoff_ref) x->tpl_keep_ref_frame[rank_index[idx] + LAST_FRAME] = 0; } } } static AOM_INLINE void adjust_rdmult_tpl_model(AV1_COMP *cpi, MACROBLOCK *x, int mi_row, int mi_col) { const BLOCK_SIZE sb_size = cpi->common.seq_params.sb_size; const int orig_rdmult = cpi->rd.RDMULT; assert(IMPLIES(cpi->gf_group.size > 0, cpi->gf_group.index < cpi->gf_group.size)); const int gf_group_index = cpi->gf_group.index; if (cpi->oxcf.algo_cfg.enable_tpl_model && cpi->oxcf.q_cfg.aq_mode == NO_AQ && cpi->oxcf.q_cfg.deltaq_mode == NO_DELTA_Q && gf_group_index > 0 && cpi->gf_group.update_type[gf_group_index] == ARF_UPDATE) { const int dr = av1_get_rdmult_delta(cpi, sb_size, mi_row, mi_col, orig_rdmult); x->rdmult = dr; } } #endif // !CONFIG_REALTIME_ONLY // Get a prediction(stored in x->est_pred) for the whole superblock. static void get_estimated_pred(AV1_COMP *cpi, const TileInfo *const tile, MACROBLOCK *x, int mi_row, int mi_col) { AV1_COMMON *const cm = &cpi->common; const int is_key_frame = frame_is_intra_only(cm); MACROBLOCKD *xd = &x->e_mbd; // TODO(kyslov) Extend to 128x128 assert(cm->seq_params.sb_size == BLOCK_64X64); av1_set_offsets(cpi, tile, x, mi_row, mi_col, BLOCK_64X64); if (!is_key_frame) { MB_MODE_INFO *mi = xd->mi[0]; const YV12_BUFFER_CONFIG *yv12 = get_ref_frame_yv12_buf(cm, LAST_FRAME); assert(yv12 != NULL); av1_setup_pre_planes(xd, 0, yv12, mi_row, mi_col, get_ref_scale_factors(cm, LAST_FRAME), 1); mi->ref_frame[0] = LAST_FRAME; mi->ref_frame[1] = NONE; mi->bsize = BLOCK_64X64; mi->mv[0].as_int = 0; mi->interp_filters = av1_broadcast_interp_filter(BILINEAR); set_ref_ptrs(cm, xd, mi->ref_frame[0], mi->ref_frame[1]); xd->plane[0].dst.buf = x->est_pred; xd->plane[0].dst.stride = 64; av1_enc_build_inter_predictor_y(xd, mi_row, mi_col); } else { #if CONFIG_AV1_HIGHBITDEPTH switch (xd->bd) { case 8: memset(x->est_pred, 128, 64 * 64 * sizeof(x->est_pred[0])); break; case 10: memset(x->est_pred, 128 * 4, 64 * 64 * sizeof(x->est_pred[0])); break; case 12: memset(x->est_pred, 128 * 16, 64 * 64 * sizeof(x->est_pred[0])); break; } #else memset(x->est_pred, 128, 64 * 64 * sizeof(x->est_pred[0])); #endif // CONFIG_VP9_HIGHBITDEPTH } } #define AVG_CDF_WEIGHT_LEFT 3 #define AVG_CDF_WEIGHT_TOP_RIGHT 1 /*!\brief Encode a superblock (minimal RD search involved) * * \ingroup partition_search * Encodes the superblock by a pre-determined partition pattern, only minor * rd-based searches are allowed to adjust the initial pattern. It is only used * by realtime encoding. */ static AOM_INLINE void encode_nonrd_sb(AV1_COMP *cpi, ThreadData *td, TileDataEnc *tile_data, TokenExtra **tp, const int mi_row, const int mi_col, const int seg_skip) { AV1_COMMON *const cm = &cpi->common; MACROBLOCK *const x = &td->mb; const SPEED_FEATURES *const sf = &cpi->sf; const TileInfo *const tile_info = &tile_data->tile_info; MB_MODE_INFO **mi = cm->mi_params.mi_grid_base + get_mi_grid_idx(&cm->mi_params, mi_row, mi_col); const BLOCK_SIZE sb_size = cm->seq_params.sb_size; // Grade the temporal variation of the sb, the grade will be used to decide // fast mode search strategy for coding blocks if (sf->rt_sf.source_metrics_sb_nonrd && cpi->svc.number_spatial_layers <= 1 && cm->current_frame.frame_type != KEY_FRAME) { int offset = cpi->source->y_stride * (mi_row << 2) + (mi_col << 2); av1_source_content_sb(cpi, x, offset); } if (sf->part_sf.partition_search_type == ML_BASED_PARTITION) { PC_TREE *const pc_root = av1_alloc_pc_tree_node(sb_size); RD_STATS dummy_rdc; get_estimated_pred(cpi, tile_info, x, mi_row, mi_col); av1_nonrd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, BLOCK_64X64, &dummy_rdc, 1, INT64_MAX, pc_root); av1_free_pc_tree_recursive(pc_root, av1_num_planes(cm), 0, 0); return; } // Set the partition if (sf->part_sf.partition_search_type == FIXED_PARTITION || seg_skip) { // set a fixed-size partition av1_set_offsets(cpi, tile_info, x, mi_row, mi_col, sb_size); const BLOCK_SIZE bsize = seg_skip ? sb_size : sf->part_sf.fixed_partition_size; av1_set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize); } else if (cpi->partition_search_skippable_frame) { // set a fixed-size partition for which the size is determined by the source // variance av1_set_offsets(cpi, tile_info, x, mi_row, mi_col, sb_size); const BLOCK_SIZE bsize = get_rd_var_based_fixed_partition(cpi, x, mi_row, mi_col); av1_set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize); } else if (sf->part_sf.partition_search_type == VAR_BASED_PARTITION) { // set a variance-based partition av1_set_offsets_without_segment_id(cpi, tile_info, x, mi_row, mi_col, sb_size); av1_choose_var_based_partitioning(cpi, tile_info, td, x, mi_row, mi_col); } assert(sf->part_sf.partition_search_type == FIXED_PARTITION || seg_skip || cpi->partition_search_skippable_frame || sf->part_sf.partition_search_type == VAR_BASED_PARTITION); set_cb_offsets(td->mb.cb_offset, 0, 0); // Adjust and encode the superblock PC_TREE *const pc_root = av1_alloc_pc_tree_node(sb_size); av1_nonrd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, sb_size, pc_root); av1_free_pc_tree_recursive(pc_root, av1_num_planes(cm), 0, 0); } // This function initializes the stats for encode_rd_sb. static INLINE void init_encode_rd_sb(AV1_COMP *cpi, ThreadData *td, const TileDataEnc *tile_data, SIMPLE_MOTION_DATA_TREE *sms_root, RD_STATS *rd_cost, int mi_row, int mi_col, int gather_tpl_data) { const AV1_COMMON *cm = &cpi->common; const TileInfo *tile_info = &tile_data->tile_info; MACROBLOCK *x = &td->mb; const SPEED_FEATURES *sf = &cpi->sf; const int use_simple_motion_search = (sf->part_sf.simple_motion_search_split || sf->part_sf.simple_motion_search_prune_rect || sf->part_sf.simple_motion_search_early_term_none || sf->part_sf.ml_early_term_after_part_split_level) && !frame_is_intra_only(cm); if (use_simple_motion_search) { init_simple_motion_search_mvs(sms_root); } #if !CONFIG_REALTIME_ONLY if (has_no_stats_stage(cpi) && cpi->oxcf.mode == REALTIME && cpi->oxcf.gf_cfg.lag_in_frames == 0) { (void)tile_info; (void)mi_row; (void)mi_col; (void)gather_tpl_data; } else { init_ref_frame_space(cpi, td, mi_row, mi_col); x->sb_energy_level = 0; x->part_search_info.cnn_output_valid = 0; if (gather_tpl_data) { if (cm->delta_q_info.delta_q_present_flag) { const int num_planes = av1_num_planes(cm); const BLOCK_SIZE sb_size = cm->seq_params.sb_size; setup_delta_q(cpi, td, x, tile_info, mi_row, mi_col, num_planes); av1_tpl_rdmult_setup_sb(cpi, x, sb_size, mi_row, mi_col); } if (cpi->oxcf.algo_cfg.enable_tpl_model) { adjust_rdmult_tpl_model(cpi, x, mi_row, mi_col); } } } #else (void)tile_info; (void)mi_row; (void)mi_col; (void)gather_tpl_data; #endif // Reset hash state for transform/mode rd hash information reset_hash_records(&x->txfm_search_info, cpi->sf.tx_sf.use_inter_txb_hash); av1_zero(x->picked_ref_frames_mask); av1_invalid_rd_stats(rd_cost); } /*!\brief Encode a superblock (RD-search-based) * * \ingroup partition_search * Conducts partition search for a superblock, based on rate-distortion costs, * from scratch or adjusting from a pre-calculated partition pattern. */ static AOM_INLINE void encode_rd_sb(AV1_COMP *cpi, ThreadData *td, TileDataEnc *tile_data, TokenExtra **tp, const int mi_row, const int mi_col, const int seg_skip) { AV1_COMMON *const cm = &cpi->common; MACROBLOCK *const x = &td->mb; const SPEED_FEATURES *const sf = &cpi->sf; const TileInfo *const tile_info = &tile_data->tile_info; MB_MODE_INFO **mi = cm->mi_params.mi_grid_base + get_mi_grid_idx(&cm->mi_params, mi_row, mi_col); const BLOCK_SIZE sb_size = cm->seq_params.sb_size; const int num_planes = av1_num_planes(cm); int dummy_rate; int64_t dummy_dist; RD_STATS dummy_rdc; SIMPLE_MOTION_DATA_TREE *const sms_root = td->sms_root; #if CONFIG_REALTIME_ONLY (void)seg_skip; #endif // CONFIG_REALTIME_ONLY init_encode_rd_sb(cpi, td, tile_data, sms_root, &dummy_rdc, mi_row, mi_col, 1); // Encode the superblock if (sf->part_sf.partition_search_type == VAR_BASED_PARTITION) { // partition search starting from a variance-based partition av1_set_offsets_without_segment_id(cpi, tile_info, x, mi_row, mi_col, sb_size); av1_choose_var_based_partitioning(cpi, tile_info, td, x, mi_row, mi_col); PC_TREE *const pc_root = av1_alloc_pc_tree_node(sb_size); av1_rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, sb_size, &dummy_rate, &dummy_dist, 1, pc_root); av1_free_pc_tree_recursive(pc_root, num_planes, 0, 0); } #if !CONFIG_REALTIME_ONLY else if (sf->part_sf.partition_search_type == FIXED_PARTITION || seg_skip) { // partition search by adjusting a fixed-size partition av1_set_offsets(cpi, tile_info, x, mi_row, mi_col, sb_size); const BLOCK_SIZE bsize = seg_skip ? sb_size : sf->part_sf.fixed_partition_size; av1_set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize); PC_TREE *const pc_root = av1_alloc_pc_tree_node(sb_size); av1_rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, sb_size, &dummy_rate, &dummy_dist, 1, pc_root); av1_free_pc_tree_recursive(pc_root, num_planes, 0, 0); } else if (cpi->partition_search_skippable_frame) { // partition search by adjusting a fixed-size partition for which the size // is determined by the source variance av1_set_offsets(cpi, tile_info, x, mi_row, mi_col, sb_size); const BLOCK_SIZE bsize = get_rd_var_based_fixed_partition(cpi, x, mi_row, mi_col); av1_set_fixed_partitioning(cpi, tile_info, mi, mi_row, mi_col, bsize); PC_TREE *const pc_root = av1_alloc_pc_tree_node(sb_size); av1_rd_use_partition(cpi, td, tile_data, mi, tp, mi_row, mi_col, sb_size, &dummy_rate, &dummy_dist, 1, pc_root); av1_free_pc_tree_recursive(pc_root, num_planes, 0, 0); } else { // The most exhaustive recursive partition search SuperBlockEnc *sb_enc = &x->sb_enc; // No stats for overlay frames. Exclude key frame. av1_get_tpl_stats_sb(cpi, sb_size, mi_row, mi_col, sb_enc); // Reset the tree for simple motion search data av1_reset_simple_motion_tree_partition(sms_root, sb_size); #if CONFIG_COLLECT_COMPONENT_TIMING start_timing(cpi, rd_pick_partition_time); #endif // Estimate the maximum square partition block size, which will be used // as the starting block size for partitioning the sb set_max_min_partition_size(sb_enc, cpi, x, sf, sb_size, mi_row, mi_col); // The superblock can be searched only once, or twice consecutively for // better quality. Note that the meaning of passes here is different from // the general concept of 1-pass/2-pass encoders. const int num_passes = cpi->oxcf.unit_test_cfg.sb_multipass_unit_test ? 2 : 1; if (num_passes == 1) { PC_TREE *const pc_root = av1_alloc_pc_tree_node(sb_size); av1_rd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, sb_size, &dummy_rdc, dummy_rdc, pc_root, sms_root, NULL, SB_SINGLE_PASS, NULL); } else { // First pass SB_FIRST_PASS_STATS sb_fp_stats; av1_backup_sb_state(&sb_fp_stats, cpi, td, tile_data, mi_row, mi_col); PC_TREE *const pc_root_p0 = av1_alloc_pc_tree_node(sb_size); av1_rd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, sb_size, &dummy_rdc, dummy_rdc, pc_root_p0, sms_root, NULL, SB_DRY_PASS, NULL); // Second pass init_encode_rd_sb(cpi, td, tile_data, sms_root, &dummy_rdc, mi_row, mi_col, 0); av1_reset_mbmi(&cm->mi_params, sb_size, mi_row, mi_col); av1_reset_simple_motion_tree_partition(sms_root, sb_size); av1_restore_sb_state(&sb_fp_stats, cpi, td, tile_data, mi_row, mi_col); PC_TREE *const pc_root_p1 = av1_alloc_pc_tree_node(sb_size); av1_rd_pick_partition(cpi, td, tile_data, tp, mi_row, mi_col, sb_size, &dummy_rdc, dummy_rdc, pc_root_p1, sms_root, NULL, SB_WET_PASS, NULL); } // Reset to 0 so that it wouldn't be used elsewhere mistakenly. sb_enc->tpl_data_count = 0; #if CONFIG_COLLECT_COMPONENT_TIMING end_timing(cpi, rd_pick_partition_time); #endif } #endif // !CONFIG_REALTIME_ONLY // Update the inter rd model // TODO(angiebird): Let inter_mode_rd_model_estimation support multi-tile. if (cpi->sf.inter_sf.inter_mode_rd_model_estimation == 1 && cm->tiles.cols == 1 && cm->tiles.rows == 1) { av1_inter_mode_data_fit(tile_data, x->rdmult); } } /*!\brief Encode a superblock row by breaking it into superblocks * * \ingroup partition_search * \callgraph * \callergraph * Do partition and mode search for an sb row: one row of superblocks filling up * the width of the current tile. */ static AOM_INLINE void encode_sb_row(AV1_COMP *cpi, ThreadData *td, TileDataEnc *tile_data, int mi_row, TokenExtra **tp) { AV1_COMMON *const cm = &cpi->common; const TileInfo *const tile_info = &tile_data->tile_info; MultiThreadInfo *const mt_info = &cpi->mt_info; AV1EncRowMultiThreadInfo *const enc_row_mt = &mt_info->enc_row_mt; AV1EncRowMultiThreadSync *const row_mt_sync = &tile_data->row_mt_sync; bool row_mt_enabled = mt_info->row_mt_enabled; MACROBLOCK *const x = &td->mb; MACROBLOCKD *const xd = &x->e_mbd; const int sb_cols_in_tile = av1_get_sb_cols_in_tile(cm, tile_data->tile_info); const BLOCK_SIZE sb_size = cm->seq_params.sb_size; const int mib_size = cm->seq_params.mib_size; const int mib_size_log2 = cm->seq_params.mib_size_log2; const int sb_row = (mi_row - tile_info->mi_row_start) >> mib_size_log2; const int use_nonrd_mode = cpi->sf.rt_sf.use_nonrd_pick_mode; #if CONFIG_COLLECT_COMPONENT_TIMING start_timing(cpi, encode_sb_time); #endif // Initialize the left context for the new SB row av1_zero_left_context(xd); // Reset delta for quantizer and loof filters at the beginning of every tile if (mi_row == tile_info->mi_row_start || row_mt_enabled) { if (cm->delta_q_info.delta_q_present_flag) xd->current_base_qindex = cm->quant_params.base_qindex; if (cm->delta_q_info.delta_lf_present_flag) { av1_reset_loop_filter_delta(xd, av1_num_planes(cm)); } } reset_thresh_freq_fact(x); // Code each SB in the row for (int mi_col = tile_info->mi_col_start, sb_col_in_tile = 0; mi_col < tile_info->mi_col_end; mi_col += mib_size, sb_col_in_tile++) { (*(enc_row_mt->sync_read_ptr))(row_mt_sync, sb_row, sb_col_in_tile); if (tile_data->allow_update_cdf && row_mt_enabled && (tile_info->mi_row_start != mi_row)) { if ((tile_info->mi_col_start == mi_col)) { // restore frame context at the 1st column sb memcpy(xd->tile_ctx, x->row_ctx, sizeof(*xd->tile_ctx)); } else { // update context int wt_left = AVG_CDF_WEIGHT_LEFT; int wt_tr = AVG_CDF_WEIGHT_TOP_RIGHT; if (tile_info->mi_col_end > (mi_col + mib_size)) av1_avg_cdf_symbols(xd->tile_ctx, x->row_ctx + sb_col_in_tile, wt_left, wt_tr); else av1_avg_cdf_symbols(xd->tile_ctx, x->row_ctx + sb_col_in_tile - 1, wt_left, wt_tr); } } // Update the rate cost tables for some symbols av1_set_cost_upd_freq(cpi, td, tile_info, mi_row, mi_col); // Reset color coding related parameters x->color_sensitivity[0] = 0; x->color_sensitivity[1] = 0; x->content_state_sb = 0; xd->cur_frame_force_integer_mv = cm->features.cur_frame_force_integer_mv; x->source_variance = UINT_MAX; td->mb.cb_coef_buff = av1_get_cb_coeff_buffer(cpi, mi_row, mi_col); // Get segment id and skip flag const struct segmentation *const seg = &cm->seg; int seg_skip = 0; if (seg->enabled) { const uint8_t *const map = seg->update_map ? cpi->enc_seg.map : cm->last_frame_seg_map; const int segment_id = map ? get_segment_id(&cm->mi_params, map, sb_size, mi_row, mi_col) : 0; seg_skip = segfeature_active(seg, segment_id, SEG_LVL_SKIP); } // encode the superblock if (use_nonrd_mode) { encode_nonrd_sb(cpi, td, tile_data, tp, mi_row, mi_col, seg_skip); } else { encode_rd_sb(cpi, td, tile_data, tp, mi_row, mi_col, seg_skip); } // Update the top-right context in row_mt coding if (tile_data->allow_update_cdf && row_mt_enabled && (tile_info->mi_row_end > (mi_row + mib_size))) { if (sb_cols_in_tile == 1) memcpy(x->row_ctx, xd->tile_ctx, sizeof(*xd->tile_ctx)); else if (sb_col_in_tile >= 1) memcpy(x->row_ctx + sb_col_in_tile - 1, xd->tile_ctx, sizeof(*xd->tile_ctx)); } (*(enc_row_mt->sync_write_ptr))(row_mt_sync, sb_row, sb_col_in_tile, sb_cols_in_tile); } #if CONFIG_COLLECT_COMPONENT_TIMING end_timing(cpi, encode_sb_time); #endif } static AOM_INLINE void init_encode_frame_mb_context(AV1_COMP *cpi) { AV1_COMMON *const cm = &cpi->common; const int num_planes = av1_num_planes(cm); MACROBLOCK *const x = &cpi->td.mb; MACROBLOCKD *const xd = &x->e_mbd; // Copy data over into macro block data structures. av1_setup_src_planes(x, cpi->source, 0, 0, num_planes, cm->seq_params.sb_size); av1_setup_block_planes(xd, cm->seq_params.subsampling_x, cm->seq_params.subsampling_y, num_planes); } void av1_alloc_tile_data(AV1_COMP *cpi) { AV1_COMMON *const cm = &cpi->common; const int tile_cols = cm->tiles.cols; const int tile_rows = cm->tiles.rows; if (cpi->tile_data != NULL) aom_free(cpi->tile_data); CHECK_MEM_ERROR( cm, cpi->tile_data, aom_memalign(32, tile_cols * tile_rows * sizeof(*cpi->tile_data))); cpi->allocated_tiles = tile_cols * tile_rows; } void av1_init_tile_data(AV1_COMP *cpi) { AV1_COMMON *const cm = &cpi->common; const int num_planes = av1_num_planes(cm); const int tile_cols = cm->tiles.cols; const int tile_rows = cm->tiles.rows; int tile_col, tile_row; TokenInfo *const token_info = &cpi->token_info; TokenExtra *pre_tok = token_info->tile_tok[0][0]; TokenList *tplist = token_info->tplist[0][0]; unsigned int tile_tok = 0; int tplist_count = 0; for (tile_row = 0; tile_row < tile_rows; ++tile_row) { for (tile_col = 0; tile_col < tile_cols; ++tile_col) { TileDataEnc *const tile_data = &cpi->tile_data[tile_row * tile_cols + tile_col]; TileInfo *const tile_info = &tile_data->tile_info; av1_tile_init(tile_info, cm, tile_row, tile_col); tile_data->firstpass_top_mv = kZeroMv; if (pre_tok != NULL && tplist != NULL) { token_info->tile_tok[tile_row][tile_col] = pre_tok + tile_tok; pre_tok = token_info->tile_tok[tile_row][tile_col]; tile_tok = allocated_tokens(*tile_info, cm->seq_params.mib_size_log2 + MI_SIZE_LOG2, num_planes); token_info->tplist[tile_row][tile_col] = tplist + tplist_count; tplist = token_info->tplist[tile_row][tile_col]; tplist_count = av1_get_sb_rows_in_tile(cm, tile_data->tile_info); } tile_data->allow_update_cdf = !cm->tiles.large_scale; tile_data->allow_update_cdf = tile_data->allow_update_cdf && !cm->features.disable_cdf_update; tile_data->tctx = *cm->fc; } } } /*!\brief Encode a superblock row * * \ingroup partition_search */ void av1_encode_sb_row(AV1_COMP *cpi, ThreadData *td, int tile_row, int tile_col, int mi_row) { AV1_COMMON *const cm = &cpi->common; const int num_planes = av1_num_planes(cm); const int tile_cols = cm->tiles.cols; TileDataEnc *this_tile = &cpi->tile_data[tile_row * tile_cols + tile_col]; const TileInfo *const tile_info = &this_tile->tile_info; TokenExtra *tok = NULL; TokenList *const tplist = cpi->token_info.tplist[tile_row][tile_col]; const int sb_row_in_tile = (mi_row - tile_info->mi_row_start) >> cm->seq_params.mib_size_log2; const int tile_mb_cols = (tile_info->mi_col_end - tile_info->mi_col_start + 2) >> 2; const int num_mb_rows_in_sb = ((1 << (cm->seq_params.mib_size_log2 + MI_SIZE_LOG2)) + 8) >> 4; get_start_tok(cpi, tile_row, tile_col, mi_row, &tok, cm->seq_params.mib_size_log2 + MI_SIZE_LOG2, num_planes); tplist[sb_row_in_tile].start = tok; encode_sb_row(cpi, td, this_tile, mi_row, &tok); tplist[sb_row_in_tile].count = (unsigned int)(tok - tplist[sb_row_in_tile].start); assert((unsigned int)(tok - tplist[sb_row_in_tile].start) <= get_token_alloc(num_mb_rows_in_sb, tile_mb_cols, cm->seq_params.mib_size_log2 + MI_SIZE_LOG2, num_planes)); (void)tile_mb_cols; (void)num_mb_rows_in_sb; } /*!\brief Encode a tile * * \ingroup partition_search */ void av1_encode_tile(AV1_COMP *cpi, ThreadData *td, int tile_row, int tile_col) { AV1_COMMON *const cm = &cpi->common; TileDataEnc *const this_tile = &cpi->tile_data[tile_row * cm->tiles.cols + tile_col]; const TileInfo *const tile_info = &this_tile->tile_info; if (!cpi->sf.rt_sf.use_nonrd_pick_mode) av1_inter_mode_data_init(this_tile); av1_zero_above_context(cm, &td->mb.e_mbd, tile_info->mi_col_start, tile_info->mi_col_end, tile_row); av1_init_above_context(&cm->above_contexts, av1_num_planes(cm), tile_row, &td->mb.e_mbd); if (cpi->oxcf.intra_mode_cfg.enable_cfl_intra) cfl_init(&td->mb.e_mbd.cfl, &cm->seq_params); av1_crc32c_calculator_init( &td->mb.txfm_search_info.mb_rd_record.crc_calculator); for (int mi_row = tile_info->mi_row_start; mi_row < tile_info->mi_row_end; mi_row += cm->seq_params.mib_size) { av1_encode_sb_row(cpi, td, tile_row, tile_col, mi_row); } } /*!\brief Break one frame into tiles and encode the tiles * * \ingroup partition_search * * \param[in] cpi Top-level encoder structure */ static AOM_INLINE void encode_tiles(AV1_COMP *cpi) { AV1_COMMON *const cm = &cpi->common; const int tile_cols = cm->tiles.cols; const int tile_rows = cm->tiles.rows; int tile_col, tile_row; assert(IMPLIES(cpi->tile_data == NULL, cpi->allocated_tiles < tile_cols * tile_rows)); if (cpi->allocated_tiles < tile_cols * tile_rows) av1_alloc_tile_data(cpi); av1_init_tile_data(cpi); for (tile_row = 0; tile_row < tile_rows; ++tile_row) { for (tile_col = 0; tile_col < tile_cols; ++tile_col) { TileDataEnc *const this_tile = &cpi->tile_data[tile_row * cm->tiles.cols + tile_col]; cpi->td.intrabc_used = 0; cpi->td.deltaq_used = 0; cpi->td.mb.e_mbd.tile_ctx = &this_tile->tctx; cpi->td.mb.tile_pb_ctx = &this_tile->tctx; av1_encode_tile(cpi, &cpi->td, tile_row, tile_col); cpi->intrabc_used |= cpi->td.intrabc_used; cpi->deltaq_used |= cpi->td.deltaq_used; } } } // Set the relative distance of a reference frame w.r.t. current frame static AOM_INLINE void set_rel_frame_dist( const AV1_COMMON *const cm, RefFrameDistanceInfo *const ref_frame_dist_info, const int ref_frame_flags) { const OrderHintInfo *const order_hint_info = &cm->seq_params.order_hint_info; MV_REFERENCE_FRAME ref_frame; int min_past_dist = INT32_MAX, min_future_dist = INT32_MAX; ref_frame_dist_info->nearest_past_ref = NONE_FRAME; ref_frame_dist_info->nearest_future_ref = NONE_FRAME; for (ref_frame = LAST_FRAME; ref_frame <= ALTREF_FRAME; ++ref_frame) { ref_frame_dist_info->ref_relative_dist[ref_frame - LAST_FRAME] = 0; if (ref_frame_flags & av1_ref_frame_flag_list[ref_frame]) { int dist = av1_encoder_get_relative_dist( order_hint_info, cm->cur_frame->ref_display_order_hint[ref_frame - LAST_FRAME], cm->current_frame.display_order_hint); ref_frame_dist_info->ref_relative_dist[ref_frame - LAST_FRAME] = dist; // Get the nearest ref_frame in the past if (abs(dist) < min_past_dist && dist < 0) { ref_frame_dist_info->nearest_past_ref = ref_frame; min_past_dist = abs(dist); } // Get the nearest ref_frame in the future if (dist < min_future_dist && dist > 0) { ref_frame_dist_info->nearest_future_ref = ref_frame; min_future_dist = dist; } } } } static INLINE int refs_are_one_sided(const AV1_COMMON *cm) { assert(!frame_is_intra_only(cm)); int one_sided_refs = 1; for (int ref = LAST_FRAME; ref <= ALTREF_FRAME; ++ref) { const RefCntBuffer *const buf = get_ref_frame_buf(cm, ref); if (buf == NULL) continue; const int ref_display_order_hint = buf->display_order_hint; if (av1_encoder_get_relative_dist( &cm->seq_params.order_hint_info, ref_display_order_hint, (int)cm->current_frame.display_order_hint) > 0) { one_sided_refs = 0; // bwd reference break; } } return one_sided_refs; } static INLINE void get_skip_mode_ref_offsets(const AV1_COMMON *cm, int ref_order_hint[2]) { const SkipModeInfo *const skip_mode_info = &cm->current_frame.skip_mode_info; ref_order_hint[0] = ref_order_hint[1] = 0; if (!skip_mode_info->skip_mode_allowed) return; const RefCntBuffer *const buf_0 = get_ref_frame_buf(cm, LAST_FRAME + skip_mode_info->ref_frame_idx_0); const RefCntBuffer *const buf_1 = get_ref_frame_buf(cm, LAST_FRAME + skip_mode_info->ref_frame_idx_1); assert(buf_0 != NULL && buf_1 != NULL); ref_order_hint[0] = buf_0->order_hint; ref_order_hint[1] = buf_1->order_hint; } static int check_skip_mode_enabled(AV1_COMP *const cpi) { AV1_COMMON *const cm = &cpi->common; av1_setup_skip_mode_allowed(cm); if (!cm->current_frame.skip_mode_info.skip_mode_allowed) return 0; // Turn off skip mode if the temporal distances of the reference pair to the // current frame are different by more than 1 frame. const int cur_offset = (int)cm->current_frame.order_hint; int ref_offset[2]; get_skip_mode_ref_offsets(cm, ref_offset); const int cur_to_ref0 = get_relative_dist(&cm->seq_params.order_hint_info, cur_offset, ref_offset[0]); const int cur_to_ref1 = abs(get_relative_dist(&cm->seq_params.order_hint_info, cur_offset, ref_offset[1])); if (abs(cur_to_ref0 - cur_to_ref1) > 1) return 0; // High Latency: Turn off skip mode if all refs are fwd. if (cpi->all_one_sided_refs && cpi->oxcf.gf_cfg.lag_in_frames > 0) return 0; static const int flag_list[REF_FRAMES] = { 0, AOM_LAST_FLAG, AOM_LAST2_FLAG, AOM_LAST3_FLAG, AOM_GOLD_FLAG, AOM_BWD_FLAG, AOM_ALT2_FLAG, AOM_ALT_FLAG }; const int ref_frame[2] = { cm->current_frame.skip_mode_info.ref_frame_idx_0 + LAST_FRAME, cm->current_frame.skip_mode_info.ref_frame_idx_1 + LAST_FRAME }; if (!(cpi->ref_frame_flags & flag_list[ref_frame[0]]) || !(cpi->ref_frame_flags & flag_list[ref_frame[1]])) return 0; return 1; } static AOM_INLINE void set_default_interp_skip_flags( const AV1_COMMON *cm, InterpSearchFlags *interp_search_flags) { const int num_planes = av1_num_planes(cm); interp_search_flags->default_interp_skip_flags = (num_planes == 1) ? INTERP_SKIP_LUMA_EVAL_CHROMA : INTERP_SKIP_LUMA_SKIP_CHROMA; } static AOM_INLINE void setup_prune_ref_frame_mask(AV1_COMP *cpi) { if ((!cpi->oxcf.ref_frm_cfg.enable_onesided_comp || cpi->sf.inter_sf.disable_onesided_comp) && cpi->all_one_sided_refs) { // Disable all compound references cpi->prune_ref_frame_mask = (1 << MODE_CTX_REF_FRAMES) - (1 << REF_FRAMES); } else if (!cpi->sf.rt_sf.use_nonrd_pick_mode && cpi->sf.inter_sf.selective_ref_frame >= 2) { AV1_COMMON *const cm = &cpi->common; const OrderHintInfo *const order_hint_info = &cm->seq_params.order_hint_info; const int cur_frame_display_order_hint = cm->current_frame.display_order_hint; unsigned int *ref_display_order_hint = cm->cur_frame->ref_display_order_hint; const int arf2_dist = av1_encoder_get_relative_dist( order_hint_info, ref_display_order_hint[ALTREF2_FRAME - LAST_FRAME], cur_frame_display_order_hint); const int bwd_dist = av1_encoder_get_relative_dist( order_hint_info, ref_display_order_hint[BWDREF_FRAME - LAST_FRAME], cur_frame_display_order_hint); for (int ref_idx = REF_FRAMES; ref_idx < MODE_CTX_REF_FRAMES; ++ref_idx) { MV_REFERENCE_FRAME rf[2]; av1_set_ref_frame(rf, ref_idx); if (!(cpi->ref_frame_flags & av1_ref_frame_flag_list[rf[0]]) || !(cpi->ref_frame_flags & av1_ref_frame_flag_list[rf[1]])) { continue; } if (!cpi->all_one_sided_refs) { int ref_dist[2]; for (int i = 0; i < 2; ++i) { ref_dist[i] = av1_encoder_get_relative_dist( order_hint_info, ref_display_order_hint[rf[i] - LAST_FRAME], cur_frame_display_order_hint); } // One-sided compound is used only when all reference frames are // one-sided. if ((ref_dist[0] > 0) == (ref_dist[1] > 0)) { cpi->prune_ref_frame_mask |= 1 << ref_idx; } } if (cpi->sf.inter_sf.selective_ref_frame >= 4 && (rf[0] == ALTREF2_FRAME || rf[1] == ALTREF2_FRAME) && (cpi->ref_frame_flags & av1_ref_frame_flag_list[BWDREF_FRAME])) { // Check if both ALTREF2_FRAME and BWDREF_FRAME are future references. if (arf2_dist > 0 && bwd_dist > 0 && bwd_dist <= arf2_dist) { // Drop ALTREF2_FRAME as a reference if BWDREF_FRAME is a closer // reference to the current frame than ALTREF2_FRAME cpi->prune_ref_frame_mask |= 1 << ref_idx; } } } } } /*!\brief Encoder setup(only for the current frame), encoding, and recontruction * for a single frame * * \ingroup high_level_algo */ static AOM_INLINE void encode_frame_internal(AV1_COMP *cpi) { ThreadData *const td = &cpi->td; MACROBLOCK *const x = &td->mb; AV1_COMMON *const cm = &cpi->common; CommonModeInfoParams *const mi_params = &cm->mi_params; FeatureFlags *const features = &cm->features; MACROBLOCKD *const xd = &x->e_mbd; RD_COUNTS *const rdc = &cpi->td.rd_counts; FrameProbInfo *const frame_probs = &cpi->frame_probs; IntraBCHashInfo *const intrabc_hash_info = &x->intrabc_hash_info; MultiThreadInfo *const mt_info = &cpi->mt_info; AV1EncRowMultiThreadInfo *const enc_row_mt = &mt_info->enc_row_mt; const AV1EncoderConfig *const oxcf = &cpi->oxcf; const DELTAQ_MODE deltaq_mode = oxcf->q_cfg.deltaq_mode; int i; if (!cpi->sf.rt_sf.use_nonrd_pick_mode) { mi_params->setup_mi(mi_params); } set_mi_offsets(mi_params, xd, 0, 0); av1_zero(*td->counts); av1_zero(rdc->comp_pred_diff); av1_zero(rdc->tx_type_used); av1_zero(rdc->obmc_used); av1_zero(rdc->warped_used); // Reset the flag. cpi->intrabc_used = 0; // Need to disable intrabc when superres is selected if (av1_superres_scaled(cm)) { features->allow_intrabc = 0; } features->allow_intrabc &= (oxcf->kf_cfg.enable_intrabc); if (features->allow_warped_motion && cpi->sf.inter_sf.prune_warped_prob_thresh > 0) { const FRAME_UPDATE_TYPE update_type = get_frame_update_type(&cpi->gf_group); if (frame_probs->warped_probs[update_type] < cpi->sf.inter_sf.prune_warped_prob_thresh) features->allow_warped_motion = 0; } int hash_table_created = 0; if (!is_stat_generation_stage(cpi) && av1_use_hash_me(cpi) && !cpi->sf.rt_sf.use_nonrd_pick_mode) { // TODO(any): move this outside of the recoding loop to avoid recalculating // the hash table. // add to hash table const int pic_width = cpi->source->y_crop_width; const int pic_height = cpi->source->y_crop_height; uint32_t *block_hash_values[2][2]; int8_t *is_block_same[2][3]; int k, j; for (k = 0; k < 2; k++) { for (j = 0; j < 2; j++) { CHECK_MEM_ERROR(cm, block_hash_values[k][j], aom_malloc(sizeof(uint32_t) * pic_width * pic_height)); } for (j = 0; j < 3; j++) { CHECK_MEM_ERROR(cm, is_block_same[k][j], aom_malloc(sizeof(int8_t) * pic_width * pic_height)); } } av1_hash_table_init(intrabc_hash_info); av1_hash_table_create(&intrabc_hash_info->intrabc_hash_table); hash_table_created = 1; av1_generate_block_2x2_hash_value(intrabc_hash_info, cpi->source, block_hash_values[0], is_block_same[0]); // Hash data generated for screen contents is used for intraBC ME const int min_alloc_size = block_size_wide[mi_params->mi_alloc_bsize]; const int max_sb_size = (1 << (cm->seq_params.mib_size_log2 + MI_SIZE_LOG2)); int src_idx = 0; for (int size = 4; size <= max_sb_size; size *= 2, src_idx = !src_idx) { const int dst_idx = !src_idx; av1_generate_block_hash_value( intrabc_hash_info, cpi->source, size, block_hash_values[src_idx], block_hash_values[dst_idx], is_block_same[src_idx], is_block_same[dst_idx]); if (size >= min_alloc_size) { av1_add_to_hash_map_by_row_with_precal_data( &intrabc_hash_info->intrabc_hash_table, block_hash_values[dst_idx], is_block_same[dst_idx][2], pic_width, pic_height, size); } } for (k = 0; k < 2; k++) { for (j = 0; j < 2; j++) { aom_free(block_hash_values[k][j]); } for (j = 0; j < 3; j++) { aom_free(is_block_same[k][j]); } } } const CommonQuantParams *quant_params = &cm->quant_params; for (i = 0; i < MAX_SEGMENTS; ++i) { const int qindex = cm->seg.enabled ? av1_get_qindex(&cm->seg, i, quant_params->base_qindex) : quant_params->base_qindex; xd->lossless[i] = qindex == 0 && quant_params->y_dc_delta_q == 0 && quant_params->u_dc_delta_q == 0 && quant_params->u_ac_delta_q == 0 && quant_params->v_dc_delta_q == 0 && quant_params->v_ac_delta_q == 0; if (xd->lossless[i]) cpi->enc_seg.has_lossless_segment = 1; xd->qindex[i] = qindex; if (xd->lossless[i]) { cpi->optimize_seg_arr[i] = NO_TRELLIS_OPT; } else { cpi->optimize_seg_arr[i] = cpi->sf.rd_sf.optimize_coefficients; } } features->coded_lossless = is_coded_lossless(cm, xd); features->all_lossless = features->coded_lossless && !av1_superres_scaled(cm); // Fix delta q resolution for the moment cm->delta_q_info.delta_q_res = 0; if (cpi->oxcf.q_cfg.aq_mode != CYCLIC_REFRESH_AQ) { if (deltaq_mode == DELTA_Q_OBJECTIVE) cm->delta_q_info.delta_q_res = DEFAULT_DELTA_Q_RES_OBJECTIVE; else if (deltaq_mode == DELTA_Q_PERCEPTUAL) cm->delta_q_info.delta_q_res = DEFAULT_DELTA_Q_RES_PERCEPTUAL; // Set delta_q_present_flag before it is used for the first time cm->delta_q_info.delta_lf_res = DEFAULT_DELTA_LF_RES; cm->delta_q_info.delta_q_present_flag = deltaq_mode != NO_DELTA_Q; // Turn off cm->delta_q_info.delta_q_present_flag if objective delta_q // is used for ineligible frames. That effectively will turn off row_mt // usage. Note objective delta_q and tpl eligible frames are only altref // frames currently. const GF_GROUP *gf_group = &cpi->gf_group; if (cm->delta_q_info.delta_q_present_flag) { if (deltaq_mode == DELTA_Q_OBJECTIVE && !is_frame_tpl_eligible(gf_group, gf_group->index)) cm->delta_q_info.delta_q_present_flag = 0; } // Reset delta_q_used flag cpi->deltaq_used = 0; cm->delta_q_info.delta_lf_present_flag = cm->delta_q_info.delta_q_present_flag && oxcf->tool_cfg.enable_deltalf_mode; cm->delta_q_info.delta_lf_multi = DEFAULT_DELTA_LF_MULTI; // update delta_q_present_flag and delta_lf_present_flag based on // base_qindex cm->delta_q_info.delta_q_present_flag &= quant_params->base_qindex > 0; cm->delta_q_info.delta_lf_present_flag &= quant_params->base_qindex > 0; } av1_frame_init_quantizer(cpi); av1_initialize_rd_consts(cpi); av1_set_sad_per_bit(cpi, &x->mv_costs, quant_params->base_qindex); init_encode_frame_mb_context(cpi); set_default_interp_skip_flags(cm, &cpi->interp_search_flags); if (cm->prev_frame && cm->prev_frame->seg.enabled) cm->last_frame_seg_map = cm->prev_frame->seg_map; else cm->last_frame_seg_map = NULL; if (features->allow_intrabc || features->coded_lossless) { av1_set_default_ref_deltas(cm->lf.ref_deltas); av1_set_default_mode_deltas(cm->lf.mode_deltas); } else if (cm->prev_frame) { memcpy(cm->lf.ref_deltas, cm->prev_frame->ref_deltas, REF_FRAMES); memcpy(cm->lf.mode_deltas, cm->prev_frame->mode_deltas, MAX_MODE_LF_DELTAS); } memcpy(cm->cur_frame->ref_deltas, cm->lf.ref_deltas, REF_FRAMES); memcpy(cm->cur_frame->mode_deltas, cm->lf.mode_deltas, MAX_MODE_LF_DELTAS); cpi->all_one_sided_refs = frame_is_intra_only(cm) ? 0 : refs_are_one_sided(cm); cpi->prune_ref_frame_mask = 0; // Figure out which ref frames can be skipped at frame level. setup_prune_ref_frame_mask(cpi); x->txfm_search_info.txb_split_count = 0; #if CONFIG_SPEED_STATS x->txfm_search_info.tx_search_count = 0; #endif // CONFIG_SPEED_STATS #if CONFIG_COLLECT_COMPONENT_TIMING start_timing(cpi, av1_compute_global_motion_time); #endif av1_compute_global_motion_facade(cpi); #if CONFIG_COLLECT_COMPONENT_TIMING end_timing(cpi, av1_compute_global_motion_time); #endif #if CONFIG_COLLECT_COMPONENT_TIMING start_timing(cpi, av1_setup_motion_field_time); #endif if (features->allow_ref_frame_mvs) av1_setup_motion_field(cm); #if CONFIG_COLLECT_COMPONENT_TIMING end_timing(cpi, av1_setup_motion_field_time); #endif cm->current_frame.skip_mode_info.skip_mode_flag = check_skip_mode_enabled(cpi); enc_row_mt->sync_read_ptr = av1_row_mt_sync_read_dummy; enc_row_mt->sync_write_ptr = av1_row_mt_sync_write_dummy; mt_info->row_mt_enabled = 0; if (oxcf->row_mt && (mt_info->num_workers > 1)) { mt_info->row_mt_enabled = 1; enc_row_mt->sync_read_ptr = av1_row_mt_sync_read; enc_row_mt->sync_write_ptr = av1_row_mt_sync_write; av1_encode_tiles_row_mt(cpi); } else { if (AOMMIN(mt_info->num_workers, cm->tiles.cols * cm->tiles.rows) > 1) av1_encode_tiles_mt(cpi); else encode_tiles(cpi); } // If intrabc is allowed but never selected, reset the allow_intrabc flag. if (features->allow_intrabc && !cpi->intrabc_used) { features->allow_intrabc = 0; } if (features->allow_intrabc) { cm->delta_q_info.delta_lf_present_flag = 0; } if (cm->delta_q_info.delta_q_present_flag && cpi->deltaq_used == 0) { cm->delta_q_info.delta_q_present_flag = 0; } // Set the transform size appropriately before bitstream creation const MODE_EVAL_TYPE eval_type = cpi->sf.winner_mode_sf.enable_winner_mode_for_tx_size_srch ? WINNER_MODE_EVAL : DEFAULT_EVAL; const TX_SIZE_SEARCH_METHOD tx_search_type = cpi->winner_mode_params.tx_size_search_methods[eval_type]; assert(oxcf->txfm_cfg.enable_tx64 || tx_search_type != USE_LARGESTALL); features->tx_mode = select_tx_mode(cm, tx_search_type); if (cpi->sf.tx_sf.tx_type_search.prune_tx_type_using_stats) { const FRAME_UPDATE_TYPE update_type = get_frame_update_type(&cpi->gf_group); for (i = 0; i < TX_SIZES_ALL; i++) { int sum = 0; int j; int left = 1024; for (j = 0; j < TX_TYPES; j++) sum += cpi->td.rd_counts.tx_type_used[i][j]; for (j = TX_TYPES - 1; j >= 0; j--) { const int new_prob = sum ? 1024 * cpi->td.rd_counts.tx_type_used[i][j] / sum : (j ? 0 : 1024); int prob = (frame_probs->tx_type_probs[update_type][i][j] + new_prob) >> 1; left -= prob; if (j == 0) prob += left; frame_probs->tx_type_probs[update_type][i][j] = prob; } } } if (!cpi->sf.inter_sf.disable_obmc && cpi->sf.inter_sf.prune_obmc_prob_thresh > 0) { const FRAME_UPDATE_TYPE update_type = get_frame_update_type(&cpi->gf_group); for (i = 0; i < BLOCK_SIZES_ALL; i++) { int sum = 0; for (int j = 0; j < 2; j++) sum += cpi->td.rd_counts.obmc_used[i][j]; const int new_prob = sum ? 128 * cpi->td.rd_counts.obmc_used[i][1] / sum : 0; frame_probs->obmc_probs[update_type][i] = (frame_probs->obmc_probs[update_type][i] + new_prob) >> 1; } } if (features->allow_warped_motion && cpi->sf.inter_sf.prune_warped_prob_thresh > 0) { const FRAME_UPDATE_TYPE update_type = get_frame_update_type(&cpi->gf_group); int sum = 0; for (i = 0; i < 2; i++) sum += cpi->td.rd_counts.warped_used[i]; const int new_prob = sum ? 128 * cpi->td.rd_counts.warped_used[1] / sum : 0; frame_probs->warped_probs[update_type] = (frame_probs->warped_probs[update_type] + new_prob) >> 1; } if (cm->current_frame.frame_type != KEY_FRAME && cpi->sf.interp_sf.adaptive_interp_filter_search == 2 && features->interp_filter == SWITCHABLE) { const FRAME_UPDATE_TYPE update_type = get_frame_update_type(&cpi->gf_group); for (i = 0; i < SWITCHABLE_FILTER_CONTEXTS; i++) { int sum = 0; int j; int left = 1536; for (j = 0; j < SWITCHABLE_FILTERS; j++) { sum += cpi->td.counts->switchable_interp[i][j]; } for (j = SWITCHABLE_FILTERS - 1; j >= 0; j--) { const int new_prob = sum ? 1536 * cpi->td.counts->switchable_interp[i][j] / sum : (j ? 0 : 1536); int prob = (frame_probs->switchable_interp_probs[update_type][i][j] + new_prob) >> 1; left -= prob; if (j == 0) prob += left; frame_probs->switchable_interp_probs[update_type][i][j] = prob; } } } if (hash_table_created) { av1_hash_table_destroy(&intrabc_hash_info->intrabc_hash_table); } } /*!\brief Setup reference frame buffers and encode a frame * * \ingroup high_level_algo * \callgraph * \callergraph * * \param[in] cpi Top-level encoder structure */ void av1_encode_frame(AV1_COMP *cpi) { AV1_COMMON *const cm = &cpi->common; CurrentFrame *const current_frame = &cm->current_frame; FeatureFlags *const features = &cm->features; const int num_planes = av1_num_planes(cm); // Indicates whether or not to use a default reduced set for ext-tx // rather than the potential full set of 16 transforms features->reduced_tx_set_used = cpi->oxcf.txfm_cfg.reduced_tx_type_set; // Make sure segment_id is no larger than last_active_segid. if (cm->seg.enabled && cm->seg.update_map) { const int mi_rows = cm->mi_params.mi_rows; const int mi_cols = cm->mi_params.mi_cols; const int last_active_segid = cm->seg.last_active_segid; uint8_t *map = cpi->enc_seg.map; for (int mi_row = 0; mi_row < mi_rows; ++mi_row) { for (int mi_col = 0; mi_col < mi_cols; ++mi_col) { map[mi_col] = AOMMIN(map[mi_col], last_active_segid); } map += mi_cols; } } av1_setup_frame_buf_refs(cm); enforce_max_ref_frames(cpi, &cpi->ref_frame_flags, cm->cur_frame->ref_display_order_hint, cm->current_frame.display_order_hint); set_rel_frame_dist(&cpi->common, &cpi->ref_frame_dist_info, cpi->ref_frame_flags); av1_setup_frame_sign_bias(cm); #if CONFIG_MISMATCH_DEBUG mismatch_reset_frame(num_planes); #else (void)num_planes; #endif if (cpi->sf.hl_sf.frame_parameter_update) { RD_COUNTS *const rdc = &cpi->td.rd_counts; if (frame_is_intra_only(cm)) current_frame->reference_mode = SINGLE_REFERENCE; else current_frame->reference_mode = REFERENCE_MODE_SELECT; features->interp_filter = SWITCHABLE; if (cm->tiles.large_scale) features->interp_filter = EIGHTTAP_REGULAR; features->switchable_motion_mode = 1; rdc->compound_ref_used_flag = 0; rdc->skip_mode_used_flag = 0; encode_frame_internal(cpi); if (current_frame->reference_mode == REFERENCE_MODE_SELECT) { // Use a flag that includes 4x4 blocks if (rdc->compound_ref_used_flag == 0) { current_frame->reference_mode = SINGLE_REFERENCE; #if CONFIG_ENTROPY_STATS av1_zero(cpi->td.counts->comp_inter); #endif // CONFIG_ENTROPY_STATS } } // Re-check on the skip mode status as reference mode may have been // changed. SkipModeInfo *const skip_mode_info = &current_frame->skip_mode_info; if (frame_is_intra_only(cm) || current_frame->reference_mode == SINGLE_REFERENCE) { skip_mode_info->skip_mode_allowed = 0; skip_mode_info->skip_mode_flag = 0; } if (skip_mode_info->skip_mode_flag && rdc->skip_mode_used_flag == 0) skip_mode_info->skip_mode_flag = 0; if (!cm->tiles.large_scale) { if (features->tx_mode == TX_MODE_SELECT && cpi->td.mb.txfm_search_info.txb_split_count == 0) features->tx_mode = TX_MODE_LARGEST; } } else { encode_frame_internal(cpi); } }
40.022154
80
0.659911
[ "model", "transform" ]
b106e81dd2f14adfe059cdd3daf32ccfa53804b3
64,295
h
C
greybus_protocols.h
agarwalvaibhav/gbsim
ba54c5743c79c16bf06eb32983442fbb0dcfe69e
[ "BSD-3-Clause" ]
34
2015-01-14T18:23:24.000Z
2021-02-12T12:39:48.000Z
greybus_protocols.h
gregkh/gbsim
ba54c5743c79c16bf06eb32983442fbb0dcfe69e
[ "BSD-3-Clause" ]
1
2019-05-28T06:12:23.000Z
2019-05-28T06:12:23.000Z
greybus_protocols.h
gregkh/gbsim
ba54c5743c79c16bf06eb32983442fbb0dcfe69e
[ "BSD-3-Clause" ]
20
2015-01-14T20:51:21.000Z
2020-04-13T09:45:18.000Z
/* * This file is provided under a dual BSD/GPLv2 license. When using or * redistributing this file, you may do so under either license. * * GPL LICENSE SUMMARY * * Copyright(c) 2014 - 2015 Google Inc. All rights reserved. * Copyright(c) 2014 - 2015 Linaro Ltd. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License version 2 for more details. * * BSD LICENSE * * Copyright(c) 2014 - 2015 Google Inc. All rights reserved. * Copyright(c) 2014 - 2015 Linaro 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: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. or Linaro Ltd. 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 GOOGLE INC. OR * LINARO LTD. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __GREYBUS_PROTOCOLS_H #define __GREYBUS_PROTOCOLS_H /* Fixed IDs for control/svc protocols */ /* SVC switch-port device ids */ #define GB_SVC_DEVICE_ID_SVC 0 #define GB_SVC_DEVICE_ID_AP 1 #define GB_SVC_DEVICE_ID_MIN 2 #define GB_SVC_DEVICE_ID_MAX 31 #define GB_SVC_CPORT_ID 0 #define GB_CONTROL_BUNDLE_ID 0 #define GB_CONTROL_CPORT_ID 0 /* * All operation messages (both requests and responses) begin with * a header that encodes the size of the message (header included). * This header also contains a unique identifier, that associates a * response message with its operation. The header contains an * operation type field, whose interpretation is dependent on what * type of protocol is used over the connection. The high bit * (0x80) of the operation type field is used to indicate whether * the message is a request (clear) or a response (set). * * Response messages include an additional result byte, which * communicates the result of the corresponding request. A zero * result value means the operation completed successfully. Any * other value indicates an error; in this case, the payload of the * response message (if any) is ignored. The result byte must be * zero in the header for a request message. * * The wire format for all numeric fields in the header is little * endian. Any operation-specific data begins immediately after the * header. */ struct gb_operation_msg_hdr { __le16 size; /* Size in bytes of header + payload */ __le16 operation_id; /* Operation unique id */ __u8 type; /* E.g GB_I2C_TYPE_* or GB_GPIO_TYPE_* */ __u8 result; /* Result of request (in responses only) */ __u8 pad[2]; /* must be zero (ignore when read) */ } __packed; /* Generic request types */ #define GB_REQUEST_TYPE_CPORT_SHUTDOWN 0x00 #define GB_REQUEST_TYPE_INVALID 0x7f struct gb_cport_shutdown_request { __u8 phase; } __packed; /* Control Protocol */ /* Greybus control request types */ #define GB_CONTROL_TYPE_VERSION 0x01 #define GB_CONTROL_TYPE_PROBE_AP 0x02 #define GB_CONTROL_TYPE_GET_MANIFEST_SIZE 0x03 #define GB_CONTROL_TYPE_GET_MANIFEST 0x04 #define GB_CONTROL_TYPE_CONNECTED 0x05 #define GB_CONTROL_TYPE_DISCONNECTED 0x06 #define GB_CONTROL_TYPE_TIMESYNC_ENABLE 0x07 #define GB_CONTROL_TYPE_TIMESYNC_DISABLE 0x08 #define GB_CONTROL_TYPE_TIMESYNC_AUTHORITATIVE 0x09 /* Unused 0x0a */ #define GB_CONTROL_TYPE_BUNDLE_VERSION 0x0b #define GB_CONTROL_TYPE_DISCONNECTING 0x0c #define GB_CONTROL_TYPE_TIMESYNC_GET_LAST_EVENT 0x0d #define GB_CONTROL_TYPE_MODE_SWITCH 0x0e #define GB_CONTROL_TYPE_BUNDLE_SUSPEND 0x0f #define GB_CONTROL_TYPE_BUNDLE_RESUME 0x10 #define GB_CONTROL_TYPE_BUNDLE_DEACTIVATE 0x11 #define GB_CONTROL_TYPE_BUNDLE_ACTIVATE 0x12 #define GB_CONTROL_TYPE_INTF_SUSPEND_PREPARE 0x13 #define GB_CONTROL_TYPE_INTF_DEACTIVATE_PREPARE 0x14 #define GB_CONTROL_TYPE_INTF_HIBERNATE_ABORT 0x15 struct gb_control_version_request { __u8 major; __u8 minor; } __packed; struct gb_control_version_response { __u8 major; __u8 minor; } __packed; struct gb_control_bundle_version_request { __u8 bundle_id; } __packed; struct gb_control_bundle_version_response { __u8 major; __u8 minor; } __packed; /* Control protocol manifest get size request has no payload*/ struct gb_control_get_manifest_size_response { __le16 size; } __packed; /* Control protocol manifest get request has no payload */ struct gb_control_get_manifest_response { __u8 data[0]; } __packed; /* Control protocol [dis]connected request */ struct gb_control_connected_request { __le16 cport_id; } __packed; struct gb_control_disconnecting_request { __le16 cport_id; } __packed; /* disconnecting response has no payload */ struct gb_control_disconnected_request { __le16 cport_id; } __packed; /* Control protocol [dis]connected response has no payload */ #define GB_TIMESYNC_MAX_STROBES 0x04 struct gb_control_timesync_enable_request { __u8 count; __le64 frame_time; __le32 strobe_delay; __le32 refclk; } __packed; /* timesync enable response has no payload */ struct gb_control_timesync_authoritative_request { __le64 frame_time[GB_TIMESYNC_MAX_STROBES]; } __packed; /* timesync authoritative response has no payload */ /* timesync get_last_event_request has no payload */ struct gb_control_timesync_get_last_event_response { __le64 frame_time; } __packed; /* * All Bundle power management operations use the same request and response * layout and status codes. */ #define GB_CONTROL_BUNDLE_PM_OK 0x00 #define GB_CONTROL_BUNDLE_PM_INVAL 0x01 #define GB_CONTROL_BUNDLE_PM_BUSY 0x02 #define GB_CONTROL_BUNDLE_PM_FAIL 0x03 #define GB_CONTROL_BUNDLE_PM_NA 0x04 struct gb_control_bundle_pm_request { __u8 bundle_id; } __packed; struct gb_control_bundle_pm_response { __u8 status; } __packed; /* * Interface Suspend Prepare and Deactivate Prepare operations use the same * response layout and error codes. Define a single response structure and reuse * it. Both operations have no payload. */ #define GB_CONTROL_INTF_PM_OK 0x00 #define GB_CONTROL_INTF_PM_BUSY 0x01 #define GB_CONTROL_INTF_PM_NA 0x02 struct gb_control_intf_pm_response { __u8 status; } __packed; /* APBridge protocol */ /* request APB1 log */ #define GB_APB_REQUEST_LOG 0x02 /* request to map a cport to bulk in and bulk out endpoints */ #define GB_APB_REQUEST_EP_MAPPING 0x03 /* request to get the number of cports available */ #define GB_APB_REQUEST_CPORT_COUNT 0x04 /* request to reset a cport state */ #define GB_APB_REQUEST_RESET_CPORT 0x05 /* request to time the latency of messages on a given cport */ #define GB_APB_REQUEST_LATENCY_TAG_EN 0x06 #define GB_APB_REQUEST_LATENCY_TAG_DIS 0x07 /* request to control the CSI transmitter */ #define GB_APB_REQUEST_CSI_TX_CONTROL 0x08 /* request to control audio streaming */ #define GB_APB_REQUEST_AUDIO_CONTROL 0x09 /* TimeSync requests */ #define GB_APB_REQUEST_TIMESYNC_ENABLE 0x0d #define GB_APB_REQUEST_TIMESYNC_DISABLE 0x0e #define GB_APB_REQUEST_TIMESYNC_AUTHORITATIVE 0x0f #define GB_APB_REQUEST_TIMESYNC_GET_LAST_EVENT 0x10 /* requests to set Greybus CPort flags */ #define GB_APB_REQUEST_CPORT_FLAGS 0x11 /* ARPC request */ #define GB_APB_REQUEST_ARPC_RUN 0x12 struct gb_apb_request_cport_flags { __le32 flags; #define GB_APB_CPORT_FLAG_CONTROL 0x01 #define GB_APB_CPORT_FLAG_HIGH_PRIO 0x02 } __packed; /* Firmware Download Protocol */ /* Request Types */ #define GB_FW_DOWNLOAD_TYPE_FIND_FIRMWARE 0x01 #define GB_FW_DOWNLOAD_TYPE_FETCH_FIRMWARE 0x02 #define GB_FW_DOWNLOAD_TYPE_RELEASE_FIRMWARE 0x03 #define GB_FIRMWARE_TAG_MAX_SIZE 10 /* firmware download find firmware request/response */ struct gb_fw_download_find_firmware_request { __u8 firmware_tag[GB_FIRMWARE_TAG_MAX_SIZE]; } __packed; struct gb_fw_download_find_firmware_response { __u8 firmware_id; __le32 size; } __packed; /* firmware download fetch firmware request/response */ struct gb_fw_download_fetch_firmware_request { __u8 firmware_id; __le32 offset; __le32 size; } __packed; struct gb_fw_download_fetch_firmware_response { __u8 data[0]; } __packed; /* firmware download release firmware request */ struct gb_fw_download_release_firmware_request { __u8 firmware_id; } __packed; /* firmware download release firmware response has no payload */ /* Firmware Management Protocol */ /* Request Types */ #define GB_FW_MGMT_TYPE_INTERFACE_FW_VERSION 0x01 #define GB_FW_MGMT_TYPE_LOAD_AND_VALIDATE_FW 0x02 #define GB_FW_MGMT_TYPE_LOADED_FW 0x03 #define GB_FW_MGMT_TYPE_BACKEND_FW_VERSION 0x04 #define GB_FW_MGMT_TYPE_BACKEND_FW_UPDATE 0x05 #define GB_FW_MGMT_TYPE_BACKEND_FW_UPDATED 0x06 #define GB_FW_LOAD_METHOD_UNIPRO 0x01 #define GB_FW_LOAD_METHOD_INTERNAL 0x02 #define GB_FW_LOAD_STATUS_FAILED 0x00 #define GB_FW_LOAD_STATUS_UNVALIDATED 0x01 #define GB_FW_LOAD_STATUS_VALIDATED 0x02 #define GB_FW_LOAD_STATUS_VALIDATION_FAILED 0x03 #define GB_FW_BACKEND_FW_STATUS_SUCCESS 0x01 #define GB_FW_BACKEND_FW_STATUS_FAIL_FIND 0x02 #define GB_FW_BACKEND_FW_STATUS_FAIL_FETCH 0x03 #define GB_FW_BACKEND_FW_STATUS_FAIL_WRITE 0x04 #define GB_FW_BACKEND_FW_STATUS_INT 0x05 #define GB_FW_BACKEND_FW_STATUS_RETRY 0x06 #define GB_FW_BACKEND_FW_STATUS_NOT_SUPPORTED 0x07 #define GB_FW_BACKEND_VERSION_STATUS_SUCCESS 0x01 #define GB_FW_BACKEND_VERSION_STATUS_NOT_AVAILABLE 0x02 #define GB_FW_BACKEND_VERSION_STATUS_NOT_SUPPORTED 0x03 #define GB_FW_BACKEND_VERSION_STATUS_RETRY 0x04 #define GB_FW_BACKEND_VERSION_STATUS_FAIL_INT 0x05 /* firmware management interface firmware version request has no payload */ struct gb_fw_mgmt_interface_fw_version_response { __u8 firmware_tag[GB_FIRMWARE_TAG_MAX_SIZE]; __le16 major; __le16 minor; } __packed; /* firmware management load and validate firmware request/response */ struct gb_fw_mgmt_load_and_validate_fw_request { __u8 request_id; __u8 load_method; __u8 firmware_tag[GB_FIRMWARE_TAG_MAX_SIZE]; } __packed; /* firmware management load and validate firmware response has no payload*/ /* firmware management loaded firmware request */ struct gb_fw_mgmt_loaded_fw_request { __u8 request_id; __u8 status; __le16 major; __le16 minor; } __packed; /* firmware management loaded firmware response has no payload */ /* firmware management backend firmware version request/response */ struct gb_fw_mgmt_backend_fw_version_request { __u8 firmware_tag[GB_FIRMWARE_TAG_MAX_SIZE]; } __packed; struct gb_fw_mgmt_backend_fw_version_response { __le16 major; __le16 minor; __u8 status; } __packed; /* firmware management backend firmware update request */ struct gb_fw_mgmt_backend_fw_update_request { __u8 request_id; __u8 firmware_tag[GB_FIRMWARE_TAG_MAX_SIZE]; } __packed; /* firmware management backend firmware update response has no payload */ /* firmware management backend firmware updated request */ struct gb_fw_mgmt_backend_fw_updated_request { __u8 request_id; __u8 status; } __packed; /* firmware management backend firmware updated response has no payload */ /* Component Authentication Protocol (CAP) */ /* Request Types */ #define GB_CAP_TYPE_GET_ENDPOINT_UID 0x01 #define GB_CAP_TYPE_GET_IMS_CERTIFICATE 0x02 #define GB_CAP_TYPE_AUTHENTICATE 0x03 /* CAP get endpoint uid request has no payload */ struct gb_cap_get_endpoint_uid_response { __u8 uid[8]; } __packed; /* CAP get endpoint ims certificate request/response */ struct gb_cap_get_ims_certificate_request { __le32 certificate_class; __le32 certificate_id; } __packed; struct gb_cap_get_ims_certificate_response { __u8 result_code; __u8 certificate[0]; } __packed; /* CAP authenticate request/response */ struct gb_cap_authenticate_request { __le32 auth_type; __u8 uid[8]; __u8 challenge[32]; } __packed; struct gb_cap_authenticate_response { __u8 result_code; __u8 response[64]; __u8 signature[0]; } __packed; /* Bootrom Protocol */ /* Version of the Greybus bootrom protocol we support */ #define GB_BOOTROM_VERSION_MAJOR 0x00 #define GB_BOOTROM_VERSION_MINOR 0x01 /* Greybus bootrom request types */ #define GB_BOOTROM_TYPE_VERSION 0x01 #define GB_BOOTROM_TYPE_FIRMWARE_SIZE 0x02 #define GB_BOOTROM_TYPE_GET_FIRMWARE 0x03 #define GB_BOOTROM_TYPE_READY_TO_BOOT 0x04 #define GB_BOOTROM_TYPE_AP_READY 0x05 /* Request with no-payload */ #define GB_BOOTROM_TYPE_GET_VID_PID 0x06 /* Request with no-payload */ /* Greybus bootrom boot stages */ #define GB_BOOTROM_BOOT_STAGE_ONE 0x01 /* Reserved for the boot ROM */ #define GB_BOOTROM_BOOT_STAGE_TWO 0x02 /* Bootrom package to be loaded by the boot ROM */ #define GB_BOOTROM_BOOT_STAGE_THREE 0x03 /* Module personality package loaded by Stage 2 firmware */ /* Greybus bootrom ready to boot status */ #define GB_BOOTROM_BOOT_STATUS_INVALID 0x00 /* Firmware blob could not be validated */ #define GB_BOOTROM_BOOT_STATUS_INSECURE 0x01 /* Firmware blob is valid but insecure */ #define GB_BOOTROM_BOOT_STATUS_SECURE 0x02 /* Firmware blob is valid and secure */ /* Max bootrom data fetch size in bytes */ #define GB_BOOTROM_FETCH_MAX 2000 struct gb_bootrom_version_request { __u8 major; __u8 minor; } __packed; struct gb_bootrom_version_response { __u8 major; __u8 minor; } __packed; /* Bootrom protocol firmware size request/response */ struct gb_bootrom_firmware_size_request { __u8 stage; } __packed; struct gb_bootrom_firmware_size_response { __le32 size; } __packed; /* Bootrom protocol get firmware request/response */ struct gb_bootrom_get_firmware_request { __le32 offset; __le32 size; } __packed; struct gb_bootrom_get_firmware_response { __u8 data[0]; } __packed; /* Bootrom protocol Ready to boot request */ struct gb_bootrom_ready_to_boot_request { __u8 status; } __packed; /* Bootrom protocol Ready to boot response has no payload */ /* Bootrom protocol get VID/PID request has no payload */ struct gb_bootrom_get_vid_pid_response { __le32 vendor_id; __le32 product_id; } __packed; /* Power Supply */ /* Greybus power supply request types */ #define GB_POWER_SUPPLY_TYPE_GET_SUPPLIES 0x02 #define GB_POWER_SUPPLY_TYPE_GET_DESCRIPTION 0x03 #define GB_POWER_SUPPLY_TYPE_GET_PROP_DESCRIPTORS 0x04 #define GB_POWER_SUPPLY_TYPE_GET_PROPERTY 0x05 #define GB_POWER_SUPPLY_TYPE_SET_PROPERTY 0x06 #define GB_POWER_SUPPLY_TYPE_EVENT 0x07 /* Greybus power supply battery technologies types */ #define GB_POWER_SUPPLY_TECH_UNKNOWN 0x0000 #define GB_POWER_SUPPLY_TECH_NiMH 0x0001 #define GB_POWER_SUPPLY_TECH_LION 0x0002 #define GB_POWER_SUPPLY_TECH_LIPO 0x0003 #define GB_POWER_SUPPLY_TECH_LiFe 0x0004 #define GB_POWER_SUPPLY_TECH_NiCd 0x0005 #define GB_POWER_SUPPLY_TECH_LiMn 0x0006 /* Greybus power supply types */ #define GB_POWER_SUPPLY_UNKNOWN_TYPE 0x0000 #define GB_POWER_SUPPLY_BATTERY_TYPE 0x0001 #define GB_POWER_SUPPLY_UPS_TYPE 0x0002 #define GB_POWER_SUPPLY_MAINS_TYPE 0x0003 #define GB_POWER_SUPPLY_USB_TYPE 0x0004 #define GB_POWER_SUPPLY_USB_DCP_TYPE 0x0005 #define GB_POWER_SUPPLY_USB_CDP_TYPE 0x0006 #define GB_POWER_SUPPLY_USB_ACA_TYPE 0x0007 /* Greybus power supply health values */ #define GB_POWER_SUPPLY_HEALTH_UNKNOWN 0x0000 #define GB_POWER_SUPPLY_HEALTH_GOOD 0x0001 #define GB_POWER_SUPPLY_HEALTH_OVERHEAT 0x0002 #define GB_POWER_SUPPLY_HEALTH_DEAD 0x0003 #define GB_POWER_SUPPLY_HEALTH_OVERVOLTAGE 0x0004 #define GB_POWER_SUPPLY_HEALTH_UNSPEC_FAILURE 0x0005 #define GB_POWER_SUPPLY_HEALTH_COLD 0x0006 #define GB_POWER_SUPPLY_HEALTH_WATCHDOG_TIMER_EXPIRE 0x0007 #define GB_POWER_SUPPLY_HEALTH_SAFETY_TIMER_EXPIRE 0x0008 /* Greybus power supply status values */ #define GB_POWER_SUPPLY_STATUS_UNKNOWN 0x0000 #define GB_POWER_SUPPLY_STATUS_CHARGING 0x0001 #define GB_POWER_SUPPLY_STATUS_DISCHARGING 0x0002 #define GB_POWER_SUPPLY_STATUS_NOT_CHARGING 0x0003 #define GB_POWER_SUPPLY_STATUS_FULL 0x0004 /* Greybus power supply capacity level values */ #define GB_POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN 0x0000 #define GB_POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL 0x0001 #define GB_POWER_SUPPLY_CAPACITY_LEVEL_LOW 0x0002 #define GB_POWER_SUPPLY_CAPACITY_LEVEL_NORMAL 0x0003 #define GB_POWER_SUPPLY_CAPACITY_LEVEL_HIGH 0x0004 #define GB_POWER_SUPPLY_CAPACITY_LEVEL_FULL 0x0005 /* Greybus power supply scope values */ #define GB_POWER_SUPPLY_SCOPE_UNKNOWN 0x0000 #define GB_POWER_SUPPLY_SCOPE_SYSTEM 0x0001 #define GB_POWER_SUPPLY_SCOPE_DEVICE 0x0002 struct gb_power_supply_get_supplies_response { __u8 supplies_count; } __packed; struct gb_power_supply_get_description_request { __u8 psy_id; } __packed; struct gb_power_supply_get_description_response { __u8 manufacturer[32]; __u8 model[32]; __u8 serial_number[32]; __le16 type; __u8 properties_count; } __packed; struct gb_power_supply_props_desc { __u8 property; #define GB_POWER_SUPPLY_PROP_STATUS 0x00 #define GB_POWER_SUPPLY_PROP_CHARGE_TYPE 0x01 #define GB_POWER_SUPPLY_PROP_HEALTH 0x02 #define GB_POWER_SUPPLY_PROP_PRESENT 0x03 #define GB_POWER_SUPPLY_PROP_ONLINE 0x04 #define GB_POWER_SUPPLY_PROP_AUTHENTIC 0x05 #define GB_POWER_SUPPLY_PROP_TECHNOLOGY 0x06 #define GB_POWER_SUPPLY_PROP_CYCLE_COUNT 0x07 #define GB_POWER_SUPPLY_PROP_VOLTAGE_MAX 0x08 #define GB_POWER_SUPPLY_PROP_VOLTAGE_MIN 0x09 #define GB_POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN 0x0A #define GB_POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN 0x0B #define GB_POWER_SUPPLY_PROP_VOLTAGE_NOW 0x0C #define GB_POWER_SUPPLY_PROP_VOLTAGE_AVG 0x0D #define GB_POWER_SUPPLY_PROP_VOLTAGE_OCV 0x0E #define GB_POWER_SUPPLY_PROP_VOLTAGE_BOOT 0x0F #define GB_POWER_SUPPLY_PROP_CURRENT_MAX 0x10 #define GB_POWER_SUPPLY_PROP_CURRENT_NOW 0x11 #define GB_POWER_SUPPLY_PROP_CURRENT_AVG 0x12 #define GB_POWER_SUPPLY_PROP_CURRENT_BOOT 0x13 #define GB_POWER_SUPPLY_PROP_POWER_NOW 0x14 #define GB_POWER_SUPPLY_PROP_POWER_AVG 0x15 #define GB_POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN 0x16 #define GB_POWER_SUPPLY_PROP_CHARGE_EMPTY_DESIGN 0x17 #define GB_POWER_SUPPLY_PROP_CHARGE_FULL 0x18 #define GB_POWER_SUPPLY_PROP_CHARGE_EMPTY 0x19 #define GB_POWER_SUPPLY_PROP_CHARGE_NOW 0x1A #define GB_POWER_SUPPLY_PROP_CHARGE_AVG 0x1B #define GB_POWER_SUPPLY_PROP_CHARGE_COUNTER 0x1C #define GB_POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT 0x1D #define GB_POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX 0x1E #define GB_POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE 0x1F #define GB_POWER_SUPPLY_PROP_CONSTANT_CHARGE_VOLTAGE_MAX 0x20 #define GB_POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT 0x21 #define GB_POWER_SUPPLY_PROP_CHARGE_CONTROL_LIMIT_MAX 0x22 #define GB_POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT 0x23 #define GB_POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN 0x24 #define GB_POWER_SUPPLY_PROP_ENERGY_EMPTY_DESIGN 0x25 #define GB_POWER_SUPPLY_PROP_ENERGY_FULL 0x26 #define GB_POWER_SUPPLY_PROP_ENERGY_EMPTY 0x27 #define GB_POWER_SUPPLY_PROP_ENERGY_NOW 0x28 #define GB_POWER_SUPPLY_PROP_ENERGY_AVG 0x29 #define GB_POWER_SUPPLY_PROP_CAPACITY 0x2A #define GB_POWER_SUPPLY_PROP_CAPACITY_ALERT_MIN 0x2B #define GB_POWER_SUPPLY_PROP_CAPACITY_ALERT_MAX 0x2C #define GB_POWER_SUPPLY_PROP_CAPACITY_LEVEL 0x2D #define GB_POWER_SUPPLY_PROP_TEMP 0x2E #define GB_POWER_SUPPLY_PROP_TEMP_MAX 0x2F #define GB_POWER_SUPPLY_PROP_TEMP_MIN 0x30 #define GB_POWER_SUPPLY_PROP_TEMP_ALERT_MIN 0x31 #define GB_POWER_SUPPLY_PROP_TEMP_ALERT_MAX 0x32 #define GB_POWER_SUPPLY_PROP_TEMP_AMBIENT 0x33 #define GB_POWER_SUPPLY_PROP_TEMP_AMBIENT_ALERT_MIN 0x34 #define GB_POWER_SUPPLY_PROP_TEMP_AMBIENT_ALERT_MAX 0x35 #define GB_POWER_SUPPLY_PROP_TIME_TO_EMPTY_NOW 0x36 #define GB_POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG 0x37 #define GB_POWER_SUPPLY_PROP_TIME_TO_FULL_NOW 0x38 #define GB_POWER_SUPPLY_PROP_TIME_TO_FULL_AVG 0x39 #define GB_POWER_SUPPLY_PROP_TYPE 0x3A #define GB_POWER_SUPPLY_PROP_SCOPE 0x3B #define GB_POWER_SUPPLY_PROP_CHARGE_TERM_CURRENT 0x3C #define GB_POWER_SUPPLY_PROP_CALIBRATE 0x3D __u8 is_writeable; } __packed; struct gb_power_supply_get_property_descriptors_request { __u8 psy_id; } __packed; struct gb_power_supply_get_property_descriptors_response { __u8 properties_count; struct gb_power_supply_props_desc props[]; } __packed; struct gb_power_supply_get_property_request { __u8 psy_id; __u8 property; } __packed; struct gb_power_supply_get_property_response { __le32 prop_val; }; struct gb_power_supply_set_property_request { __u8 psy_id; __u8 property; __le32 prop_val; } __packed; struct gb_power_supply_event_request { __u8 psy_id; __u8 event; #define GB_POWER_SUPPLY_UPDATE 0x01 } __packed; /* HID */ /* Greybus HID operation types */ #define GB_HID_TYPE_GET_DESC 0x02 #define GB_HID_TYPE_GET_REPORT_DESC 0x03 #define GB_HID_TYPE_PWR_ON 0x04 #define GB_HID_TYPE_PWR_OFF 0x05 #define GB_HID_TYPE_GET_REPORT 0x06 #define GB_HID_TYPE_SET_REPORT 0x07 #define GB_HID_TYPE_IRQ_EVENT 0x08 /* Report type */ #define GB_HID_INPUT_REPORT 0 #define GB_HID_OUTPUT_REPORT 1 #define GB_HID_FEATURE_REPORT 2 /* Different request/response structures */ /* HID get descriptor response */ struct gb_hid_desc_response { __u8 bLength; __le16 wReportDescLength; __le16 bcdHID; __le16 wProductID; __le16 wVendorID; __u8 bCountryCode; } __packed; /* HID get report request/response */ struct gb_hid_get_report_request { __u8 report_type; __u8 report_id; } __packed; /* HID set report request */ struct gb_hid_set_report_request { __u8 report_type; __u8 report_id; __u8 report[0]; } __packed; /* HID input report request, via interrupt pipe */ struct gb_hid_input_report_request { __u8 report[0]; } __packed; /* I2C */ /* Greybus i2c request types */ #define GB_I2C_TYPE_FUNCTIONALITY 0x02 #define GB_I2C_TYPE_TRANSFER 0x05 /* functionality request has no payload */ struct gb_i2c_functionality_response { __le32 functionality; } __packed; /* * Outgoing data immediately follows the op count and ops array. * The data for each write (master -> slave) op in the array is sent * in order, with no (e.g. pad) bytes separating them. * * Short reads cause the entire transfer request to fail So response * payload consists only of bytes read, and the number of bytes is * exactly what was specified in the corresponding op. Like * outgoing data, the incoming data is in order and contiguous. */ struct gb_i2c_transfer_op { __le16 addr; __le16 flags; __le16 size; } __packed; struct gb_i2c_transfer_request { __le16 op_count; struct gb_i2c_transfer_op ops[0]; /* op_count of these */ } __packed; struct gb_i2c_transfer_response { __u8 data[0]; /* inbound data */ } __packed; /* GPIO */ /* Greybus GPIO request types */ #define GB_GPIO_TYPE_LINE_COUNT 0x02 #define GB_GPIO_TYPE_ACTIVATE 0x03 #define GB_GPIO_TYPE_DEACTIVATE 0x04 #define GB_GPIO_TYPE_GET_DIRECTION 0x05 #define GB_GPIO_TYPE_DIRECTION_IN 0x06 #define GB_GPIO_TYPE_DIRECTION_OUT 0x07 #define GB_GPIO_TYPE_GET_VALUE 0x08 #define GB_GPIO_TYPE_SET_VALUE 0x09 #define GB_GPIO_TYPE_SET_DEBOUNCE 0x0a #define GB_GPIO_TYPE_IRQ_TYPE 0x0b #define GB_GPIO_TYPE_IRQ_MASK 0x0c #define GB_GPIO_TYPE_IRQ_UNMASK 0x0d #define GB_GPIO_TYPE_IRQ_EVENT 0x0e #define GB_GPIO_IRQ_TYPE_NONE 0x00 #define GB_GPIO_IRQ_TYPE_EDGE_RISING 0x01 #define GB_GPIO_IRQ_TYPE_EDGE_FALLING 0x02 #define GB_GPIO_IRQ_TYPE_EDGE_BOTH 0x03 #define GB_GPIO_IRQ_TYPE_LEVEL_HIGH 0x04 #define GB_GPIO_IRQ_TYPE_LEVEL_LOW 0x08 /* line count request has no payload */ struct gb_gpio_line_count_response { __u8 count; } __packed; struct gb_gpio_activate_request { __u8 which; } __packed; /* activate response has no payload */ struct gb_gpio_deactivate_request { __u8 which; } __packed; /* deactivate response has no payload */ struct gb_gpio_get_direction_request { __u8 which; } __packed; struct gb_gpio_get_direction_response { __u8 direction; } __packed; struct gb_gpio_direction_in_request { __u8 which; } __packed; /* direction in response has no payload */ struct gb_gpio_direction_out_request { __u8 which; __u8 value; } __packed; /* direction out response has no payload */ struct gb_gpio_get_value_request { __u8 which; } __packed; struct gb_gpio_get_value_response { __u8 value; } __packed; struct gb_gpio_set_value_request { __u8 which; __u8 value; } __packed; /* set value response has no payload */ struct gb_gpio_set_debounce_request { __u8 which; __le16 usec; } __packed; /* debounce response has no payload */ struct gb_gpio_irq_type_request { __u8 which; __u8 type; } __packed; /* irq type response has no payload */ struct gb_gpio_irq_mask_request { __u8 which; } __packed; /* irq mask response has no payload */ struct gb_gpio_irq_unmask_request { __u8 which; } __packed; /* irq unmask response has no payload */ /* irq event requests originate on another module and are handled on the AP */ struct gb_gpio_irq_event_request { __u8 which; } __packed; /* irq event has no response */ /* PWM */ /* Greybus PWM operation types */ #define GB_PWM_TYPE_PWM_COUNT 0x02 #define GB_PWM_TYPE_ACTIVATE 0x03 #define GB_PWM_TYPE_DEACTIVATE 0x04 #define GB_PWM_TYPE_CONFIG 0x05 #define GB_PWM_TYPE_POLARITY 0x06 #define GB_PWM_TYPE_ENABLE 0x07 #define GB_PWM_TYPE_DISABLE 0x08 /* pwm count request has no payload */ struct gb_pwm_count_response { __u8 count; } __packed; struct gb_pwm_activate_request { __u8 which; } __packed; struct gb_pwm_deactivate_request { __u8 which; } __packed; struct gb_pwm_config_request { __u8 which; __le32 duty; __le32 period; } __packed; struct gb_pwm_polarity_request { __u8 which; __u8 polarity; } __packed; struct gb_pwm_enable_request { __u8 which; } __packed; struct gb_pwm_disable_request { __u8 which; } __packed; /* SPI */ /* Should match up with modes in linux/spi/spi.h */ #define GB_SPI_MODE_CPHA 0x01 /* clock phase */ #define GB_SPI_MODE_CPOL 0x02 /* clock polarity */ #define GB_SPI_MODE_MODE_0 (0|0) /* (original MicroWire) */ #define GB_SPI_MODE_MODE_1 (0|GB_SPI_MODE_CPHA) #define GB_SPI_MODE_MODE_2 (GB_SPI_MODE_CPOL|0) #define GB_SPI_MODE_MODE_3 (GB_SPI_MODE_CPOL|GB_SPI_MODE_CPHA) #define GB_SPI_MODE_CS_HIGH 0x04 /* chipselect active high? */ #define GB_SPI_MODE_LSB_FIRST 0x08 /* per-word bits-on-wire */ #define GB_SPI_MODE_3WIRE 0x10 /* SI/SO signals shared */ #define GB_SPI_MODE_LOOP 0x20 /* loopback mode */ #define GB_SPI_MODE_NO_CS 0x40 /* 1 dev/bus, no chipselect */ #define GB_SPI_MODE_READY 0x80 /* slave pulls low to pause */ /* Should match up with flags in linux/spi/spi.h */ #define GB_SPI_FLAG_HALF_DUPLEX BIT(0) /* can't do full duplex */ #define GB_SPI_FLAG_NO_RX BIT(1) /* can't do buffer read */ #define GB_SPI_FLAG_NO_TX BIT(2) /* can't do buffer write */ /* Greybus spi operation types */ #define GB_SPI_TYPE_MASTER_CONFIG 0x02 #define GB_SPI_TYPE_DEVICE_CONFIG 0x03 #define GB_SPI_TYPE_TRANSFER 0x04 /* mode request has no payload */ struct gb_spi_master_config_response { __le32 bits_per_word_mask; __le32 min_speed_hz; __le32 max_speed_hz; __le16 mode; __le16 flags; __u8 num_chipselect; } __packed; struct gb_spi_device_config_request { __u8 chip_select; } __packed; struct gb_spi_device_config_response { __le16 mode; __u8 bits_per_word; __le32 max_speed_hz; __u8 device_type; #define GB_SPI_SPI_DEV 0x00 #define GB_SPI_SPI_NOR 0x01 #define GB_SPI_SPI_MODALIAS 0x02 __u8 name[32]; } __packed; /** * struct gb_spi_transfer - a read/write buffer pair * @speed_hz: Select a speed other than the device default for this transfer. If * 0 the default (from @spi_device) is used. * @len: size of rx and tx buffers (in bytes) * @delay_usecs: microseconds to delay after this transfer before (optionally) * changing the chipselect status, then starting the next transfer or * completing this spi_message. * @cs_change: affects chipselect after this transfer completes * @bits_per_word: select a bits_per_word other than the device default for this * transfer. If 0 the default (from @spi_device) is used. */ struct gb_spi_transfer { __le32 speed_hz; __le32 len; __le16 delay_usecs; __u8 cs_change; __u8 bits_per_word; __u8 xfer_flags; #define GB_SPI_XFER_READ 0x01 #define GB_SPI_XFER_WRITE 0x02 #define GB_SPI_XFER_INPROGRESS 0x04 } __packed; struct gb_spi_transfer_request { __u8 chip_select; /* of the spi device */ __u8 mode; /* of the spi device */ __le16 count; struct gb_spi_transfer transfers[0]; /* count of these */ } __packed; struct gb_spi_transfer_response { __u8 data[0]; /* inbound data */ } __packed; /* Version of the Greybus SVC protocol we support */ #define GB_SVC_VERSION_MAJOR 0x00 #define GB_SVC_VERSION_MINOR 0x01 /* Greybus SVC request types */ #define GB_SVC_TYPE_PROTOCOL_VERSION 0x01 #define GB_SVC_TYPE_SVC_HELLO 0x02 #define GB_SVC_TYPE_INTF_DEVICE_ID 0x03 #define GB_SVC_TYPE_INTF_RESET 0x06 #define GB_SVC_TYPE_CONN_CREATE 0x07 #define GB_SVC_TYPE_CONN_DESTROY 0x08 #define GB_SVC_TYPE_DME_PEER_GET 0x09 #define GB_SVC_TYPE_DME_PEER_SET 0x0a #define GB_SVC_TYPE_ROUTE_CREATE 0x0b #define GB_SVC_TYPE_ROUTE_DESTROY 0x0c #define GB_SVC_TYPE_TIMESYNC_ENABLE 0x0d #define GB_SVC_TYPE_TIMESYNC_DISABLE 0x0e #define GB_SVC_TYPE_TIMESYNC_AUTHORITATIVE 0x0f #define GB_SVC_TYPE_INTF_SET_PWRM 0x10 #define GB_SVC_TYPE_INTF_EJECT 0x11 #define GB_SVC_TYPE_PING 0x13 #define GB_SVC_TYPE_PWRMON_RAIL_COUNT_GET 0x14 #define GB_SVC_TYPE_PWRMON_RAIL_NAMES_GET 0x15 #define GB_SVC_TYPE_PWRMON_SAMPLE_GET 0x16 #define GB_SVC_TYPE_PWRMON_INTF_SAMPLE_GET 0x17 #define GB_SVC_TYPE_TIMESYNC_WAKE_PINS_ACQUIRE 0x18 #define GB_SVC_TYPE_TIMESYNC_WAKE_PINS_RELEASE 0x19 #define GB_SVC_TYPE_TIMESYNC_PING 0x1a #define GB_SVC_TYPE_MODULE_INSERTED 0x1f #define GB_SVC_TYPE_MODULE_REMOVED 0x20 #define GB_SVC_TYPE_INTF_VSYS_ENABLE 0x21 #define GB_SVC_TYPE_INTF_VSYS_DISABLE 0x22 #define GB_SVC_TYPE_INTF_REFCLK_ENABLE 0x23 #define GB_SVC_TYPE_INTF_REFCLK_DISABLE 0x24 #define GB_SVC_TYPE_INTF_UNIPRO_ENABLE 0x25 #define GB_SVC_TYPE_INTF_UNIPRO_DISABLE 0x26 #define GB_SVC_TYPE_INTF_ACTIVATE 0x27 #define GB_SVC_TYPE_INTF_RESUME 0x28 #define GB_SVC_TYPE_INTF_MAILBOX_EVENT 0x29 #define GB_SVC_TYPE_INTF_OOPS 0x2a /* Greybus SVC protocol status values */ #define GB_SVC_OP_SUCCESS 0x00 #define GB_SVC_OP_UNKNOWN_ERROR 0x01 #define GB_SVC_INTF_NOT_DETECTED 0x02 #define GB_SVC_INTF_NO_UPRO_LINK 0x03 #define GB_SVC_INTF_UPRO_NOT_DOWN 0x04 #define GB_SVC_INTF_UPRO_NOT_HIBERNATED 0x05 #define GB_SVC_INTF_NO_V_SYS 0x06 #define GB_SVC_INTF_V_CHG 0x07 #define GB_SVC_INTF_WAKE_BUSY 0x08 #define GB_SVC_INTF_NO_REFCLK 0x09 #define GB_SVC_INTF_RELEASING 0x0a #define GB_SVC_INTF_NO_ORDER 0x0b #define GB_SVC_INTF_MBOX_SET 0x0c #define GB_SVC_INTF_BAD_MBOX 0x0d #define GB_SVC_INTF_OP_TIMEOUT 0x0e #define GB_SVC_PWRMON_OP_NOT_PRESENT 0x0f struct gb_svc_version_request { __u8 major; __u8 minor; } __packed; struct gb_svc_version_response { __u8 major; __u8 minor; } __packed; /* SVC protocol hello request */ struct gb_svc_hello_request { __le16 endo_id; __u8 interface_id; } __packed; /* hello response has no payload */ struct gb_svc_intf_device_id_request { __u8 intf_id; __u8 device_id; } __packed; /* device id response has no payload */ struct gb_svc_intf_reset_request { __u8 intf_id; } __packed; /* interface reset response has no payload */ struct gb_svc_intf_eject_request { __u8 intf_id; } __packed; /* interface eject response has no payload */ struct gb_svc_conn_create_request { __u8 intf1_id; __le16 cport1_id; __u8 intf2_id; __le16 cport2_id; __u8 tc; __u8 flags; } __packed; /* connection create response has no payload */ struct gb_svc_conn_destroy_request { __u8 intf1_id; __le16 cport1_id; __u8 intf2_id; __le16 cport2_id; } __packed; /* connection destroy response has no payload */ struct gb_svc_dme_peer_get_request { __u8 intf_id; __le16 attr; __le16 selector; } __packed; struct gb_svc_dme_peer_get_response { __le16 result_code; __le32 attr_value; } __packed; struct gb_svc_dme_peer_set_request { __u8 intf_id; __le16 attr; __le16 selector; __le32 value; } __packed; struct gb_svc_dme_peer_set_response { __le16 result_code; } __packed; /* Greybus init-status values, currently retrieved using DME peer gets. */ #define GB_INIT_SPI_BOOT_STARTED 0x02 #define GB_INIT_TRUSTED_SPI_BOOT_FINISHED 0x03 #define GB_INIT_UNTRUSTED_SPI_BOOT_FINISHED 0x04 #define GB_INIT_BOOTROM_UNIPRO_BOOT_STARTED 0x06 #define GB_INIT_BOOTROM_FALLBACK_UNIPRO_BOOT_STARTED 0x09 #define GB_INIT_S2_LOADER_BOOT_STARTED 0x0D struct gb_svc_route_create_request { __u8 intf1_id; __u8 dev1_id; __u8 intf2_id; __u8 dev2_id; } __packed; /* route create response has no payload */ struct gb_svc_route_destroy_request { __u8 intf1_id; __u8 intf2_id; } __packed; /* route destroy response has no payload */ /* used for svc_intf_vsys_{enable,disable} */ struct gb_svc_intf_vsys_request { __u8 intf_id; } __packed; struct gb_svc_intf_vsys_response { __u8 result_code; #define GB_SVC_INTF_VSYS_OK 0x00 /* 0x01 is reserved */ #define GB_SVC_INTF_VSYS_FAIL 0x02 } __packed; /* used for svc_intf_refclk_{enable,disable} */ struct gb_svc_intf_refclk_request { __u8 intf_id; } __packed; struct gb_svc_intf_refclk_response { __u8 result_code; #define GB_SVC_INTF_REFCLK_OK 0x00 /* 0x01 is reserved */ #define GB_SVC_INTF_REFCLK_FAIL 0x02 } __packed; /* used for svc_intf_unipro_{enable,disable} */ struct gb_svc_intf_unipro_request { __u8 intf_id; } __packed; struct gb_svc_intf_unipro_response { __u8 result_code; #define GB_SVC_INTF_UNIPRO_OK 0x00 /* 0x01 is reserved */ #define GB_SVC_INTF_UNIPRO_FAIL 0x02 #define GB_SVC_INTF_UNIPRO_NOT_OFF 0x03 } __packed; struct gb_svc_timesync_enable_request { __u8 count; __le64 frame_time; __le32 strobe_delay; __le32 refclk; } __packed; /* timesync enable response has no payload */ /* timesync authoritative request has no payload */ struct gb_svc_timesync_authoritative_response { __le64 frame_time[GB_TIMESYNC_MAX_STROBES]; }; struct gb_svc_timesync_wake_pins_acquire_request { __le32 strobe_mask; }; /* timesync wake pins acquire response has no payload */ /* timesync wake pins release request has no payload */ /* timesync wake pins release response has no payload */ /* timesync svc ping request has no payload */ struct gb_svc_timesync_ping_response { __le64 frame_time; } __packed; #define GB_SVC_UNIPRO_FAST_MODE 0x01 #define GB_SVC_UNIPRO_SLOW_MODE 0x02 #define GB_SVC_UNIPRO_FAST_AUTO_MODE 0x04 #define GB_SVC_UNIPRO_SLOW_AUTO_MODE 0x05 #define GB_SVC_UNIPRO_MODE_UNCHANGED 0x07 #define GB_SVC_UNIPRO_HIBERNATE_MODE 0x11 #define GB_SVC_UNIPRO_OFF_MODE 0x12 #define GB_SVC_SMALL_AMPLITUDE 0x01 #define GB_SVC_LARGE_AMPLITUDE 0x02 #define GB_SVC_NO_DE_EMPHASIS 0x00 #define GB_SVC_SMALL_DE_EMPHASIS 0x01 #define GB_SVC_LARGE_DE_EMPHASIS 0x02 #define GB_SVC_PWRM_RXTERMINATION 0x01 #define GB_SVC_PWRM_TXTERMINATION 0x02 #define GB_SVC_PWRM_LINE_RESET 0x04 #define GB_SVC_PWRM_SCRAMBLING 0x20 #define GB_SVC_PWRM_QUIRK_HSSER 0x00000001 #define GB_SVC_UNIPRO_HS_SERIES_A 0x01 #define GB_SVC_UNIPRO_HS_SERIES_B 0x02 #define GB_SVC_SETPWRM_PWR_OK 0x00 #define GB_SVC_SETPWRM_PWR_LOCAL 0x01 #define GB_SVC_SETPWRM_PWR_REMOTE 0x02 #define GB_SVC_SETPWRM_PWR_BUSY 0x03 #define GB_SVC_SETPWRM_PWR_ERROR_CAP 0x04 #define GB_SVC_SETPWRM_PWR_FATAL_ERROR 0x05 struct gb_svc_l2_timer_cfg { __le16 tsb_fc0_protection_timeout; __le16 tsb_tc0_replay_timeout; __le16 tsb_afc0_req_timeout; __le16 tsb_fc1_protection_timeout; __le16 tsb_tc1_replay_timeout; __le16 tsb_afc1_req_timeout; __le16 reserved_for_tc2[3]; __le16 reserved_for_tc3[3]; } __packed; struct gb_svc_intf_set_pwrm_request { __u8 intf_id; __u8 hs_series; __u8 tx_mode; __u8 tx_gear; __u8 tx_nlanes; __u8 tx_amplitude; __u8 tx_hs_equalizer; __u8 rx_mode; __u8 rx_gear; __u8 rx_nlanes; __u8 flags; __le32 quirks; struct gb_svc_l2_timer_cfg local_l2timerdata, remote_l2timerdata; } __packed; struct gb_svc_intf_set_pwrm_response { __u8 result_code; } __packed; struct gb_svc_key_event_request { __le16 key_code; #define GB_KEYCODE_ARA 0x00 __u8 key_event; #define GB_SVC_KEY_RELEASED 0x00 #define GB_SVC_KEY_PRESSED 0x01 } __packed; #define GB_SVC_PWRMON_MAX_RAIL_COUNT 254 struct gb_svc_pwrmon_rail_count_get_response { __u8 rail_count; } __packed; #define GB_SVC_PWRMON_RAIL_NAME_BUFSIZE 32 struct gb_svc_pwrmon_rail_names_get_response { __u8 status; __u8 name[0][GB_SVC_PWRMON_RAIL_NAME_BUFSIZE]; } __packed; #define GB_SVC_PWRMON_TYPE_CURR 0x01 #define GB_SVC_PWRMON_TYPE_VOL 0x02 #define GB_SVC_PWRMON_TYPE_PWR 0x03 #define GB_SVC_PWRMON_GET_SAMPLE_OK 0x00 #define GB_SVC_PWRMON_GET_SAMPLE_INVAL 0x01 #define GB_SVC_PWRMON_GET_SAMPLE_NOSUPP 0x02 #define GB_SVC_PWRMON_GET_SAMPLE_HWERR 0x03 struct gb_svc_pwrmon_sample_get_request { __u8 rail_id; __u8 measurement_type; } __packed; struct gb_svc_pwrmon_sample_get_response { __u8 result; __le32 measurement; } __packed; struct gb_svc_pwrmon_intf_sample_get_request { __u8 intf_id; __u8 measurement_type; } __packed; struct gb_svc_pwrmon_intf_sample_get_response { __u8 result; __le32 measurement; } __packed; #define GB_SVC_MODULE_INSERTED_FLAG_NO_PRIMARY 0x0001 struct gb_svc_module_inserted_request { __u8 primary_intf_id; __u8 intf_count; __le16 flags; } __packed; /* module_inserted response has no payload */ struct gb_svc_module_removed_request { __u8 primary_intf_id; } __packed; /* module_removed response has no payload */ struct gb_svc_intf_activate_request { __u8 intf_id; } __packed; #define GB_SVC_INTF_TYPE_UNKNOWN 0x00 #define GB_SVC_INTF_TYPE_DUMMY 0x01 #define GB_SVC_INTF_TYPE_UNIPRO 0x02 #define GB_SVC_INTF_TYPE_GREYBUS 0x03 struct gb_svc_intf_activate_response { __u8 status; __u8 intf_type; } __packed; struct gb_svc_intf_resume_request { __u8 intf_id; } __packed; struct gb_svc_intf_resume_response { __u8 status; } __packed; #define GB_SVC_INTF_MAILBOX_NONE 0x00 #define GB_SVC_INTF_MAILBOX_AP 0x01 #define GB_SVC_INTF_MAILBOX_GREYBUS 0x02 struct gb_svc_intf_mailbox_event_request { __u8 intf_id; __le16 result_code; __le32 mailbox; } __packed; /* intf_mailbox_event response has no payload */ struct gb_svc_intf_oops_request { __u8 intf_id; __u8 reason; } __packed; /* intf_oops response has no payload */ /* RAW */ /* Greybus raw request types */ #define GB_RAW_TYPE_SEND 0x02 struct gb_raw_send_request { __le32 len; __u8 data[0]; } __packed; /* UART */ /* Greybus UART operation types */ #define GB_UART_TYPE_SEND_DATA 0x02 #define GB_UART_TYPE_RECEIVE_DATA 0x03 /* Unsolicited data */ #define GB_UART_TYPE_SET_LINE_CODING 0x04 #define GB_UART_TYPE_SET_CONTROL_LINE_STATE 0x05 #define GB_UART_TYPE_SEND_BREAK 0x06 #define GB_UART_TYPE_SERIAL_STATE 0x07 /* Unsolicited data */ #define GB_UART_TYPE_RECEIVE_CREDITS 0x08 #define GB_UART_TYPE_FLUSH_FIFOS 0x09 /* Represents data from AP -> Module */ struct gb_uart_send_data_request { __le16 size; __u8 data[0]; } __packed; /* recv-data-request flags */ #define GB_UART_RECV_FLAG_FRAMING 0x01 /* Framing error */ #define GB_UART_RECV_FLAG_PARITY 0x02 /* Parity error */ #define GB_UART_RECV_FLAG_OVERRUN 0x04 /* Overrun error */ #define GB_UART_RECV_FLAG_BREAK 0x08 /* Break */ /* Represents data from Module -> AP */ struct gb_uart_recv_data_request { __le16 size; __u8 flags; __u8 data[0]; } __packed; struct gb_uart_receive_credits_request { __le16 count; } __packed; struct gb_uart_set_line_coding_request { __le32 rate; __u8 format; #define GB_SERIAL_1_STOP_BITS 0 #define GB_SERIAL_1_5_STOP_BITS 1 #define GB_SERIAL_2_STOP_BITS 2 __u8 parity; #define GB_SERIAL_NO_PARITY 0 #define GB_SERIAL_ODD_PARITY 1 #define GB_SERIAL_EVEN_PARITY 2 #define GB_SERIAL_MARK_PARITY 3 #define GB_SERIAL_SPACE_PARITY 4 __u8 data_bits; __u8 flow_control; #define GB_SERIAL_AUTO_RTSCTS_EN 0x1 } __packed; /* output control lines */ #define GB_UART_CTRL_DTR 0x01 #define GB_UART_CTRL_RTS 0x02 struct gb_uart_set_control_line_state_request { __u8 control; } __packed; struct gb_uart_set_break_request { __u8 state; } __packed; /* input control lines and line errors */ #define GB_UART_CTRL_DCD 0x01 #define GB_UART_CTRL_DSR 0x02 #define GB_UART_CTRL_RI 0x04 struct gb_uart_serial_state_request { __u8 control; } __packed; struct gb_uart_serial_flush_request { __u8 flags; #define GB_SERIAL_FLAG_FLUSH_TRANSMITTER 0x01 #define GB_SERIAL_FLAG_FLUSH_RECEIVER 0x02 } __packed; /* Loopback */ /* Greybus loopback request types */ #define GB_LOOPBACK_TYPE_PING 0x02 #define GB_LOOPBACK_TYPE_TRANSFER 0x03 #define GB_LOOPBACK_TYPE_SINK 0x04 /* * Loopback request/response header format should be identical * to simplify bandwidth and data movement analysis. */ struct gb_loopback_transfer_request { __le32 len; __le32 reserved0; __le32 reserved1; __u8 data[0]; } __packed; struct gb_loopback_transfer_response { __le32 len; __le32 reserved0; __le32 reserved1; __u8 data[0]; } __packed; /* SDIO */ /* Greybus SDIO operation types */ #define GB_SDIO_TYPE_GET_CAPABILITIES 0x02 #define GB_SDIO_TYPE_SET_IOS 0x03 #define GB_SDIO_TYPE_COMMAND 0x04 #define GB_SDIO_TYPE_TRANSFER 0x05 #define GB_SDIO_TYPE_EVENT 0x06 /* get caps response: request has no payload */ struct gb_sdio_get_caps_response { __le32 caps; #define GB_SDIO_CAP_NONREMOVABLE 0x00000001 #define GB_SDIO_CAP_4_BIT_DATA 0x00000002 #define GB_SDIO_CAP_8_BIT_DATA 0x00000004 #define GB_SDIO_CAP_MMC_HS 0x00000008 #define GB_SDIO_CAP_SD_HS 0x00000010 #define GB_SDIO_CAP_ERASE 0x00000020 #define GB_SDIO_CAP_1_2V_DDR 0x00000040 #define GB_SDIO_CAP_1_8V_DDR 0x00000080 #define GB_SDIO_CAP_POWER_OFF_CARD 0x00000100 #define GB_SDIO_CAP_UHS_SDR12 0x00000200 #define GB_SDIO_CAP_UHS_SDR25 0x00000400 #define GB_SDIO_CAP_UHS_SDR50 0x00000800 #define GB_SDIO_CAP_UHS_SDR104 0x00001000 #define GB_SDIO_CAP_UHS_DDR50 0x00002000 #define GB_SDIO_CAP_DRIVER_TYPE_A 0x00004000 #define GB_SDIO_CAP_DRIVER_TYPE_C 0x00008000 #define GB_SDIO_CAP_DRIVER_TYPE_D 0x00010000 #define GB_SDIO_CAP_HS200_1_2V 0x00020000 #define GB_SDIO_CAP_HS200_1_8V 0x00040000 #define GB_SDIO_CAP_HS400_1_2V 0x00080000 #define GB_SDIO_CAP_HS400_1_8V 0x00100000 /* see possible values below at vdd */ __le32 ocr; __le32 f_min; __le32 f_max; __le16 max_blk_count; __le16 max_blk_size; } __packed; /* set ios request: response has no payload */ struct gb_sdio_set_ios_request { __le32 clock; __le32 vdd; #define GB_SDIO_VDD_165_195 0x00000001 #define GB_SDIO_VDD_20_21 0x00000002 #define GB_SDIO_VDD_21_22 0x00000004 #define GB_SDIO_VDD_22_23 0x00000008 #define GB_SDIO_VDD_23_24 0x00000010 #define GB_SDIO_VDD_24_25 0x00000020 #define GB_SDIO_VDD_25_26 0x00000040 #define GB_SDIO_VDD_26_27 0x00000080 #define GB_SDIO_VDD_27_28 0x00000100 #define GB_SDIO_VDD_28_29 0x00000200 #define GB_SDIO_VDD_29_30 0x00000400 #define GB_SDIO_VDD_30_31 0x00000800 #define GB_SDIO_VDD_31_32 0x00001000 #define GB_SDIO_VDD_32_33 0x00002000 #define GB_SDIO_VDD_33_34 0x00004000 #define GB_SDIO_VDD_34_35 0x00008000 #define GB_SDIO_VDD_35_36 0x00010000 __u8 bus_mode; #define GB_SDIO_BUSMODE_OPENDRAIN 0x00 #define GB_SDIO_BUSMODE_PUSHPULL 0x01 __u8 power_mode; #define GB_SDIO_POWER_OFF 0x00 #define GB_SDIO_POWER_UP 0x01 #define GB_SDIO_POWER_ON 0x02 #define GB_SDIO_POWER_UNDEFINED 0x03 __u8 bus_width; #define GB_SDIO_BUS_WIDTH_1 0x00 #define GB_SDIO_BUS_WIDTH_4 0x02 #define GB_SDIO_BUS_WIDTH_8 0x03 __u8 timing; #define GB_SDIO_TIMING_LEGACY 0x00 #define GB_SDIO_TIMING_MMC_HS 0x01 #define GB_SDIO_TIMING_SD_HS 0x02 #define GB_SDIO_TIMING_UHS_SDR12 0x03 #define GB_SDIO_TIMING_UHS_SDR25 0x04 #define GB_SDIO_TIMING_UHS_SDR50 0x05 #define GB_SDIO_TIMING_UHS_SDR104 0x06 #define GB_SDIO_TIMING_UHS_DDR50 0x07 #define GB_SDIO_TIMING_MMC_DDR52 0x08 #define GB_SDIO_TIMING_MMC_HS200 0x09 #define GB_SDIO_TIMING_MMC_HS400 0x0A __u8 signal_voltage; #define GB_SDIO_SIGNAL_VOLTAGE_330 0x00 #define GB_SDIO_SIGNAL_VOLTAGE_180 0x01 #define GB_SDIO_SIGNAL_VOLTAGE_120 0x02 __u8 drv_type; #define GB_SDIO_SET_DRIVER_TYPE_B 0x00 #define GB_SDIO_SET_DRIVER_TYPE_A 0x01 #define GB_SDIO_SET_DRIVER_TYPE_C 0x02 #define GB_SDIO_SET_DRIVER_TYPE_D 0x03 } __packed; /* command request */ struct gb_sdio_command_request { __u8 cmd; __u8 cmd_flags; #define GB_SDIO_RSP_NONE 0x00 #define GB_SDIO_RSP_PRESENT 0x01 #define GB_SDIO_RSP_136 0x02 #define GB_SDIO_RSP_CRC 0x04 #define GB_SDIO_RSP_BUSY 0x08 #define GB_SDIO_RSP_OPCODE 0x10 __u8 cmd_type; #define GB_SDIO_CMD_AC 0x00 #define GB_SDIO_CMD_ADTC 0x01 #define GB_SDIO_CMD_BC 0x02 #define GB_SDIO_CMD_BCR 0x03 __le32 cmd_arg; __le16 data_blocks; __le16 data_blksz; } __packed; struct gb_sdio_command_response { __le32 resp[4]; } __packed; /* transfer request */ struct gb_sdio_transfer_request { __u8 data_flags; #define GB_SDIO_DATA_WRITE 0x01 #define GB_SDIO_DATA_READ 0x02 #define GB_SDIO_DATA_STREAM 0x04 __le16 data_blocks; __le16 data_blksz; __u8 data[0]; } __packed; struct gb_sdio_transfer_response { __le16 data_blocks; __le16 data_blksz; __u8 data[0]; } __packed; /* event request: generated by module and is defined as unidirectional */ struct gb_sdio_event_request { __u8 event; #define GB_SDIO_CARD_INSERTED 0x01 #define GB_SDIO_CARD_REMOVED 0x02 #define GB_SDIO_WP 0x04 } __packed; /* Camera */ /* Greybus Camera request types */ #define GB_CAMERA_TYPE_CAPABILITIES 0x02 #define GB_CAMERA_TYPE_CONFIGURE_STREAMS 0x03 #define GB_CAMERA_TYPE_CAPTURE 0x04 #define GB_CAMERA_TYPE_FLUSH 0x05 #define GB_CAMERA_TYPE_METADATA 0x06 #define GB_CAMERA_MAX_STREAMS 4 #define GB_CAMERA_MAX_SETTINGS_SIZE 8192 /* Greybus Camera Configure Streams request payload */ struct gb_camera_stream_config_request { __le16 width; __le16 height; __le16 format; __le16 padding; } __packed; struct gb_camera_configure_streams_request { __u8 num_streams; __u8 flags; #define GB_CAMERA_CONFIGURE_STREAMS_TEST_ONLY 0x01 __le16 padding; struct gb_camera_stream_config_request config[0]; } __packed; /* Greybus Camera Configure Streams response payload */ struct gb_camera_stream_config_response { __le16 width; __le16 height; __le16 format; __u8 virtual_channel; __u8 data_type[2]; __le16 max_pkt_size; __u8 padding; __le32 max_size; } __packed; struct gb_camera_configure_streams_response { __u8 num_streams; #define GB_CAMERA_CONFIGURE_STREAMS_ADJUSTED 0x01 __u8 flags; __u8 padding[2]; __le32 data_rate; struct gb_camera_stream_config_response config[0]; }; /* Greybus Camera Capture request payload - response has no payload */ struct gb_camera_capture_request { __le32 request_id; __u8 streams; __u8 padding; __le16 num_frames; __u8 settings[0]; } __packed; /* Greybus Camera Flush response payload - request has no payload */ struct gb_camera_flush_response { __le32 request_id; } __packed; /* Greybus Camera Metadata request payload - operation has no response */ struct gb_camera_metadata_request { __le32 request_id; __le16 frame_number; __u8 stream; __u8 padding; __u8 metadata[0]; } __packed; /* Lights */ /* Greybus Lights request types */ #define GB_LIGHTS_TYPE_GET_LIGHTS 0x02 #define GB_LIGHTS_TYPE_GET_LIGHT_CONFIG 0x03 #define GB_LIGHTS_TYPE_GET_CHANNEL_CONFIG 0x04 #define GB_LIGHTS_TYPE_GET_CHANNEL_FLASH_CONFIG 0x05 #define GB_LIGHTS_TYPE_SET_BRIGHTNESS 0x06 #define GB_LIGHTS_TYPE_SET_BLINK 0x07 #define GB_LIGHTS_TYPE_SET_COLOR 0x08 #define GB_LIGHTS_TYPE_SET_FADE 0x09 #define GB_LIGHTS_TYPE_EVENT 0x0A #define GB_LIGHTS_TYPE_SET_FLASH_INTENSITY 0x0B #define GB_LIGHTS_TYPE_SET_FLASH_STROBE 0x0C #define GB_LIGHTS_TYPE_SET_FLASH_TIMEOUT 0x0D #define GB_LIGHTS_TYPE_GET_FLASH_FAULT 0x0E /* Greybus Light modes */ /* * if you add any specific mode below, update also the * GB_CHANNEL_MODE_DEFINED_RANGE value accordingly */ #define GB_CHANNEL_MODE_NONE 0x00000000 #define GB_CHANNEL_MODE_BATTERY 0x00000001 #define GB_CHANNEL_MODE_POWER 0x00000002 #define GB_CHANNEL_MODE_WIRELESS 0x00000004 #define GB_CHANNEL_MODE_BLUETOOTH 0x00000008 #define GB_CHANNEL_MODE_KEYBOARD 0x00000010 #define GB_CHANNEL_MODE_BUTTONS 0x00000020 #define GB_CHANNEL_MODE_NOTIFICATION 0x00000040 #define GB_CHANNEL_MODE_ATTENTION 0x00000080 #define GB_CHANNEL_MODE_FLASH 0x00000100 #define GB_CHANNEL_MODE_TORCH 0x00000200 #define GB_CHANNEL_MODE_INDICATOR 0x00000400 /* Lights Mode valid bit values */ #define GB_CHANNEL_MODE_DEFINED_RANGE 0x000004FF #define GB_CHANNEL_MODE_VENDOR_RANGE 0x00F00000 /* Greybus Light Channels Flags */ #define GB_LIGHT_CHANNEL_MULTICOLOR 0x00000001 #define GB_LIGHT_CHANNEL_FADER 0x00000002 #define GB_LIGHT_CHANNEL_BLINK 0x00000004 /* get count of lights in module */ struct gb_lights_get_lights_response { __u8 lights_count; } __packed; /* light config request payload */ struct gb_lights_get_light_config_request { __u8 id; } __packed; /* light config response payload */ struct gb_lights_get_light_config_response { __u8 channel_count; __u8 name[32]; } __packed; /* channel config request payload */ struct gb_lights_get_channel_config_request { __u8 light_id; __u8 channel_id; } __packed; /* channel flash config request payload */ struct gb_lights_get_channel_flash_config_request { __u8 light_id; __u8 channel_id; } __packed; /* channel config response payload */ struct gb_lights_get_channel_config_response { __u8 max_brightness; __le32 flags; __le32 color; __u8 color_name[32]; __le32 mode; __u8 mode_name[32]; } __packed; /* channel flash config response payload */ struct gb_lights_get_channel_flash_config_response { __le32 intensity_min_uA; __le32 intensity_max_uA; __le32 intensity_step_uA; __le32 timeout_min_us; __le32 timeout_max_us; __le32 timeout_step_us; } __packed; /* blink request payload: response have no payload */ struct gb_lights_blink_request { __u8 light_id; __u8 channel_id; __le16 time_on_ms; __le16 time_off_ms; } __packed; /* set brightness request payload: response have no payload */ struct gb_lights_set_brightness_request { __u8 light_id; __u8 channel_id; __u8 brightness; } __packed; /* set color request payload: response have no payload */ struct gb_lights_set_color_request { __u8 light_id; __u8 channel_id; __le32 color; } __packed; /* set fade request payload: response have no payload */ struct gb_lights_set_fade_request { __u8 light_id; __u8 channel_id; __u8 fade_in; __u8 fade_out; } __packed; /* event request: generated by module */ struct gb_lights_event_request { __u8 light_id; __u8 event; #define GB_LIGHTS_LIGHT_CONFIG 0x01 } __packed; /* set flash intensity request payload: response have no payload */ struct gb_lights_set_flash_intensity_request { __u8 light_id; __u8 channel_id; __le32 intensity_uA; } __packed; /* set flash strobe state request payload: response have no payload */ struct gb_lights_set_flash_strobe_request { __u8 light_id; __u8 channel_id; __u8 state; } __packed; /* set flash timeout request payload: response have no payload */ struct gb_lights_set_flash_timeout_request { __u8 light_id; __u8 channel_id; __le32 timeout_us; } __packed; /* get flash fault request payload */ struct gb_lights_get_flash_fault_request { __u8 light_id; __u8 channel_id; } __packed; /* get flash fault response payload */ struct gb_lights_get_flash_fault_response { __le32 fault; #define GB_LIGHTS_FLASH_FAULT_OVER_VOLTAGE 0x00000000 #define GB_LIGHTS_FLASH_FAULT_TIMEOUT 0x00000001 #define GB_LIGHTS_FLASH_FAULT_OVER_TEMPERATURE 0x00000002 #define GB_LIGHTS_FLASH_FAULT_SHORT_CIRCUIT 0x00000004 #define GB_LIGHTS_FLASH_FAULT_OVER_CURRENT 0x00000008 #define GB_LIGHTS_FLASH_FAULT_INDICATOR 0x00000010 #define GB_LIGHTS_FLASH_FAULT_UNDER_VOLTAGE 0x00000020 #define GB_LIGHTS_FLASH_FAULT_INPUT_VOLTAGE 0x00000040 #define GB_LIGHTS_FLASH_FAULT_LED_OVER_TEMPERATURE 0x00000080 } __packed; /* Audio */ #define GB_AUDIO_TYPE_GET_TOPOLOGY_SIZE 0x02 #define GB_AUDIO_TYPE_GET_TOPOLOGY 0x03 #define GB_AUDIO_TYPE_GET_CONTROL 0x04 #define GB_AUDIO_TYPE_SET_CONTROL 0x05 #define GB_AUDIO_TYPE_ENABLE_WIDGET 0x06 #define GB_AUDIO_TYPE_DISABLE_WIDGET 0x07 #define GB_AUDIO_TYPE_GET_PCM 0x08 #define GB_AUDIO_TYPE_SET_PCM 0x09 #define GB_AUDIO_TYPE_SET_TX_DATA_SIZE 0x0a /* 0x0b unused */ #define GB_AUDIO_TYPE_ACTIVATE_TX 0x0c #define GB_AUDIO_TYPE_DEACTIVATE_TX 0x0d #define GB_AUDIO_TYPE_SET_RX_DATA_SIZE 0x0e /* 0x0f unused */ #define GB_AUDIO_TYPE_ACTIVATE_RX 0x10 #define GB_AUDIO_TYPE_DEACTIVATE_RX 0x11 #define GB_AUDIO_TYPE_JACK_EVENT 0x12 #define GB_AUDIO_TYPE_BUTTON_EVENT 0x13 #define GB_AUDIO_TYPE_STREAMING_EVENT 0x14 #define GB_AUDIO_TYPE_SEND_DATA 0x15 /* Module must be able to buffer 10ms of audio data, minimum */ #define GB_AUDIO_SAMPLE_BUFFER_MIN_US 10000 #define GB_AUDIO_PCM_NAME_MAX 32 #define AUDIO_DAI_NAME_MAX 32 #define AUDIO_CONTROL_NAME_MAX 32 #define AUDIO_CTL_ELEM_NAME_MAX 44 #define AUDIO_ENUM_NAME_MAX 64 #define AUDIO_WIDGET_NAME_MAX 32 /* See SNDRV_PCM_FMTBIT_* in Linux source */ #define GB_AUDIO_PCM_FMT_S8 BIT(0) #define GB_AUDIO_PCM_FMT_U8 BIT(1) #define GB_AUDIO_PCM_FMT_S16_LE BIT(2) #define GB_AUDIO_PCM_FMT_S16_BE BIT(3) #define GB_AUDIO_PCM_FMT_U16_LE BIT(4) #define GB_AUDIO_PCM_FMT_U16_BE BIT(5) #define GB_AUDIO_PCM_FMT_S24_LE BIT(6) #define GB_AUDIO_PCM_FMT_S24_BE BIT(7) #define GB_AUDIO_PCM_FMT_U24_LE BIT(8) #define GB_AUDIO_PCM_FMT_U24_BE BIT(9) #define GB_AUDIO_PCM_FMT_S32_LE BIT(10) #define GB_AUDIO_PCM_FMT_S32_BE BIT(11) #define GB_AUDIO_PCM_FMT_U32_LE BIT(12) #define GB_AUDIO_PCM_FMT_U32_BE BIT(13) /* See SNDRV_PCM_RATE_* in Linux source */ #define GB_AUDIO_PCM_RATE_5512 BIT(0) #define GB_AUDIO_PCM_RATE_8000 BIT(1) #define GB_AUDIO_PCM_RATE_11025 BIT(2) #define GB_AUDIO_PCM_RATE_16000 BIT(3) #define GB_AUDIO_PCM_RATE_22050 BIT(4) #define GB_AUDIO_PCM_RATE_32000 BIT(5) #define GB_AUDIO_PCM_RATE_44100 BIT(6) #define GB_AUDIO_PCM_RATE_48000 BIT(7) #define GB_AUDIO_PCM_RATE_64000 BIT(8) #define GB_AUDIO_PCM_RATE_88200 BIT(9) #define GB_AUDIO_PCM_RATE_96000 BIT(10) #define GB_AUDIO_PCM_RATE_176400 BIT(11) #define GB_AUDIO_PCM_RATE_192000 BIT(12) #define GB_AUDIO_STREAM_TYPE_CAPTURE 0x1 #define GB_AUDIO_STREAM_TYPE_PLAYBACK 0x2 #define GB_AUDIO_CTL_ELEM_ACCESS_READ BIT(0) #define GB_AUDIO_CTL_ELEM_ACCESS_WRITE BIT(1) /* See SNDRV_CTL_ELEM_TYPE_* in Linux source */ #define GB_AUDIO_CTL_ELEM_TYPE_BOOLEAN 0x01 #define GB_AUDIO_CTL_ELEM_TYPE_INTEGER 0x02 #define GB_AUDIO_CTL_ELEM_TYPE_ENUMERATED 0x03 #define GB_AUDIO_CTL_ELEM_TYPE_INTEGER64 0x06 /* See SNDRV_CTL_ELEM_IFACE_* in Linux source */ #define GB_AUDIO_CTL_ELEM_IFACE_CARD 0x00 #define GB_AUDIO_CTL_ELEM_IFACE_HWDEP 0x01 #define GB_AUDIO_CTL_ELEM_IFACE_MIXER 0x02 #define GB_AUDIO_CTL_ELEM_IFACE_PCM 0x03 #define GB_AUDIO_CTL_ELEM_IFACE_RAWMIDI 0x04 #define GB_AUDIO_CTL_ELEM_IFACE_TIMER 0x05 #define GB_AUDIO_CTL_ELEM_IFACE_SEQUENCER 0x06 /* SNDRV_CTL_ELEM_ACCESS_* in Linux source */ #define GB_AUDIO_ACCESS_READ BIT(0) #define GB_AUDIO_ACCESS_WRITE BIT(1) #define GB_AUDIO_ACCESS_VOLATILE BIT(2) #define GB_AUDIO_ACCESS_TIMESTAMP BIT(3) #define GB_AUDIO_ACCESS_TLV_READ BIT(4) #define GB_AUDIO_ACCESS_TLV_WRITE BIT(5) #define GB_AUDIO_ACCESS_TLV_COMMAND BIT(6) #define GB_AUDIO_ACCESS_INACTIVE BIT(7) #define GB_AUDIO_ACCESS_LOCK BIT(8) #define GB_AUDIO_ACCESS_OWNER BIT(9) /* enum snd_soc_dapm_type */ #define GB_AUDIO_WIDGET_TYPE_INPUT 0x0 #define GB_AUDIO_WIDGET_TYPE_OUTPUT 0x1 #define GB_AUDIO_WIDGET_TYPE_MUX 0x2 #define GB_AUDIO_WIDGET_TYPE_VIRT_MUX 0x3 #define GB_AUDIO_WIDGET_TYPE_VALUE_MUX 0x4 #define GB_AUDIO_WIDGET_TYPE_MIXER 0x5 #define GB_AUDIO_WIDGET_TYPE_MIXER_NAMED_CTL 0x6 #define GB_AUDIO_WIDGET_TYPE_PGA 0x7 #define GB_AUDIO_WIDGET_TYPE_OUT_DRV 0x8 #define GB_AUDIO_WIDGET_TYPE_ADC 0x9 #define GB_AUDIO_WIDGET_TYPE_DAC 0xa #define GB_AUDIO_WIDGET_TYPE_MICBIAS 0xb #define GB_AUDIO_WIDGET_TYPE_MIC 0xc #define GB_AUDIO_WIDGET_TYPE_HP 0xd #define GB_AUDIO_WIDGET_TYPE_SPK 0xe #define GB_AUDIO_WIDGET_TYPE_LINE 0xf #define GB_AUDIO_WIDGET_TYPE_SWITCH 0x10 #define GB_AUDIO_WIDGET_TYPE_VMID 0x11 #define GB_AUDIO_WIDGET_TYPE_PRE 0x12 #define GB_AUDIO_WIDGET_TYPE_POST 0x13 #define GB_AUDIO_WIDGET_TYPE_SUPPLY 0x14 #define GB_AUDIO_WIDGET_TYPE_REGULATOR_SUPPLY 0x15 #define GB_AUDIO_WIDGET_TYPE_CLOCK_SUPPLY 0x16 #define GB_AUDIO_WIDGET_TYPE_AIF_IN 0x17 #define GB_AUDIO_WIDGET_TYPE_AIF_OUT 0x18 #define GB_AUDIO_WIDGET_TYPE_SIGGEN 0x19 #define GB_AUDIO_WIDGET_TYPE_DAI_IN 0x1a #define GB_AUDIO_WIDGET_TYPE_DAI_OUT 0x1b #define GB_AUDIO_WIDGET_TYPE_DAI_LINK 0x1c #define GB_AUDIO_WIDGET_STATE_DISABLED 0x01 #define GB_AUDIO_WIDGET_STATE_ENAABLED 0x02 #define GB_AUDIO_JACK_EVENT_INSERTION 0x1 #define GB_AUDIO_JACK_EVENT_REMOVAL 0x2 #define GB_AUDIO_BUTTON_EVENT_PRESS 0x1 #define GB_AUDIO_BUTTON_EVENT_RELEASE 0x2 #define GB_AUDIO_STREAMING_EVENT_UNSPECIFIED 0x1 #define GB_AUDIO_STREAMING_EVENT_HALT 0x2 #define GB_AUDIO_STREAMING_EVENT_INTERNAL_ERROR 0x3 #define GB_AUDIO_STREAMING_EVENT_PROTOCOL_ERROR 0x4 #define GB_AUDIO_STREAMING_EVENT_FAILURE 0x5 #define GB_AUDIO_STREAMING_EVENT_UNDERRUN 0x6 #define GB_AUDIO_STREAMING_EVENT_OVERRUN 0x7 #define GB_AUDIO_STREAMING_EVENT_CLOCKING 0x8 #define GB_AUDIO_STREAMING_EVENT_DATA_LEN 0x9 #define GB_AUDIO_INVALID_INDEX 0xff /* enum snd_jack_types */ #define GB_AUDIO_JACK_HEADPHONE 0x0000001 #define GB_AUDIO_JACK_MICROPHONE 0x0000002 #define GB_AUDIO_JACK_HEADSET (GB_AUDIO_JACK_HEADPHONE | \ GB_AUDIO_JACK_MICROPHONE) #define GB_AUDIO_JACK_LINEOUT 0x0000004 #define GB_AUDIO_JACK_MECHANICAL 0x0000008 #define GB_AUDIO_JACK_VIDEOOUT 0x0000010 #define GB_AUDIO_JACK_AVOUT (GB_AUDIO_JACK_LINEOUT | \ GB_AUDIO_JACK_VIDEOOUT) #define GB_AUDIO_JACK_LINEIN 0x0000020 #define GB_AUDIO_JACK_OC_HPHL 0x0000040 #define GB_AUDIO_JACK_OC_HPHR 0x0000080 #define GB_AUDIO_JACK_MICROPHONE2 0x0000200 #define GB_AUDIO_JACK_ANC_HEADPHONE (GB_AUDIO_JACK_HEADPHONE | \ GB_AUDIO_JACK_MICROPHONE | \ GB_AUDIO_JACK_MICROPHONE2) /* Kept separate from switches to facilitate implementation */ #define GB_AUDIO_JACK_BTN_0 0x4000000 #define GB_AUDIO_JACK_BTN_1 0x2000000 #define GB_AUDIO_JACK_BTN_2 0x1000000 #define GB_AUDIO_JACK_BTN_3 0x0800000 struct gb_audio_pcm { __u8 stream_name[GB_AUDIO_PCM_NAME_MAX]; __le32 formats; /* GB_AUDIO_PCM_FMT_* */ __le32 rates; /* GB_AUDIO_PCM_RATE_* */ __u8 chan_min; __u8 chan_max; __u8 sig_bits; /* number of bits of content */ } __packed; struct gb_audio_dai { __u8 name[AUDIO_DAI_NAME_MAX]; __le16 data_cport; struct gb_audio_pcm capture; struct gb_audio_pcm playback; } __packed; struct gb_audio_integer { __le32 min; __le32 max; __le32 step; } __packed; struct gb_audio_integer64 { __le64 min; __le64 max; __le64 step; } __packed; struct gb_audio_enumerated { __le32 items; __le16 names_length; __u8 names[0]; } __packed; struct gb_audio_ctl_elem_info { /* See snd_ctl_elem_info in Linux source */ __u8 type; /* GB_AUDIO_CTL_ELEM_TYPE_* */ __le16 dimen[4]; union { struct gb_audio_integer integer; struct gb_audio_integer64 integer64; struct gb_audio_enumerated enumerated; } value; } __packed; struct gb_audio_ctl_elem_value { /* See snd_ctl_elem_value in Linux source */ __le64 timestamp; /* XXX needed? */ union { __le32 integer_value[2]; /* consider CTL_DOUBLE_xxx */ __le64 integer64_value[2]; __le32 enumerated_item[2]; } value; } __packed; struct gb_audio_control { __u8 name[AUDIO_CONTROL_NAME_MAX]; __u8 id; /* 0-63 */ __u8 iface; /* GB_AUDIO_IFACE_* */ __le16 data_cport; __le32 access; /* GB_AUDIO_ACCESS_* */ __u8 count; /* count of same elements */ __u8 count_values; /* count of values, max=2 for CTL_DOUBLE_xxx */ struct gb_audio_ctl_elem_info info; } __packed; struct gb_audio_widget { __u8 name[AUDIO_WIDGET_NAME_MAX]; __u8 sname[AUDIO_WIDGET_NAME_MAX]; __u8 id; __u8 type; /* GB_AUDIO_WIDGET_TYPE_* */ __u8 state; /* GB_AUDIO_WIDGET_STATE_* */ __u8 ncontrols; struct gb_audio_control ctl[0]; /* 'ncontrols' entries */ } __packed; struct gb_audio_route { __u8 source_id; /* widget id */ __u8 destination_id; /* widget id */ __u8 control_id; /* 0-63 */ __u8 index; /* Selection within the control */ } __packed; struct gb_audio_topology { __u8 num_dais; __u8 num_controls; __u8 num_widgets; __u8 num_routes; __le32 size_dais; __le32 size_controls; __le32 size_widgets; __le32 size_routes; __le32 jack_type; /* * struct gb_audio_dai dai[num_dais]; * struct gb_audio_control controls[num_controls]; * struct gb_audio_widget widgets[num_widgets]; * struct gb_audio_route routes[num_routes]; */ __u8 data[0]; } __packed; struct gb_audio_get_topology_size_response { __le16 size; } __packed; struct gb_audio_get_topology_response { struct gb_audio_topology topology; } __packed; struct gb_audio_get_control_request { __u8 control_id; __u8 index; } __packed; struct gb_audio_get_control_response { struct gb_audio_ctl_elem_value value; } __packed; struct gb_audio_set_control_request { __u8 control_id; __u8 index; struct gb_audio_ctl_elem_value value; } __packed; struct gb_audio_enable_widget_request { __u8 widget_id; } __packed; struct gb_audio_disable_widget_request { __u8 widget_id; } __packed; struct gb_audio_get_pcm_request { __le16 data_cport; } __packed; struct gb_audio_get_pcm_response { __le32 format; __le32 rate; __u8 channels; __u8 sig_bits; } __packed; struct gb_audio_set_pcm_request { __le16 data_cport; __le32 format; __le32 rate; __u8 channels; __u8 sig_bits; } __packed; struct gb_audio_set_tx_data_size_request { __le16 data_cport; __le16 size; } __packed; struct gb_audio_activate_tx_request { __le16 data_cport; } __packed; struct gb_audio_deactivate_tx_request { __le16 data_cport; } __packed; struct gb_audio_set_rx_data_size_request { __le16 data_cport; __le16 size; } __packed; struct gb_audio_activate_rx_request { __le16 data_cport; } __packed; struct gb_audio_deactivate_rx_request { __le16 data_cport; } __packed; struct gb_audio_jack_event_request { __u8 widget_id; __u8 jack_attribute; __u8 event; } __packed; struct gb_audio_button_event_request { __u8 widget_id; __u8 button_id; __u8 event; } __packed; struct gb_audio_streaming_event_request { __le16 data_cport; __u8 event; } __packed; struct gb_audio_send_data_request { __le64 timestamp; __u8 data[0]; } __packed; /* Log */ /* operations */ #define GB_LOG_TYPE_SEND_LOG 0x02 /* length */ #define GB_LOG_MAX_LEN 1024 struct gb_log_send_log_request { __le16 len; __u8 msg[0]; } __packed; #endif /* __GREYBUS_PROTOCOLS_H */
28.336271
101
0.809876
[ "model" ]
b106f4e9e939aa7774f86e3b56db3144d174746a
31,729
c
C
src/mono/mono/metadata/sgen-new-bridge.c
berkansasmaz/runtime
7626c5d8be527d6735eddcdc7c97423211d8f9e9
[ "MIT" ]
8
2022-02-19T15:57:07.000Z
2022-03-10T06:00:02.000Z
src/mono/mono/metadata/sgen-new-bridge.c
berkansasmaz/runtime
7626c5d8be527d6735eddcdc7c97423211d8f9e9
[ "MIT" ]
6
2020-03-20T18:33:48.000Z
2022-01-13T13:20:05.000Z
src/mono/mono/metadata/sgen-new-bridge.c
berkansasmaz/runtime
7626c5d8be527d6735eddcdc7c97423211d8f9e9
[ "MIT" ]
2
2022-02-24T06:39:57.000Z
2022-03-18T16:03:11.000Z
/** * \file * Simple generational GC. * * Copyright 2011 Novell, Inc (http://www.novell.com) * Copyright 2011 Xamarin Inc (http://www.xamarin.com) * Copyright 2001-2003 Ximian, Inc * Copyright 2003-2010 Novell, Inc. * * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include "config.h" #if defined (HAVE_SGEN_GC) && !defined (DISABLE_SGEN_GC_BRIDGE) #include <stdlib.h> #include <errno.h> #include "sgen/sgen-gc.h" #include "sgen-bridge-internals.h" #include "sgen/sgen-hash-table.h" #include "sgen/sgen-qsort.h" #include "sgen/sgen-client.h" #include "tabledefs.h" #include "utils/mono-logger-internals.h" #define OPTIMIZATION_COPY #define OPTIMIZATION_FORWARD #define OPTIMIZATION_SINGLETON_DYN_ARRAY #include "sgen-dynarray.h" //#define NEW_XREFS #ifdef NEW_XREFS //#define TEST_NEW_XREFS #endif #if !defined(NEW_XREFS) || defined(TEST_NEW_XREFS) #define OLD_XREFS #endif #ifdef NEW_XREFS #define XREFS new_xrefs #else #define XREFS old_xrefs #endif /* * Bridge data for a single managed object * * FIXME: Optimizations: * * Don't allocate a srcs array for just one source. Most objects have * just one source, so use the srcs pointer itself. */ typedef struct _HashEntry { gboolean is_bridge; union { struct { guint32 is_visited : 1; guint32 finishing_time : 31; struct _HashEntry *forwarded_to; } dfs1; struct { // Index in sccs array of SCC this object was folded into int scc_index; } dfs2; } v; // "Source" managed objects pointing at this destination DynPtrArray srcs; } HashEntry; typedef struct { HashEntry entry; double weight; } HashEntryWithAccounting; // The graph of managed objects/HashEntries is reduced to a graph of strongly connected components typedef struct _SCC { int index; int api_index; // How many bridged objects does this SCC hold references to? int num_bridge_entries; gboolean flag; /* * Index in global sccs array of SCCs holding pointers to this SCC * * New and old xrefs are typically mutually exclusive. Only when TEST_NEW_XREFS is * enabled we do both, and compare the results. This should only be done for * debugging, obviously. */ #ifdef OLD_XREFS DynIntArray old_xrefs; /* these are incoming, not outgoing */ #endif #ifdef NEW_XREFS DynIntArray new_xrefs; #endif } SCC; static char *dump_prefix = NULL; // Maps managed objects to corresponding HashEntry stricts static SgenHashTable hash_table = SGEN_HASH_TABLE_INIT (INTERNAL_MEM_BRIDGE_HASH_TABLE, INTERNAL_MEM_BRIDGE_HASH_TABLE_ENTRY, sizeof (HashEntry), mono_aligned_addr_hash, NULL); static guint32 current_time; static gboolean bridge_accounting_enabled = FALSE; static SgenBridgeProcessor *bridge_processor; /* Core functions */ /*SCC */ static void dyn_array_scc_init (DynSCCArray *da) { dyn_array_init (&da->array); } static void dyn_array_scc_uninit (DynSCCArray *da) { dyn_array_uninit (&da->array, sizeof (SCC)); } static int dyn_array_scc_size (DynSCCArray *da) { return da->array.size; } static SCC* dyn_array_scc_add (DynSCCArray *da) { return (SCC *)dyn_array_add (&da->array, sizeof (SCC)); } static SCC* dyn_array_scc_get_ptr (DynSCCArray *da, int x) { return &((SCC*)da->array.data)[x]; } /* Merge code*/ static DynIntArray merge_array; #ifdef NEW_XREFS static gboolean dyn_array_int_contains (DynIntArray *da, int x) { int i; for (i = 0; i < dyn_array_int_size (da); ++i) if (dyn_array_int_get (da, i) == x) return TRUE; return FALSE; } #endif static void set_config (const SgenBridgeProcessorConfig *config) { if (config->accounting) { SgenHashTable table = SGEN_HASH_TABLE_INIT (INTERNAL_MEM_BRIDGE_HASH_TABLE, INTERNAL_MEM_BRIDGE_HASH_TABLE_ENTRY, sizeof (HashEntryWithAccounting), mono_aligned_addr_hash, NULL); bridge_accounting_enabled = TRUE; hash_table = table; } if (config->dump_prefix) { dump_prefix = strdup (config->dump_prefix); } } static MonoGCBridgeObjectKind class_kind (MonoClass *klass) { MonoGCBridgeObjectKind res = mono_bridge_callbacks.bridge_class_kind (klass); /* If it's a bridge, nothing we can do about it. */ if (res == GC_BRIDGE_TRANSPARENT_BRIDGE_CLASS || res == GC_BRIDGE_OPAQUE_BRIDGE_CLASS) return res; /* Non bridge classes with no pointers will never point to a bridge, so we can savely ignore them. */ if (!m_class_has_references (klass)) { SGEN_LOG (6, "class %s is opaque\n", m_class_get_name (klass)); return GC_BRIDGE_OPAQUE_CLASS; } /* Some arrays can be ignored */ if (m_class_get_rank (klass) == 1) { MonoClass *elem_class = m_class_get_element_class (klass); /* FIXME the bridge check can be quite expensive, cache it at the class level. */ /* An array of a sealed type that is not a bridge will never get to a bridge */ if ((mono_class_get_flags (elem_class) & TYPE_ATTRIBUTE_SEALED) && !m_class_has_references (elem_class) && !mono_bridge_callbacks.bridge_class_kind (elem_class)) { SGEN_LOG (6, "class %s is opaque\n", m_class_get_name (klass)); return GC_BRIDGE_OPAQUE_CLASS; } } return GC_BRIDGE_TRANSPARENT_CLASS; } static HashEntry* get_hash_entry (MonoObject *obj, gboolean *existing) { HashEntry *entry = (HashEntry *)sgen_hash_table_lookup (&hash_table, obj); HashEntry new_entry; if (entry) { if (existing) *existing = TRUE; return entry; } if (existing) *existing = FALSE; memset (&new_entry, 0, sizeof (HashEntry)); dyn_array_ptr_init (&new_entry.srcs); new_entry.v.dfs1.finishing_time = 0; sgen_hash_table_replace (&hash_table, obj, &new_entry, NULL); return (HashEntry *)sgen_hash_table_lookup (&hash_table, obj); } static void add_source (HashEntry *entry, HashEntry *src) { dyn_array_ptr_add (&entry->srcs, src); } static void free_data (void) { MonoObject *obj G_GNUC_UNUSED; HashEntry *entry; int max_srcs = 0; SGEN_HASH_TABLE_FOREACH (&hash_table, MonoObject *, obj, HashEntry *, entry) { int entry_size = dyn_array_ptr_size (&entry->srcs); if (entry_size > max_srcs) max_srcs = entry_size; dyn_array_ptr_uninit (&entry->srcs); } SGEN_HASH_TABLE_FOREACH_END; sgen_hash_table_clean (&hash_table); dyn_array_int_uninit (&merge_array); } static HashEntry* register_bridge_object (MonoObject *obj) { HashEntry *entry = get_hash_entry (obj, NULL); entry->is_bridge = TRUE; return entry; } static void register_finishing_time (HashEntry *entry, guint32 t) { g_assert (entry->v.dfs1.finishing_time == 0); /* finishing_time has 31 bits, so it must be within signed int32 range. */ g_assert (t > 0 && t <= G_MAXINT32); entry->v.dfs1.finishing_time = t; } static int ignored_objects; static gboolean is_opaque_object (MonoObject *obj) { if ((obj->vtable->gc_bits & SGEN_GC_BIT_BRIDGE_OPAQUE_OBJECT) == SGEN_GC_BIT_BRIDGE_OPAQUE_OBJECT) { SGEN_LOG (6, "ignoring %s\n", m_class_get_name (mono_object_class (obj))); ++ignored_objects; return TRUE; } return FALSE; } static gboolean object_needs_expansion (MonoObject **objp) { MonoObject *obj = *objp; MonoObject *fwd = SGEN_OBJECT_IS_FORWARDED (obj); if (fwd) { *objp = fwd; if (is_opaque_object (fwd)) return FALSE; return sgen_hash_table_lookup (&hash_table, fwd) != NULL; } if (is_opaque_object (obj)) return FALSE; if (!sgen_object_is_live (obj)) return TRUE; return sgen_hash_table_lookup (&hash_table, obj) != NULL; } static HashEntry* follow_forward (HashEntry *entry) { #ifdef OPTIMIZATION_FORWARD while (entry->v.dfs1.forwarded_to) { HashEntry *next = entry->v.dfs1.forwarded_to; if (next->v.dfs1.forwarded_to) entry->v.dfs1.forwarded_to = next->v.dfs1.forwarded_to; entry = next; } #else g_assert (!entry->v.dfs1.forwarded_to); #endif return entry; } static DynPtrArray registered_bridges; static DynPtrArray dfs_stack; static int dfs1_passes, dfs2_passes; /* * DFS1 maintains a stack, where each two entries are effectively one entry. (FIXME: * Optimize this via pointer tagging.) There are two different types of entries: * * entry, src: entry needs to be expanded via scanning, and linked to from src * NULL, entry: entry has already been expanded and needs to be finished */ #undef HANDLE_PTR #define HANDLE_PTR(ptr,obj) do { \ GCObject *dst = (GCObject*)*(ptr); \ if (dst && object_needs_expansion (&dst)) { \ ++num_links; \ dyn_array_ptr_push (&dfs_stack, obj_entry); \ dyn_array_ptr_push (&dfs_stack, follow_forward (get_hash_entry (dst, NULL))); \ } \ } while (0) static void dfs1 (HashEntry *obj_entry) { HashEntry *src; g_assert (dyn_array_ptr_size (&dfs_stack) == 0); dyn_array_ptr_push (&dfs_stack, NULL); dyn_array_ptr_push (&dfs_stack, obj_entry); do { MonoObject *obj; char *start; ++dfs1_passes; obj_entry = (HashEntry *)dyn_array_ptr_pop (&dfs_stack); if (obj_entry) { /* obj_entry needs to be expanded */ src = (HashEntry *)dyn_array_ptr_pop (&dfs_stack); if (src) g_assert (!src->v.dfs1.forwarded_to); obj_entry = follow_forward (obj_entry); again: g_assert (!obj_entry->v.dfs1.forwarded_to); obj = sgen_hash_table_key_for_value_pointer (obj_entry); start = (char*)obj; if (!obj_entry->v.dfs1.is_visited) { int num_links = 0; mword desc = sgen_obj_get_descriptor_safe (obj); obj_entry->v.dfs1.is_visited = 1; /* push the finishing entry on the stack */ dyn_array_ptr_push (&dfs_stack, obj_entry); dyn_array_ptr_push (&dfs_stack, NULL); #include "sgen/sgen-scan-object.h" /* * We can remove non-bridge objects with a single outgoing * link by forwarding links going to it. * * This is the first time we've encountered this object, so * no links to it have yet been added. We'll keep it that * way by setting the forward pointer, and instead of * continuing processing this object, we start over with the * object it points to. */ #ifdef OPTIMIZATION_FORWARD if (!obj_entry->is_bridge && num_links == 1) { HashEntry *dst_entry = (HashEntry *)dyn_array_ptr_pop (&dfs_stack); HashEntry *obj_entry_again = (HashEntry *)dyn_array_ptr_pop (&dfs_stack); g_assert (obj_entry_again == obj_entry); g_assert (!dst_entry->v.dfs1.forwarded_to); if (obj_entry != dst_entry) { obj_entry->v.dfs1.forwarded_to = dst_entry; obj_entry = dst_entry; } goto again; } #endif } if (src) { //g_print ("link %s -> %s\n", sgen_safe_name (src->obj), sgen_safe_name (obj)); g_assert (!obj_entry->v.dfs1.forwarded_to); add_source (obj_entry, src); } else { //g_print ("starting with %s\n", sgen_safe_name (obj)); } } else { /* obj_entry needs to be finished */ obj_entry = (HashEntry *)dyn_array_ptr_pop (&dfs_stack); //g_print ("finish %s\n", sgen_safe_name (obj_entry->obj)); register_finishing_time (obj_entry, ++current_time); } } while (dyn_array_ptr_size (&dfs_stack) > 0); } static DynSCCArray sccs; static SCC *current_scc; /* * At the end of bridge processing we need to end up with an (acyclyc) graph of bridge * object SCCs, where the links between the nodes (each one an SCC) in that graph represent * the presence of a direct or indirect link between those SCCs. An example: * * D * | * v * A -> B -> c -> e -> F * * A, B, D and F are SCCs that contain bridge objects, c and e don't contain bridge objects. * The graph we need to produce from this is: * * D * | * v * A -> B -> F * * Note that we don't need to produce an edge from A to F. It's sufficient that F is * indirectly reachable from A. * * The old algorithm would create a set, for each SCC, of bridge SCCs that can reach it, * directly or indirectly, by merging the ones sets for those that reach it directly. The * sets it would build up are these: * * A: {} * B: {A} * c: {B} * D: {} * e: {B,D} * F: {B,D} * * The merge operations on these sets turned out to be huge time sinks. * * The new algorithm proceeds in two passes: During DFS2, it only builds up the sets of SCCs * that directly point to each SCC: * * A: {} * B: {A} * c: {B} * D: {} * e: {c,D} * F: {e} * * This is the adjacency list for the SCC graph, in other words. In a separate step * afterwards, it does a depth-first traversal of that graph, for each bridge node, to get * to the final list. It uses a flag to avoid traversing any node twice. */ static void scc_add_xref (SCC *src, SCC *dst) { g_assert (src != dst); g_assert (src->index != dst->index); #ifdef NEW_XREFS /* * FIXME: Right now we don't even unique the direct ancestors, but just add to the * list. Doing a containment check slows this algorithm down to almost the speed of * the old one. Use the flag instead! */ dyn_array_int_add (&dst->new_xrefs, src->index); #endif #ifdef OLD_XREFS if (dyn_array_int_is_copy (&dst->old_xrefs)) { int i; dyn_array_int_ensure_independent (&dst->old_xrefs); for (i = 0; i < dyn_array_int_size (&dst->old_xrefs); ++i) { int j = dyn_array_int_get (&dst->old_xrefs, i); SCC *bridge_scc = dyn_array_scc_get_ptr (&sccs, j); g_assert (!bridge_scc->flag); bridge_scc->flag = TRUE; } } if (src->num_bridge_entries) { if (src->flag) return; src->flag = TRUE; dyn_array_int_add (&dst->old_xrefs, src->index); #ifdef OPTIMIZATION_COPY } else if (dyn_array_int_size (&dst->old_xrefs) == 0) { dyn_array_int_copy (&dst->old_xrefs, &src->old_xrefs); #endif } else { int i; for (i = 0; i < dyn_array_int_size (&src->old_xrefs); ++i) { int j = dyn_array_int_get (&src->old_xrefs, i); SCC *bridge_scc = dyn_array_scc_get_ptr (&sccs, j); g_assert (bridge_scc->num_bridge_entries); if (!bridge_scc->flag) { bridge_scc->flag = TRUE; dyn_array_int_add (&dst->old_xrefs, j); } } } #endif } static void scc_add_entry (SCC *scc, HashEntry *entry) { g_assert (entry->v.dfs2.scc_index < 0); entry->v.dfs2.scc_index = scc->index; if (entry->is_bridge) ++scc->num_bridge_entries; } static void dfs2 (HashEntry *entry) { int i; g_assert (dyn_array_ptr_size (&dfs_stack) == 0); dyn_array_ptr_push (&dfs_stack, entry); do { entry = (HashEntry *)dyn_array_ptr_pop (&dfs_stack); ++dfs2_passes; if (entry->v.dfs2.scc_index >= 0) { if (entry->v.dfs2.scc_index != current_scc->index) scc_add_xref (dyn_array_scc_get_ptr (&sccs, entry->v.dfs2.scc_index), current_scc); continue; } scc_add_entry (current_scc, entry); for (i = 0; i < dyn_array_ptr_size (&entry->srcs); ++i) dyn_array_ptr_push (&dfs_stack, dyn_array_ptr_get (&entry->srcs, i)); } while (dyn_array_ptr_size (&dfs_stack) > 0); #ifdef OLD_XREFS /* If xrefs is a copy then we haven't set a single flag. */ if (dyn_array_int_is_copy (&current_scc->old_xrefs)) return; for (i = 0; i < dyn_array_int_size (&current_scc->old_xrefs); ++i) { int j = dyn_array_int_get (&current_scc->old_xrefs, i); SCC *bridge_scc = dyn_array_scc_get_ptr (&sccs, j); g_assert (bridge_scc->flag); bridge_scc->flag = FALSE; } #endif } #ifdef NEW_XREFS static void gather_xrefs (SCC *scc) { int i; for (i = 0; i < dyn_array_int_size (&scc->new_xrefs); ++i) { int index = dyn_array_int_get (&scc->new_xrefs, i); SCC *src = dyn_array_scc_get_ptr (&sccs, index); if (src->flag) continue; src->flag = TRUE; if (src->num_bridge_entries) dyn_array_int_add (&merge_array, index); else gather_xrefs (src); } } static void reset_flags (SCC *scc) { int i; for (i = 0; i < dyn_array_int_size (&scc->new_xrefs); ++i) { int index = dyn_array_int_get (&scc->new_xrefs, i); SCC *src = dyn_array_scc_get_ptr (&sccs, index); if (!src->flag) continue; src->flag = FALSE; if (!src->num_bridge_entries) reset_flags (src); } } #endif static void dump_graph (void) { static int counter = 0; MonoObject *obj; HashEntry *entry; size_t prefix_len = strlen (dump_prefix); char *filename = g_newa (char, prefix_len + 64); FILE *file; int edge_id = 0; sprintf (filename, "%s.%d.gexf", dump_prefix, counter++); file = fopen (filename, "w"); if (file == NULL) { fprintf (stderr, "Warning: Could not open bridge dump file `%s` for writing: %s\n", filename, strerror (errno)); return; } fprintf (file, "<gexf xmlns=\"http://www.gexf.net/1.2draft\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd\" version=\"1.2\">\n"); fprintf (file, "<graph defaultedgetype=\"directed\">\n" "<attributes class=\"node\">\n" "<attribute id=\"0\" title=\"class\" type=\"string\"/>\n" "<attribute id=\"1\" title=\"bridge\" type=\"boolean\"/>\n" "</attributes>\n"); fprintf (file, "<nodes>\n"); SGEN_HASH_TABLE_FOREACH (&hash_table, MonoObject *, obj, HashEntry *, entry) { MonoVTable *vt = SGEN_LOAD_VTABLE (obj); fprintf (file, "<node id=\"%p\"><attvalues><attvalue for=\"0\" value=\"%s.%s\"/><attvalue for=\"1\" value=\"%s\"/></attvalues></node>\n", obj, m_class_get_name_space (vt->klass), m_class_get_name (vt->klass), entry->is_bridge ? "true" : "false"); } SGEN_HASH_TABLE_FOREACH_END; fprintf (file, "</nodes>\n"); fprintf (file, "<edges>\n"); SGEN_HASH_TABLE_FOREACH (&hash_table, MonoObject *, obj, HashEntry *, entry) { int i; for (i = 0; i < dyn_array_ptr_size (&entry->srcs); ++i) { HashEntry *src = (HashEntry *)dyn_array_ptr_get (&entry->srcs, i); fprintf (file, "<edge id=\"%d\" source=\"%p\" target=\"%p\"/>\n", edge_id++, sgen_hash_table_key_for_value_pointer (src), obj); } } SGEN_HASH_TABLE_FOREACH_END; fprintf (file, "</edges>\n"); fprintf (file, "</graph></gexf>\n"); fclose (file); } static int compare_hash_entries (const HashEntry *e1, const HashEntry *e2) { /* We can cast to signed int here because finishing_time has only 31 bits. */ return (gint32)e2->v.dfs1.finishing_time - (gint32)e1->v.dfs1.finishing_time; } DEF_QSORT_INLINE(hash_entries, HashEntry*, compare_hash_entries) static gint64 step_1, step_2, step_3, step_4, step_5, step_6; static int fist_pass_links, second_pass_links, sccs_links; static int max_sccs_links = 0; static void register_finalized_object (GCObject *obj) { g_assert (sgen_need_bridge_processing ()); dyn_array_ptr_push (&registered_bridges, obj); } static void reset_data (void) { dyn_array_ptr_empty (&registered_bridges); } static void processing_stw_step (void) { int i; int bridge_count; MonoObject *obj G_GNUC_UNUSED; HashEntry *entry; SGEN_TV_DECLARE (atv); SGEN_TV_DECLARE (btv); if (!dyn_array_ptr_size (&registered_bridges)) return; SGEN_TV_GETTIME (btv); /* first DFS pass */ dyn_array_ptr_init (&dfs_stack); dyn_array_int_init (&merge_array); current_time = 0; /* First we insert all bridges into the hash table and then we do dfs1. It must be done in 2 steps since the bridge arrays doesn't come in reverse topological order, which means that we can have entry N pointing to entry N + 1. If we dfs1 entry N before N + 1 is registered we'll not consider N + 1 for this bridge pass and not create the required xref between the two. */ bridge_count = dyn_array_ptr_size (&registered_bridges); for (i = 0; i < bridge_count ; ++i) register_bridge_object ((MonoObject *)dyn_array_ptr_get (&registered_bridges, i)); for (i = 0; i < bridge_count; ++i) dfs1 (get_hash_entry ((MonoObject *)dyn_array_ptr_get (&registered_bridges, i), NULL)); /* Remove all forwarded objects. */ SGEN_HASH_TABLE_FOREACH (&hash_table, MonoObject *, obj, HashEntry *, entry) { if (entry->v.dfs1.forwarded_to) { g_assert (dyn_array_ptr_size (&entry->srcs) == 0); SGEN_HASH_TABLE_FOREACH_REMOVE (TRUE); continue; } } SGEN_HASH_TABLE_FOREACH_END; SGEN_TV_GETTIME (atv); step_2 = SGEN_TV_ELAPSED (btv, atv); if (dump_prefix) dump_graph (); } static int num_registered_bridges, hash_table_size; static void processing_build_callback_data (int generation) { int i, j; int num_sccs, num_xrefs; int max_entries, max_xrefs; MonoObject *obj = NULL; HashEntry *entry; HashEntry **all_entries; MonoGCBridgeSCC **api_sccs; MonoGCBridgeXRef *api_xrefs; SGEN_TV_DECLARE (atv); SGEN_TV_DECLARE (btv); g_assert (bridge_processor->num_sccs == 0 && bridge_processor->num_xrefs == 0); g_assert (!bridge_processor->api_sccs && !bridge_processor->api_xrefs); if (!dyn_array_ptr_size (&registered_bridges)) return; g_assert (mono_bridge_processing_in_progress); SGEN_TV_GETTIME (atv); /* alloc and fill array of all entries */ all_entries = (HashEntry **)sgen_alloc_internal_dynamic (sizeof (HashEntry*) * hash_table.num_entries, INTERNAL_MEM_BRIDGE_DATA, TRUE); j = 0; SGEN_HASH_TABLE_FOREACH (&hash_table, MonoObject *, obj, HashEntry *, entry) { g_assert (entry->v.dfs1.finishing_time > 0); all_entries [j++] = entry; fist_pass_links += dyn_array_ptr_size (&entry->srcs); } SGEN_HASH_TABLE_FOREACH_END; g_assert (j == hash_table.num_entries); hash_table_size = hash_table.num_entries; /* sort array according to decreasing finishing time */ qsort_hash_entries (all_entries, hash_table.num_entries); SGEN_HASH_TABLE_FOREACH (&hash_table, MonoObject *, obj, HashEntry *, entry) { entry->v.dfs2.scc_index = -1; } SGEN_HASH_TABLE_FOREACH_END; SGEN_TV_GETTIME (btv); step_3 = SGEN_TV_ELAPSED (atv, btv); /* second DFS pass */ dyn_array_scc_init (&sccs); for (i = 0; i < hash_table.num_entries; ++i) { entry = all_entries [i]; if (entry->v.dfs2.scc_index < 0) { int index = dyn_array_scc_size (&sccs); current_scc = dyn_array_scc_add (&sccs); current_scc->index = index; current_scc->num_bridge_entries = 0; #ifdef NEW_XREFS current_scc->flag = FALSE; dyn_array_int_init (&current_scc->new_xrefs); #endif #ifdef OLD_XREFS dyn_array_int_init (&current_scc->old_xrefs); #endif current_scc->api_index = -1; dfs2 (entry); #ifdef NEW_XREFS /* * If a node has only one incoming edge, we just copy the source's * xrefs array, effectively removing the source from the graph. * This takes care of long linked lists. */ if (!current_scc->num_bridge_entries && dyn_array_int_size (&current_scc->new_xrefs) == 1) { SCC *src; j = dyn_array_int_get (&current_scc->new_xrefs, 0); src = dyn_array_scc_get_ptr (&sccs, j); if (src->num_bridge_entries) dyn_array_int_set (&current_scc->new_xrefs, 0, j); else dyn_array_int_copy (&current_scc->new_xrefs, &src->new_xrefs); } #endif } } #ifdef NEW_XREFS #ifdef TEST_NEW_XREFS for (j = 0; j < dyn_array_scc_size (&sccs); ++j) { SCC *scc = dyn_array_scc_get_ptr (&sccs, j); g_assert (!scc->flag); } #endif for (i = 0; i < dyn_array_scc_size (&sccs); ++i) { SCC *scc = dyn_array_scc_get_ptr (&sccs, i); g_assert (scc->index == i); if (!scc->num_bridge_entries) continue; dyn_array_int_empty (&merge_array); gather_xrefs (scc); reset_flags (scc); dyn_array_int_copy (&scc->new_xrefs, &merge_array); dyn_array_int_ensure_independent (&scc->new_xrefs); #ifdef TEST_NEW_XREFS for (j = 0; j < dyn_array_scc_size (&sccs); ++j) { SCC *scc = dyn_array_scc_get_ptr (&sccs, j); g_assert (!scc->flag); } #endif } #ifdef TEST_NEW_XREFS for (i = 0; i < dyn_array_scc_size (&sccs); ++i) { SCC *scc = dyn_array_scc_get_ptr (&sccs, i); g_assert (scc->index == i); if (!scc->num_bridge_entries) continue; g_assert (dyn_array_int_size (&scc->new_xrefs) == dyn_array_int_size (&scc->old_xrefs)); for (j = 0; j < dyn_array_int_size (&scc->new_xrefs); ++j) g_assert (dyn_array_int_contains (&scc->old_xrefs, dyn_array_int_get (&scc->new_xrefs, j))); } #endif #endif /* * Compute the weight of each object. The weight of an object is its size plus the size of all * objects it points do. When the an object is pointed by multiple objects we distribute it's weight * equally among them. This distribution gives a rough estimate of the real impact of making the object * go away. * * The reasoning for this model is that complex graphs with single roots will have a bridge with very high * value in comparison to others. * * The all_entries array has all objects topologically sorted. To correctly propagate the weights it must be * done in reverse topological order - so we calculate the weight of the pointed-to objects before processing * pointer-from objects. * * We log those objects in the opposite order for no particular reason. The other constrain is that it should use the same * direction as the other logging loop that records live/dead information. */ if (bridge_accounting_enabled) { for (i = hash_table.num_entries - 1; i >= 0; --i) { double w; HashEntryWithAccounting *entry_acc = (HashEntryWithAccounting*)all_entries [i]; entry_acc->weight += (double)sgen_safe_object_get_size (sgen_hash_table_key_for_value_pointer (entry_acc)); w = entry_acc->weight / dyn_array_ptr_size (&entry_acc->entry.srcs); for (j = 0; j < dyn_array_ptr_size (&entry_acc->entry.srcs); ++j) { HashEntryWithAccounting *other = (HashEntryWithAccounting *)dyn_array_ptr_get (&entry_acc->entry.srcs, j); other->weight += w; } } for (i = 0; i < hash_table.num_entries; ++i) { HashEntryWithAccounting *entry_acc = (HashEntryWithAccounting*)all_entries [i]; if (entry_acc->entry.is_bridge) { MonoObject *instance = sgen_hash_table_key_for_value_pointer (entry_acc); MonoClass *klass = SGEN_LOAD_VTABLE (instance)->klass; mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_GC, "OBJECT %s::%s (%p) weight %f", m_class_get_name_space (klass), m_class_get_name (klass), instance, entry_acc->weight); } } } for (i = 0; i < hash_table.num_entries; ++i) { entry = all_entries [i]; second_pass_links += dyn_array_ptr_size (&entry->srcs); } SGEN_TV_GETTIME (atv); step_4 = SGEN_TV_ELAPSED (btv, atv); //g_print ("%d sccs\n", sccs.size); dyn_array_ptr_uninit (&dfs_stack); /* init data for callback */ num_sccs = 0; for (i = 0; i < dyn_array_scc_size (&sccs); ++i) { SCC *scc = dyn_array_scc_get_ptr (&sccs, i); g_assert (scc->index == i); if (scc->num_bridge_entries) ++num_sccs; sccs_links += dyn_array_int_size (&scc->XREFS); max_sccs_links = MAX (max_sccs_links, dyn_array_int_size (&scc->XREFS)); } api_sccs = (MonoGCBridgeSCC **)sgen_alloc_internal_dynamic (sizeof (MonoGCBridgeSCC*) * num_sccs, INTERNAL_MEM_BRIDGE_DATA, TRUE); num_xrefs = 0; j = 0; for (i = 0; i < dyn_array_scc_size (&sccs); ++i) { SCC *scc = dyn_array_scc_get_ptr (&sccs, i); if (!scc->num_bridge_entries) continue; api_sccs [j] = (MonoGCBridgeSCC *)sgen_alloc_internal_dynamic (sizeof (MonoGCBridgeSCC) + sizeof (MonoObject*) * scc->num_bridge_entries, INTERNAL_MEM_BRIDGE_DATA, TRUE); api_sccs [j]->is_alive = FALSE; api_sccs [j]->num_objs = scc->num_bridge_entries; scc->num_bridge_entries = 0; scc->api_index = j++; num_xrefs += dyn_array_int_size (&scc->XREFS); } SGEN_HASH_TABLE_FOREACH (&hash_table, MonoObject *, obj, HashEntry *, entry) { if (entry->is_bridge) { SCC *scc = dyn_array_scc_get_ptr (&sccs, entry->v.dfs2.scc_index); api_sccs [scc->api_index]->objs [scc->num_bridge_entries++] = sgen_hash_table_key_for_value_pointer (entry); } } SGEN_HASH_TABLE_FOREACH_END; api_xrefs = (MonoGCBridgeXRef *)sgen_alloc_internal_dynamic (sizeof (MonoGCBridgeXRef) * num_xrefs, INTERNAL_MEM_BRIDGE_DATA, TRUE); j = 0; for (i = 0; i < dyn_array_scc_size (&sccs); ++i) { int k; SCC *scc = dyn_array_scc_get_ptr (&sccs, i); if (!scc->num_bridge_entries) continue; for (k = 0; k < dyn_array_int_size (&scc->XREFS); ++k) { SCC *src_scc = dyn_array_scc_get_ptr (&sccs, dyn_array_int_get (&scc->XREFS, k)); if (!src_scc->num_bridge_entries) continue; api_xrefs [j].src_scc_index = src_scc->api_index; api_xrefs [j].dst_scc_index = scc->api_index; ++j; } } SGEN_TV_GETTIME (btv); step_5 = SGEN_TV_ELAPSED (atv, btv); /* free data */ j = 0; max_entries = max_xrefs = 0; for (i = 0; i < dyn_array_scc_size (&sccs); ++i) { SCC *scc = dyn_array_scc_get_ptr (&sccs, i); if (scc->num_bridge_entries) ++j; if (scc->num_bridge_entries > max_entries) max_entries = scc->num_bridge_entries; if (dyn_array_int_size (&scc->XREFS) > max_xrefs) max_xrefs = dyn_array_int_size (&scc->XREFS); #ifdef NEW_XREFS dyn_array_int_uninit (&scc->new_xrefs); #endif #ifdef OLD_XREFS dyn_array_int_uninit (&scc->old_xrefs); #endif } dyn_array_scc_uninit (&sccs); sgen_free_internal_dynamic (all_entries, sizeof (HashEntry*) * hash_table.num_entries, INTERNAL_MEM_BRIDGE_DATA); free_data (); /* Empty the registered bridges array */ num_registered_bridges = dyn_array_ptr_size (&registered_bridges); dyn_array_ptr_empty (&registered_bridges); SGEN_TV_GETTIME (atv); step_6 = SGEN_TV_ELAPSED (btv, atv); //g_print ("%d sccs containing bridges - %d max bridge objects - %d max xrefs\n", j, max_entries, max_xrefs); bridge_processor->num_sccs = num_sccs; bridge_processor->api_sccs = api_sccs; bridge_processor->num_xrefs = num_xrefs; bridge_processor->api_xrefs = api_xrefs; } static void processing_after_callback (int generation) { int i, j; int num_sccs = bridge_processor->num_sccs; MonoGCBridgeSCC **api_sccs = bridge_processor->api_sccs; if (bridge_accounting_enabled) { for (i = 0; i < num_sccs; ++i) { for (j = 0; j < api_sccs [i]->num_objs; ++j) { GCVTable vtable = SGEN_LOAD_VTABLE (api_sccs [i]->objs [j]); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_GC, "OBJECT %s.%s (%p) SCC [%d] %s", sgen_client_vtable_get_namespace (vtable), sgen_client_vtable_get_name (vtable), api_sccs [i]->objs [j], i, api_sccs [i]->is_alive ? "ALIVE" : "DEAD"); } } } mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_GC, "GC_NEW_BRIDGE num-objects %d num_hash_entries %d sccs size %d init %.2fms df1 %.2fms sort %.2fms dfs2 %.2fms setup-cb %.2fms free-data %.2fms links %d/%d/%d/%d dfs passes %d/%d ignored %d", num_registered_bridges, hash_table_size, dyn_array_scc_size (&sccs), step_1 / 10000.0f, step_2 / 10000.0f, step_3 / 10000.0f, step_4 / 10000.0f, step_5 / 10000.0f, step_6 / 10000.0f, fist_pass_links, second_pass_links, sccs_links, max_sccs_links, dfs1_passes, dfs2_passes, ignored_objects); step_1 = 0; /* We must cleanup since this value is used as an accumulator. */ fist_pass_links = second_pass_links = sccs_links = max_sccs_links = 0; dfs1_passes = dfs2_passes = ignored_objects = 0; } static void describe_pointer (GCObject *obj) { HashEntry *entry; int i; for (i = 0; i < dyn_array_ptr_size (&registered_bridges); ++i) { if (obj == dyn_array_ptr_get (&registered_bridges, i)) { printf ("Pointer is a registered bridge object.\n"); break; } } entry = (HashEntry *)sgen_hash_table_lookup (&hash_table, obj); if (!entry) return; printf ("Bridge hash table entry %p:\n", entry); printf (" is bridge: %d\n", (int)entry->is_bridge); printf (" is visited: %d\n", (int)entry->v.dfs1.is_visited); } void sgen_new_bridge_init (SgenBridgeProcessor *collector) { collector->reset_data = reset_data; collector->processing_stw_step = processing_stw_step; collector->processing_build_callback_data = processing_build_callback_data; collector->processing_after_callback = processing_after_callback; collector->class_kind = class_kind; collector->register_finalized_object = register_finalized_object; collector->describe_pointer = describe_pointer; collector->set_config = set_config; bridge_processor = collector; } #else #include <mono/utils/mono-compiler.h> MONO_EMPTY_SOURCE_FILE (sgen_new_bridge); #endif
28.870792
237
0.705348
[ "object", "model" ]
b10bd07af7deea0d1cc5815d92e060b714e96e61
4,857
h
C
SCRambl/Constructs.h
Deji69/SCRambl
cf6eb64272b4126094c77a720c2402ed47822a50
[ "MIT" ]
5
2015-07-10T18:31:14.000Z
2021-12-31T18:35:10.000Z
SCRambl/Constructs.h
Deji69/SCRambl
cf6eb64272b4126094c77a720c2402ed47822a50
[ "MIT" ]
null
null
null
SCRambl/Constructs.h
Deji69/SCRambl
cf6eb64272b4126094c77a720c2402ed47822a50
[ "MIT" ]
2
2015-03-21T20:03:24.000Z
2021-09-18T02:46:26.000Z
/**********************************************************/ // SCRambl Advanced SCR Compiler/Assembler // This program is distributed freely under the MIT license // (See the LICENSE file provided // or copy at http://opensource.org/licenses/MIT) /**********************************************************/ #pragma once #include <string> #include <vector> #include <unordered_map> #include "Configuration.h" namespace SCRambl { class Engine; namespace Constructing { class DataCode { public: virtual ~DataCode() = default; private: }; class CommandCode : public DataCode { public: enum class ConditionType { Name }; public: CommandCode() { } void AddCondition(ConditionType type, XMLValue value) { m_Conditions.emplace_back(type, value); } private: std::vector<std::pair<ConditionType, XMLValue>> m_Conditions; std::vector<std::string> m_Args; }; enum class DataPosition { Block, Conditions, }; class Data { public: template<typename T, typename... TArgs> inline T& AddCode(TArgs&&... args) { m_Code.emplace_back(std::make_unique<T>(std::forward<TArgs>(args)...)); return *static_cast<T*>(m_Code.back().get()); } private: std::vector<std::unique_ptr<DataCode>> m_Code; }; class ConditionList { public: void SetMinConditions(size_t v) { m_Min = v; } void SetMaxConditions(size_t v) { m_Max = v; } void SetDisableMixedLogic(bool b) { m_DisableMixedLogic = b; } private: size_t m_Min = 0, m_Max = 0; bool m_DisableMixedLogic = false; }; class Block { public: Block(std::string begin, std::string end, bool repeat = false) : m_Begin(begin), m_End(end), m_Repeatable(repeat) { } Block(const Block& v) = delete; Block(Block&& v) : m_Begin(v.m_Begin), m_End(v.m_End), m_Blocks(std::move(v.m_Blocks)), m_Default(v.m_Default), m_Repeatable(v.m_Repeatable), m_Data(std::move(v.m_Data)) { } Block& operator=(const Block&) = delete; Block& operator=(Block&& v) { if (this != &v) { m_Begin = v.m_Begin; m_End = v.m_End; m_Blocks = std::move(v.m_Blocks); m_Default = v.m_Default; m_Repeatable = v.m_Repeatable; m_Data = std::move(v.m_Data); } return *this; } template<typename... TArgs> inline Block& AddBlock(TArgs&&... args) { m_Blocks.emplace_back(std::make_unique<Block>(std::forward<TArgs>(args)...)); return *m_Blocks.back(); } inline Data& AddData(DataPosition pos, bool before = false) { auto it = m_Data.emplace(pos, std::make_pair(std::make_unique<Data>(), before)); return *it->second.first; } size_t GetDataAt(std::vector<Data*>& vec, DataPosition pos, bool before = false) { auto rg = m_Data.equal_range(pos); size_t n = 0; for (auto it = rg.first; it != rg.second; ++it) { if (it->second.second == before) { ++n; vec.push_back(it->second.first.get()); } } return n; } inline ConditionList& AddConditionList() { ASSERT(!m_ConditionList); if (!m_ConditionList) m_ConditionList = std::make_unique<ConditionList>(); return *m_ConditionList.get(); } inline ConditionList& GetConditionList() const { return *m_ConditionList; } inline bool HasConditionList() const { return m_ConditionList != false; } private: std::string m_Begin = "{", m_End = "}"; std::vector<std::unique_ptr<Block>> m_Blocks; std::multimap<DataPosition, std::pair<std::unique_ptr<Data>, bool>> m_Data; std::unique_ptr<ConditionList> m_ConditionList; bool m_Default = false, m_Repeatable = false; }; class Construct { public: Construct(std::string name) : m_Name(name) { } Construct(const Construct&) = delete; template<typename... TArgs> Block& AddBlock(TArgs&&... args) { m_Blocks.emplace_back(std::make_unique<Block>(std::forward<TArgs>(args)...)); return *m_Blocks.back(); } size_t NumBlocks() const { return m_Blocks.size(); } Block& GetBlock(size_t i) const { return *m_Blocks[i]; } inline const std::string& Name() const { return m_Name; } private: std::string m_Name; std::vector<std::unique_ptr<Block>> m_Blocks; }; class Constructs { using Map = std::unordered_multimap<std::string, std::unique_ptr<Construct>>; public: Constructs(); Constructs(const Constructs&) = delete; void Init(Build& build); Construct* AddConstruct(std::string name) { auto pr = m_Constructs.emplace(name, std::make_unique<Construct>(name)); return pr->second.get(); } Construct* GetConstruct(std::string name) const { auto it = m_Constructs.find(name); return it != m_Constructs.end() ? it->second.get() : nullptr; } private: void AddDataConfig(XMLConfig*, const char *); private: Map m_Constructs; XMLConfiguration* m_Config; }; } }
26.254054
116
0.638872
[ "vector" ]
b10f12c81175eb151091c44903e34e03f7f67c7e
7,111
h
C
src/LabelTrack.h
lstolcman/audacity
1efebb7cdcb3fd4939a564e3775eeb2ed054ab54
[ "CC-BY-3.0" ]
3
2020-09-26T18:20:20.000Z
2020-10-06T05:32:35.000Z
src/LabelTrack.h
lstolcman/audacity
1efebb7cdcb3fd4939a564e3775eeb2ed054ab54
[ "CC-BY-3.0" ]
1
2021-09-14T10:59:41.000Z
2021-09-14T10:59:41.000Z
src/LabelTrack.h
lstolcman/audacity
1efebb7cdcb3fd4939a564e3775eeb2ed054ab54
[ "CC-BY-3.0" ]
1
2020-11-17T19:54:58.000Z
2020-11-17T19:54:58.000Z
/********************************************************************** Audacity: A Digital Audio Editor LabelTrack.h Dominic Mazzoni James Crook Jun Wan **********************************************************************/ #ifndef _LABELTRACK_ #define _LABELTRACK_ #include "SelectedRegion.h" #include "Track.h" class wxTextFile; class AudacityProject; class NotifyingSelectedRegion; class TimeWarper; struct LabelTrackHit; struct TrackPanelDrawingContext; class LabelStruct { public: LabelStruct() = default; // Copies region LabelStruct(const SelectedRegion& region, const wxString &aTitle); // Copies region but then overwrites other times LabelStruct(const SelectedRegion& region, double t0, double t1, const wxString &aTitle); const SelectedRegion &getSelectedRegion() const { return selectedRegion; } double getDuration() const { return selectedRegion.duration(); } double getT0() const { return selectedRegion.t0(); } double getT1() const { return selectedRegion.t1(); } // Returns true iff the label got inverted: bool AdjustEdge( int iEdge, double fNewTime); void MoveLabel( int iEdge, double fNewTime); struct BadFormatException {}; static LabelStruct Import(wxTextFile &file, int &index); void Export(wxTextFile &file) const; /// Relationships between selection region and labels enum TimeRelations { BEFORE_LABEL, AFTER_LABEL, SURROUNDS_LABEL, WITHIN_LABEL, BEGINS_IN_LABEL, ENDS_IN_LABEL }; /// Returns relationship between a region described and this label; if /// parent is set, it will consider point labels at the very beginning /// and end of parent to be within a region that borders them (this makes /// it possible to DELETE capture all labels with a Select All). TimeRelations RegionRelation(double reg_t0, double reg_t1, const LabelTrack *parent = NULL) const; public: SelectedRegion selectedRegion; wxString title; /// Text of the label. mutable int width{}; /// width of the text in pixels. // Working storage for on-screen layout. mutable int x{}; /// Pixel position of left hand glyph mutable int x1{}; /// Pixel position of right hand glyph mutable int xText{}; /// Pixel position of left hand side of text box mutable int y{}; /// Pixel position of label. bool updated{}; /// flag to tell if the label times were updated }; using LabelArray = std::vector<LabelStruct>; class AUDACITY_DLL_API LabelTrack final : public Track , public wxEvtHandler { public: LabelTrack(); LabelTrack(const LabelTrack &orig); virtual ~ LabelTrack(); void SetLabel( size_t iLabel, const LabelStruct &newLabel ); void SetOffset(double dOffset) override; void SetSelected(bool s) override; double GetOffset() const override; double GetStartTime() const override; double GetEndTime() const override; using Holder = std::shared_ptr<LabelTrack>; private: Track::Holder Clone() const override; public: bool HandleXMLTag(const wxChar *tag, const wxChar **attrs) override; XMLTagHandler *HandleXMLChild(const wxChar *tag) override; void WriteXML(XMLWriter &xmlFile) const override; Track::Holder Cut (double t0, double t1) override; Track::Holder Copy (double t0, double t1, bool forClipboard = true) const override; void Clear(double t0, double t1) override; void Paste(double t, const Track * src) override; bool Repeat(double t0, double t1, int n); void SyncLockAdjust(double oldT1, double newT1) override; void Silence(double t0, double t1) override; void InsertSilence(double t, double len) override; void Import(wxTextFile & f); void Export(wxTextFile & f) const; int GetNumLabels() const; const LabelStruct *GetLabel(int index) const; const LabelArray &GetLabels() const { return mLabels; } void OnLabelAdded( const wxString &title, int pos ); //This returns the index of the label we just added. int AddLabel(const SelectedRegion &region, const wxString &title); //This deletes the label at given index. void DeleteLabel(int index); // This pastes labels without shifting existing ones bool PasteOver(double t, const Track *src); // PRL: These functions were not used because they were not overrides! Was that right? //Track::Holder SplitCut(double b, double e) /* not override */; //bool SplitDelete(double b, double e) /* not override */; void ShiftLabelsOnInsert(double length, double pt); void ChangeLabelsOnReverse(double b, double e); void ScaleLabels(double b, double e, double change); double AdjustTimeStampOnScale(double t, double b, double e, double change); void WarpLabels(const TimeWarper &warper); // Returns tab-separated text of all labels completely within given region wxString GetTextOfLabels(double t0, double t1) const; int FindNextLabel(const SelectedRegion& currentSelection); int FindPrevLabel(const SelectedRegion& currentSelection); struct IntervalData final : Track::IntervalData { size_t index; explicit IntervalData(size_t index) : index{index} {}; }; ConstInterval MakeInterval ( size_t index ) const; Interval MakeInterval ( size_t index ); ConstIntervals GetIntervals() const override; Intervals GetIntervals() override; public: void SortLabels(); private: TrackKind GetKind() const override { return TrackKind::Label; } LabelArray mLabels; // Set in copied label tracks double mClipLen; int miLastLabel; // used by FindNextLabel and FindPrevLabel }; struct LabelTrackEvent : TrackListEvent { explicit LabelTrackEvent( wxEventType commandType, const std::shared_ptr<LabelTrack> &pTrack, const wxString &title, int formerPosition, int presentPosition ) : TrackListEvent{ commandType, pTrack } , mTitle{ title } , mFormerPosition{ formerPosition } , mPresentPosition{ presentPosition } {} LabelTrackEvent( const LabelTrackEvent& ) = default; wxEvent *Clone() const override { // wxWidgets will own the event object return safenew LabelTrackEvent(*this); } // invalid for selection events wxString mTitle; // invalid for addition and selection events int mFormerPosition{ -1 }; // invalid for deletion and selection events int mPresentPosition{ -1 }; }; // Posted when a label is added. wxDECLARE_EXPORTED_EVENT(AUDACITY_DLL_API, EVT_LABELTRACK_ADDITION, LabelTrackEvent); // Posted when a label is deleted. wxDECLARE_EXPORTED_EVENT(AUDACITY_DLL_API, EVT_LABELTRACK_DELETION, LabelTrackEvent); // Posted when a label is repositioned in the sequence of labels. wxDECLARE_EXPORTED_EVENT(AUDACITY_DLL_API, EVT_LABELTRACK_PERMUTED, LabelTrackEvent); // Posted when the track is selected or unselected. wxDECLARE_EXPORTED_EVENT(AUDACITY_DLL_API, EVT_LABELTRACK_SELECTION, LabelTrackEvent); #endif
31.325991
91
0.696245
[ "object", "vector" ]
b114b5c74fe9f790bad94911970e9f9917c36627
11,704
h
C
aws-cpp-sdk-ec2/include/aws/ec2/model/TargetNetwork.h
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
1
2020-03-11T05:36:20.000Z
2020-03-11T05:36:20.000Z
aws-cpp-sdk-ec2/include/aws/ec2/model/TargetNetwork.h
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-ec2/include/aws/ec2/model/TargetNetwork.h
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #pragma once #include <aws/ec2/EC2_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSStreamFwd.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/ec2/model/AssociationStatus.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <utility> namespace Aws { namespace Utils { namespace Xml { class XmlNode; } // namespace Xml } // namespace Utils namespace EC2 { namespace Model { /** * <p>Describes a target network associated with a Client VPN * endpoint.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/TargetNetwork">AWS * API Reference</a></p> */ class AWS_EC2_API TargetNetwork { public: TargetNetwork(); TargetNetwork(const Aws::Utils::Xml::XmlNode& xmlNode); TargetNetwork& operator=(const Aws::Utils::Xml::XmlNode& xmlNode); void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const; void OutputToStream(Aws::OStream& oStream, const char* location) const; /** * <p>The ID of the association.</p> */ inline const Aws::String& GetAssociationId() const{ return m_associationId; } /** * <p>The ID of the association.</p> */ inline bool AssociationIdHasBeenSet() const { return m_associationIdHasBeenSet; } /** * <p>The ID of the association.</p> */ inline void SetAssociationId(const Aws::String& value) { m_associationIdHasBeenSet = true; m_associationId = value; } /** * <p>The ID of the association.</p> */ inline void SetAssociationId(Aws::String&& value) { m_associationIdHasBeenSet = true; m_associationId = std::move(value); } /** * <p>The ID of the association.</p> */ inline void SetAssociationId(const char* value) { m_associationIdHasBeenSet = true; m_associationId.assign(value); } /** * <p>The ID of the association.</p> */ inline TargetNetwork& WithAssociationId(const Aws::String& value) { SetAssociationId(value); return *this;} /** * <p>The ID of the association.</p> */ inline TargetNetwork& WithAssociationId(Aws::String&& value) { SetAssociationId(std::move(value)); return *this;} /** * <p>The ID of the association.</p> */ inline TargetNetwork& WithAssociationId(const char* value) { SetAssociationId(value); return *this;} /** * <p>The ID of the VPC in which the target network (subnet) is located.</p> */ inline const Aws::String& GetVpcId() const{ return m_vpcId; } /** * <p>The ID of the VPC in which the target network (subnet) is located.</p> */ inline bool VpcIdHasBeenSet() const { return m_vpcIdHasBeenSet; } /** * <p>The ID of the VPC in which the target network (subnet) is located.</p> */ inline void SetVpcId(const Aws::String& value) { m_vpcIdHasBeenSet = true; m_vpcId = value; } /** * <p>The ID of the VPC in which the target network (subnet) is located.</p> */ inline void SetVpcId(Aws::String&& value) { m_vpcIdHasBeenSet = true; m_vpcId = std::move(value); } /** * <p>The ID of the VPC in which the target network (subnet) is located.</p> */ inline void SetVpcId(const char* value) { m_vpcIdHasBeenSet = true; m_vpcId.assign(value); } /** * <p>The ID of the VPC in which the target network (subnet) is located.</p> */ inline TargetNetwork& WithVpcId(const Aws::String& value) { SetVpcId(value); return *this;} /** * <p>The ID of the VPC in which the target network (subnet) is located.</p> */ inline TargetNetwork& WithVpcId(Aws::String&& value) { SetVpcId(std::move(value)); return *this;} /** * <p>The ID of the VPC in which the target network (subnet) is located.</p> */ inline TargetNetwork& WithVpcId(const char* value) { SetVpcId(value); return *this;} /** * <p>The ID of the subnet specified as the target network.</p> */ inline const Aws::String& GetTargetNetworkId() const{ return m_targetNetworkId; } /** * <p>The ID of the subnet specified as the target network.</p> */ inline bool TargetNetworkIdHasBeenSet() const { return m_targetNetworkIdHasBeenSet; } /** * <p>The ID of the subnet specified as the target network.</p> */ inline void SetTargetNetworkId(const Aws::String& value) { m_targetNetworkIdHasBeenSet = true; m_targetNetworkId = value; } /** * <p>The ID of the subnet specified as the target network.</p> */ inline void SetTargetNetworkId(Aws::String&& value) { m_targetNetworkIdHasBeenSet = true; m_targetNetworkId = std::move(value); } /** * <p>The ID of the subnet specified as the target network.</p> */ inline void SetTargetNetworkId(const char* value) { m_targetNetworkIdHasBeenSet = true; m_targetNetworkId.assign(value); } /** * <p>The ID of the subnet specified as the target network.</p> */ inline TargetNetwork& WithTargetNetworkId(const Aws::String& value) { SetTargetNetworkId(value); return *this;} /** * <p>The ID of the subnet specified as the target network.</p> */ inline TargetNetwork& WithTargetNetworkId(Aws::String&& value) { SetTargetNetworkId(std::move(value)); return *this;} /** * <p>The ID of the subnet specified as the target network.</p> */ inline TargetNetwork& WithTargetNetworkId(const char* value) { SetTargetNetworkId(value); return *this;} /** * <p>The ID of the Client VPN endpoint with which the target network is * associated.</p> */ inline const Aws::String& GetClientVpnEndpointId() const{ return m_clientVpnEndpointId; } /** * <p>The ID of the Client VPN endpoint with which the target network is * associated.</p> */ inline bool ClientVpnEndpointIdHasBeenSet() const { return m_clientVpnEndpointIdHasBeenSet; } /** * <p>The ID of the Client VPN endpoint with which the target network is * associated.</p> */ inline void SetClientVpnEndpointId(const Aws::String& value) { m_clientVpnEndpointIdHasBeenSet = true; m_clientVpnEndpointId = value; } /** * <p>The ID of the Client VPN endpoint with which the target network is * associated.</p> */ inline void SetClientVpnEndpointId(Aws::String&& value) { m_clientVpnEndpointIdHasBeenSet = true; m_clientVpnEndpointId = std::move(value); } /** * <p>The ID of the Client VPN endpoint with which the target network is * associated.</p> */ inline void SetClientVpnEndpointId(const char* value) { m_clientVpnEndpointIdHasBeenSet = true; m_clientVpnEndpointId.assign(value); } /** * <p>The ID of the Client VPN endpoint with which the target network is * associated.</p> */ inline TargetNetwork& WithClientVpnEndpointId(const Aws::String& value) { SetClientVpnEndpointId(value); return *this;} /** * <p>The ID of the Client VPN endpoint with which the target network is * associated.</p> */ inline TargetNetwork& WithClientVpnEndpointId(Aws::String&& value) { SetClientVpnEndpointId(std::move(value)); return *this;} /** * <p>The ID of the Client VPN endpoint with which the target network is * associated.</p> */ inline TargetNetwork& WithClientVpnEndpointId(const char* value) { SetClientVpnEndpointId(value); return *this;} /** * <p>The current state of the target network association.</p> */ inline const AssociationStatus& GetStatus() const{ return m_status; } /** * <p>The current state of the target network association.</p> */ inline bool StatusHasBeenSet() const { return m_statusHasBeenSet; } /** * <p>The current state of the target network association.</p> */ inline void SetStatus(const AssociationStatus& value) { m_statusHasBeenSet = true; m_status = value; } /** * <p>The current state of the target network association.</p> */ inline void SetStatus(AssociationStatus&& value) { m_statusHasBeenSet = true; m_status = std::move(value); } /** * <p>The current state of the target network association.</p> */ inline TargetNetwork& WithStatus(const AssociationStatus& value) { SetStatus(value); return *this;} /** * <p>The current state of the target network association.</p> */ inline TargetNetwork& WithStatus(AssociationStatus&& value) { SetStatus(std::move(value)); return *this;} /** * <p>The IDs of the security groups applied to the target network association.</p> */ inline const Aws::Vector<Aws::String>& GetSecurityGroups() const{ return m_securityGroups; } /** * <p>The IDs of the security groups applied to the target network association.</p> */ inline bool SecurityGroupsHasBeenSet() const { return m_securityGroupsHasBeenSet; } /** * <p>The IDs of the security groups applied to the target network association.</p> */ inline void SetSecurityGroups(const Aws::Vector<Aws::String>& value) { m_securityGroupsHasBeenSet = true; m_securityGroups = value; } /** * <p>The IDs of the security groups applied to the target network association.</p> */ inline void SetSecurityGroups(Aws::Vector<Aws::String>&& value) { m_securityGroupsHasBeenSet = true; m_securityGroups = std::move(value); } /** * <p>The IDs of the security groups applied to the target network association.</p> */ inline TargetNetwork& WithSecurityGroups(const Aws::Vector<Aws::String>& value) { SetSecurityGroups(value); return *this;} /** * <p>The IDs of the security groups applied to the target network association.</p> */ inline TargetNetwork& WithSecurityGroups(Aws::Vector<Aws::String>&& value) { SetSecurityGroups(std::move(value)); return *this;} /** * <p>The IDs of the security groups applied to the target network association.</p> */ inline TargetNetwork& AddSecurityGroups(const Aws::String& value) { m_securityGroupsHasBeenSet = true; m_securityGroups.push_back(value); return *this; } /** * <p>The IDs of the security groups applied to the target network association.</p> */ inline TargetNetwork& AddSecurityGroups(Aws::String&& value) { m_securityGroupsHasBeenSet = true; m_securityGroups.push_back(std::move(value)); return *this; } /** * <p>The IDs of the security groups applied to the target network association.</p> */ inline TargetNetwork& AddSecurityGroups(const char* value) { m_securityGroupsHasBeenSet = true; m_securityGroups.push_back(value); return *this; } private: Aws::String m_associationId; bool m_associationIdHasBeenSet; Aws::String m_vpcId; bool m_vpcIdHasBeenSet; Aws::String m_targetNetworkId; bool m_targetNetworkIdHasBeenSet; Aws::String m_clientVpnEndpointId; bool m_clientVpnEndpointIdHasBeenSet; AssociationStatus m_status; bool m_statusHasBeenSet; Aws::Vector<Aws::String> m_securityGroups; bool m_securityGroupsHasBeenSet; }; } // namespace Model } // namespace EC2 } // namespace Aws
35.792049
163
0.676948
[ "vector", "model" ]
b116c3d843049af93250136a56164be8232e257c
35,398
h
C
ext/hal/st/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_smartcard.h
timoML/zephyr-riscv
f14d41a7f352570dcd534d5af0819a33c7e728ae
[ "Apache-2.0" ]
31
2016-12-10T14:41:26.000Z
2021-03-23T23:57:16.000Z
ext/hal/st/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_smartcard.h
timoML/zephyr-riscv
f14d41a7f352570dcd534d5af0819a33c7e728ae
[ "Apache-2.0" ]
9
2017-02-22T12:24:11.000Z
2022-02-10T21:20:51.000Z
ext/hal/st/stm32cube/stm32f1xx/drivers/include/stm32f1xx_hal_smartcard.h
timoML/zephyr-riscv
f14d41a7f352570dcd534d5af0819a33c7e728ae
[ "Apache-2.0" ]
25
2019-05-24T18:07:11.000Z
2022-03-03T19:48:36.000Z
/** ****************************************************************************** * @file stm32f1xx_hal_smartcard.h * @author MCD Application Team * @version V1.1.0 * @date 14-April-2017 * @brief Header file of SMARTCARD HAL module. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2017 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F1xx_HAL_SMARTCARD_H #define __STM32F1xx_HAL_SMARTCARD_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f1xx_hal_def.h" /** @addtogroup STM32F1xx_HAL_Driver * @{ */ /** @addtogroup SMARTCARD * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup SMARTCARD_Exported_Types SMARTCARD Exported Types * @{ */ /** * @brief SMARTCARD Init Structure definition */ typedef struct { uint32_t BaudRate; /*!< This member configures the SmartCard communication baud rate. The baud rate is computed using the following formula: - IntegerDivider = ((PCLKx) / (16 * (hsmartcard->Init.BaudRate))) - FractionalDivider = ((IntegerDivider - ((uint32_t) IntegerDivider)) * 16) + 0.5 */ uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. This parameter can be a value of @ref SMARTCARD_Word_Length */ uint32_t StopBits; /*!< Specifies the number of stop bits transmitted. This parameter can be a value of @ref SMARTCARD_Stop_Bits */ uint32_t Parity; /*!< Specifies the parity mode. This parameter can be a value of @ref SMARTCARD_Parity @note When parity is enabled, the computed parity is inserted at the MSB position of the transmitted data (9th bit when the word length is set to 9 data bits; 8th bit when the word length is set to 8 data bits).*/ uint32_t Mode; /*!< Specifies whether the Receive or Transmit mode is enabled or disabled. This parameter can be a value of @ref SMARTCARD_Mode */ uint32_t CLKPolarity; /*!< Specifies the steady state of the serial clock. This parameter can be a value of @ref SMARTCARD_Clock_Polarity */ uint32_t CLKPhase; /*!< Specifies the clock transition on which the bit capture is made. This parameter can be a value of @ref SMARTCARD_Clock_Phase */ uint32_t CLKLastBit; /*!< Specifies whether the clock pulse corresponding to the last transmitted data bit (MSB) has to be output on the SCLK pin in synchronous mode. This parameter can be a value of @ref SMARTCARD_Last_Bit */ uint32_t Prescaler; /*!< Specifies the SmartCard Prescaler value used for dividing the system clock to provide the smartcard clock. The value given in the register (5 significant bits) is multiplied by 2 to give the division factor of the source clock frequency. This parameter can be a value of @ref SMARTCARD_Prescaler */ uint32_t GuardTime; /*!< Specifies the SmartCard Guard Time value in terms of number of baud clocks */ uint32_t NACKState; /*!< Specifies the SmartCard NACK Transmission state This parameter can be a value of @ref SMARTCARD_NACK_State */ }SMARTCARD_InitTypeDef; /** * @brief HAL SMARTCARD State structures definition * @note HAL SMARTCARD State value is a combination of 2 different substates: gState and RxState. * - gState contains SMARTCARD state information related to global Handle management * and also information related to Tx operations. * gState value coding follow below described bitmap : * b7-b6 Error information * 00 : No Error * 01 : (Not Used) * 10 : Timeout * 11 : Error * b5 IP initilisation status * 0 : Reset (IP not initialized) * 1 : Init done (IP not initialized. HAL SMARTCARD Init function already called) * b4-b3 (not used) * xx : Should be set to 00 * b2 Intrinsic process state * 0 : Ready * 1 : Busy (IP busy with some configuration or internal operations) * b1 (not used) * x : Should be set to 0 * b0 Tx state * 0 : Ready (no Tx operation ongoing) * 1 : Busy (Tx operation ongoing) * - RxState contains information related to Rx operations. * RxState value coding follow below described bitmap : * b7-b6 (not used) * xx : Should be set to 00 * b5 IP initilisation status * 0 : Reset (IP not initialized) * 1 : Init done (IP not initialized) * b4-b2 (not used) * xxx : Should be set to 000 * b1 Rx state * 0 : Ready (no Rx operation ongoing) * 1 : Busy (Rx operation ongoing) * b0 (not used) * x : Should be set to 0. */ typedef enum { HAL_SMARTCARD_STATE_RESET = 0x00U, /*!< Peripheral is not yet Initialized Value is allowed for gState and RxState */ HAL_SMARTCARD_STATE_READY = 0x20U, /*!< Peripheral Initialized and ready for use Value is allowed for gState and RxState */ HAL_SMARTCARD_STATE_BUSY = 0x24U, /*!< an internal process is ongoing Value is allowed for gState only */ HAL_SMARTCARD_STATE_BUSY_TX = 0x21U, /*!< Data Transmission process is ongoing Value is allowed for gState only */ HAL_SMARTCARD_STATE_BUSY_RX = 0x22U, /*!< Data Reception process is ongoing Value is allowed for RxState only */ HAL_SMARTCARD_STATE_BUSY_TX_RX = 0x23U, /*!< Data Transmission and Reception process is ongoing Not to be used for neither gState nor RxState. Value is result of combination (Or) between gState and RxState values */ HAL_SMARTCARD_STATE_TIMEOUT = 0xA0U, /*!< Timeout state Value is allowed for gState only */ HAL_SMARTCARD_STATE_ERROR = 0xE0U /*!< Error Value is allowed for gState only */ }HAL_SMARTCARD_StateTypeDef; /** * @brief SMARTCARD handle Structure definition */ typedef struct { USART_TypeDef *Instance; /*!< USART registers base address */ SMARTCARD_InitTypeDef Init; /*!< SmartCard communication parameters */ uint8_t *pTxBuffPtr; /*!< Pointer to SmartCard Tx transfer Buffer */ uint16_t TxXferSize; /*!< SmartCard Tx Transfer size */ __IO uint16_t TxXferCount; /*!< SmartCard Tx Transfer Counter */ uint8_t *pRxBuffPtr; /*!< Pointer to SmartCard Rx transfer Buffer */ uint16_t RxXferSize; /*!< SmartCard Rx Transfer size */ __IO uint16_t RxXferCount; /*!< SmartCard Rx Transfer Counter */ DMA_HandleTypeDef *hdmatx; /*!< SmartCard Tx DMA Handle parameters */ DMA_HandleTypeDef *hdmarx; /*!< SmartCard Rx DMA Handle parameters */ HAL_LockTypeDef Lock; /*!< Locking object */ __IO HAL_SMARTCARD_StateTypeDef gState; /*!< SmartCard state information related to global Handle management and also related to Tx operations. This parameter can be a value of @ref HAL_SMARTCARD_StateTypeDef */ __IO HAL_SMARTCARD_StateTypeDef RxState; /*!< SmartCard state information related to Rx operations. This parameter can be a value of @ref HAL_SMARTCARD_StateTypeDef */ __IO uint32_t ErrorCode; /*!< SmartCard Error code */ }SMARTCARD_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup SMARTCARD_Exported_Constants SMARTCARD Exported constants * @{ */ /** @defgroup SMARTCARD_Error_Code SMARTCARD Error Code * @{ */ #define HAL_SMARTCARD_ERROR_NONE 0x00000000U /*!< No error */ #define HAL_SMARTCARD_ERROR_PE 0x00000001U /*!< Parity error */ #define HAL_SMARTCARD_ERROR_NE 0x00000002U /*!< Noise error */ #define HAL_SMARTCARD_ERROR_FE 0x00000004U /*!< Frame error */ #define HAL_SMARTCARD_ERROR_ORE 0x00000008U /*!< OverRun error */ #define HAL_SMARTCARD_ERROR_DMA 0x00000010U /*!< DMA transfer error */ /** * @} */ /** @defgroup SMARTCARD_Word_Length SMARTCARD Word Length * @{ */ #define SMARTCARD_WORDLENGTH_9B ((uint32_t)USART_CR1_M) /** * @} */ /** @defgroup SMARTCARD_Stop_Bits SMARTCARD Number of Stop Bits * @{ */ #define SMARTCARD_STOPBITS_0_5 ((uint32_t)USART_CR2_STOP_0) #define SMARTCARD_STOPBITS_1_5 ((uint32_t)(USART_CR2_STOP_0 | USART_CR2_STOP_1)) /** * @} */ /** @defgroup SMARTCARD_Parity SMARTCARD Parity * @{ */ #define SMARTCARD_PARITY_EVEN ((uint32_t)USART_CR1_PCE) #define SMARTCARD_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) /** * @} */ /** @defgroup SMARTCARD_Mode SMARTCARD Mode * @{ */ #define SMARTCARD_MODE_RX ((uint32_t)USART_CR1_RE) #define SMARTCARD_MODE_TX ((uint32_t)USART_CR1_TE) #define SMARTCARD_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) /** * @} */ /** @defgroup SMARTCARD_Clock_Polarity SMARTCARD Clock Polarity * @{ */ #define SMARTCARD_POLARITY_LOW 0x00000000U #define SMARTCARD_POLARITY_HIGH ((uint32_t)USART_CR2_CPOL) /** * @} */ /** @defgroup SMARTCARD_Clock_Phase SMARTCARD Clock Phase * @{ */ #define SMARTCARD_PHASE_1EDGE 0x00000000U #define SMARTCARD_PHASE_2EDGE ((uint32_t)USART_CR2_CPHA) /** * @} */ /** @defgroup SMARTCARD_Last_Bit SMARTCARD Last Bit * @{ */ #define SMARTCARD_LASTBIT_DISABLE 0x00000000U #define SMARTCARD_LASTBIT_ENABLE ((uint32_t)USART_CR2_LBCL) /** * @} */ /** @defgroup SMARTCARD_NACK_State SMARTCARD NACK State * @{ */ #define SMARTCARD_NACK_ENABLE ((uint32_t)USART_CR3_NACK) #define SMARTCARD_NACK_DISABLE 0x00000000U /** * @} */ /** @defgroup SMARTCARD_DMA_Requests SMARTCARD DMA requests * @{ */ #define SMARTCARD_DMAREQ_TX ((uint32_t)USART_CR3_DMAT) #define SMARTCARD_DMAREQ_RX ((uint32_t)USART_CR3_DMAR) /** * @} */ /** @defgroup SMARTCARD_Prescaler SMARTCARD Prescaler * @{ */ #define SMARTCARD_PRESCALER_SYSCLK_DIV2 0x00000001U /*!< SYSCLK divided by 2 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV4 0x00000002U /*!< SYSCLK divided by 4 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV6 0x00000003U /*!< SYSCLK divided by 6 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV8 0x00000004U /*!< SYSCLK divided by 8 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV10 0x00000005U /*!< SYSCLK divided by 10 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV12 0x00000006U /*!< SYSCLK divided by 12 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV14 0x00000007U /*!< SYSCLK divided by 14 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV16 0x00000008U /*!< SYSCLK divided by 16 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV18 0x00000009U /*!< SYSCLK divided by 18 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV20 0x0000000AU /*!< SYSCLK divided by 20 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV22 0x0000000BU /*!< SYSCLK divided by 22 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV24 0x0000000CU /*!< SYSCLK divided by 24 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV26 0x0000000DU /*!< SYSCLK divided by 26 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV28 0x0000000EU /*!< SYSCLK divided by 28 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV30 0x0000000FU /*!< SYSCLK divided by 30 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV32 0x00000010U /*!< SYSCLK divided by 32 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV34 0x00000011U /*!< SYSCLK divided by 34 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV36 0x00000012U /*!< SYSCLK divided by 36 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV38 0x00000013U /*!< SYSCLK divided by 38 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV40 0x00000014U /*!< SYSCLK divided by 40 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV42 0x00000015U /*!< SYSCLK divided by 42 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV44 0x00000016U /*!< SYSCLK divided by 44 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV46 0x00000017U /*!< SYSCLK divided by 46 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV48 0x00000018U /*!< SYSCLK divided by 48 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV50 0x00000019U /*!< SYSCLK divided by 50 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV52 0x0000001AU /*!< SYSCLK divided by 52 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV54 0x0000001BU /*!< SYSCLK divided by 54 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV56 0x0000001CU /*!< SYSCLK divided by 56 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV58 0x0000001DU /*!< SYSCLK divided by 58 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV60 0x0000001EU /*!< SYSCLK divided by 60 */ #define SMARTCARD_PRESCALER_SYSCLK_DIV62 0x0000001FU /*!< SYSCLK divided by 62 */ /** * @} */ /** @defgroup SmartCard_Flags SMARTCARD Flags * Elements values convention: 0xXXXX * - 0xXXXX : Flag mask in the SR register * @{ */ #define SMARTCARD_FLAG_TXE ((uint32_t)USART_SR_TXE) #define SMARTCARD_FLAG_TC ((uint32_t)USART_SR_TC) #define SMARTCARD_FLAG_RXNE ((uint32_t)USART_SR_RXNE) #define SMARTCARD_FLAG_IDLE ((uint32_t)USART_SR_IDLE) #define SMARTCARD_FLAG_ORE ((uint32_t)USART_SR_ORE) #define SMARTCARD_FLAG_NE ((uint32_t)USART_SR_NE) #define SMARTCARD_FLAG_FE ((uint32_t)USART_SR_FE) #define SMARTCARD_FLAG_PE ((uint32_t)USART_SR_PE) /** * @} */ /** @defgroup SmartCard_Interrupt_definition SMARTCARD Interrupts Definition * Elements values convention: 0xY000XXXX * - XXXX : Interrupt mask in the XX register * - Y : Interrupt source register (2bits) * - 01: CR1 register * - 11: CR3 register * @{ */ #define SMARTCARD_IT_PE ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28U | USART_CR1_PEIE)) #define SMARTCARD_IT_TXE ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28U | USART_CR1_TXEIE)) #define SMARTCARD_IT_TC ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28U | USART_CR1_TCIE)) #define SMARTCARD_IT_RXNE ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28U | USART_CR1_RXNEIE)) #define SMARTCARD_IT_IDLE ((uint32_t)(SMARTCARD_CR1_REG_INDEX << 28U | USART_CR1_IDLEIE)) #define SMARTCARD_IT_ERR ((uint32_t)(SMARTCARD_CR3_REG_INDEX << 28U | USART_CR3_EIE)) /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup SMARTCARD_Exported_Macros SMARTCARD Exported Macros * @{ */ /** @brief Reset SMARTCARD handle gstate & RxState * @param __HANDLE__: specifies the SMARTCARD Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). */ #define __HAL_SMARTCARD_RESET_HANDLE_STATE(__HANDLE__) do{ \ (__HANDLE__)->gState = HAL_SMARTCARD_STATE_RESET; \ (__HANDLE__)->RxState = HAL_SMARTCARD_STATE_RESET; \ } while(0U) /** @brief Flush the Smartcard DR register * @param __HANDLE__: specifies the SMARTCARD Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). */ #define __HAL_SMARTCARD_FLUSH_DRREGISTER(__HANDLE__) ((__HANDLE__)->Instance->DR) /** @brief Check whether the specified Smartcard flag is set or not. * @param __HANDLE__: specifies the SMARTCARD Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). * @param __FLAG__: specifies the flag to check. * This parameter can be one of the following values: * @arg SMARTCARD_FLAG_TXE: Transmit data register empty flag * @arg SMARTCARD_FLAG_TC: Transmission Complete flag * @arg SMARTCARD_FLAG_RXNE: Receive data register not empty flag * @arg SMARTCARD_FLAG_IDLE: Idle Line detection flag * @arg SMARTCARD_FLAG_ORE: OverRun Error flag * @arg SMARTCARD_FLAG_NE: Noise Error flag * @arg SMARTCARD_FLAG_FE: Framing Error flag * @arg SMARTCARD_FLAG_PE: Parity Error flag * @retval The new state of __FLAG__ (TRUE or FALSE). */ #define __HAL_SMARTCARD_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) /** @brief Clear the specified Smartcard pending flags. * @param __HANDLE__: specifies the SMARTCARD Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). * @param __FLAG__: specifies the flag to check. * This parameter can be any combination of the following values: * @arg SMARTCARD_FLAG_TC: Transmission Complete flag. * @arg SMARTCARD_FLAG_RXNE: Receive data register not empty flag. * * @note PE (Parity error), FE (Framing error), NE (Noise error) and ORE (OverRun * error) flags are cleared by software sequence: a read operation to * USART_SR register followed by a read operation to USART_DR register. * @note RXNE flag can be also cleared by a read to the USART_DR register. * @note TC flag can be also cleared by software sequence: a read operation to * USART_SR register followed by a write operation to USART_DR register. * @note TXE flag is cleared only by a write to the USART_DR register. */ #define __HAL_SMARTCARD_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR = ~(__FLAG__)) /** @brief Clear the SMARTCARD PE pending flag. * @param __HANDLE__: specifies the USART Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). */ #define __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) \ do{ \ __IO uint32_t tmpreg = 0x00U; \ tmpreg = (__HANDLE__)->Instance->SR; \ tmpreg = (__HANDLE__)->Instance->DR; \ UNUSED(tmpreg); \ } while(0U) /** @brief Clear the SMARTCARD FE pending flag. * @param __HANDLE__: specifies the USART Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). */ #define __HAL_SMARTCARD_CLEAR_FEFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the SMARTCARD NE pending flag. * @param __HANDLE__: specifies the USART Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). */ #define __HAL_SMARTCARD_CLEAR_NEFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the SMARTCARD ORE pending flag. * @param __HANDLE__: specifies the USART Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). */ #define __HAL_SMARTCARD_CLEAR_OREFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) /** @brief Clear the SMARTCARD IDLE pending flag. * @param __HANDLE__: specifies the USART Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). */ #define __HAL_SMARTCARD_CLEAR_IDLEFLAG(__HANDLE__) __HAL_SMARTCARD_CLEAR_PEFLAG(__HANDLE__) /** @brief Enable the specified SmartCard interrupt. * @param __HANDLE__: specifies the SMARTCARD Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). * @param __INTERRUPT__: specifies the SMARTCARD interrupt to enable. * This parameter can be one of the following values: * @arg SMARTCARD_IT_TXE: Transmit Data Register empty interrupt * @arg SMARTCARD_IT_TC: Transmission complete interrupt * @arg SMARTCARD_IT_RXNE: Receive Data register not empty interrupt * @arg SMARTCARD_IT_IDLE: Idle line detection interrupt * @arg SMARTCARD_IT_PE: Parity Error interrupt * @arg SMARTCARD_IT_ERR: Error interrupt(Frame error, noise error, overRun error) */ #define __HAL_SMARTCARD_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28U) == SMARTCARD_CR1_REG_INDEX)? ((__HANDLE__)->Instance->CR1 |= ((__INTERRUPT__) & SMARTCARD_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 |= ((__INTERRUPT__) & SMARTCARD_IT_MASK))) /** @brief Disable the specified SmartCard interrupt. * @param __HANDLE__: specifies the SMARTCARD Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). * @param __INTERRUPT__: specifies the SMARTCARD interrupt to disable. * This parameter can be one of the following values: * @arg SMARTCARD_IT_TXE: Transmit Data Register empty interrupt * @arg SMARTCARD_IT_TC: Transmission complete interrupt * @arg SMARTCARD_IT_RXNE: Receive Data register not empty interrupt * @arg SMARTCARD_IT_IDLE: Idle line detection interrupt * @arg SMARTCARD_IT_PE: Parity Error interrupt * @arg SMARTCARD_IT_ERR: Error interrupt(Frame error, noise error, overRun error) */ #define __HAL_SMARTCARD_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((((__INTERRUPT__) >> 28U) == SMARTCARD_CR1_REG_INDEX)? ((__HANDLE__)->Instance->CR1 &= ~((__INTERRUPT__) & SMARTCARD_IT_MASK)): \ ((__HANDLE__)->Instance->CR3 &= ~ ((__INTERRUPT__) & SMARTCARD_IT_MASK))) /** @brief Checks whether the specified SmartCard interrupt has occurred or not. * @param __HANDLE__: specifies the SmartCard Handle. * @param __IT__: specifies the SMARTCARD interrupt source to check. * This parameter can be one of the following values: * @arg SMARTCARD_IT_TXE: Transmit Data Register empty interrupt * @arg SMARTCARD_IT_TC: Transmission complete interrupt * @arg SMARTCARD_IT_RXNE: Receive Data register not empty interrupt * @arg SMARTCARD_IT_IDLE: Idle line detection interrupt * @arg SMARTCARD_IT_ERR: Error interrupt * @arg SMARTCARD_IT_PE: Parity Error interrupt * @retval The new state of __IT__ (TRUE or FALSE). */ #define __HAL_SMARTCARD_GET_IT_SOURCE(__HANDLE__, __IT__) (((((__IT__) >> 28U) == SMARTCARD_CR1_REG_INDEX)? (__HANDLE__)->Instance->CR1: (__HANDLE__)->Instance->CR3) & (((uint32_t)(__IT__)) & SMARTCARD_IT_MASK)) /** @brief Enable the USART associated to the SMARTCARD Handle * @param __HANDLE__: specifies the SMARTCARD Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). */ #define __HAL_SMARTCARD_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= USART_CR1_UE) /** @brief Disable the USART associated to the SMARTCARD Handle * @param __HANDLE__: specifies the SMARTCARD Handle. * SMARTCARD Handle selects the USARTx peripheral (USART availability and x value depending on device). */ #define __HAL_SMARTCARD_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) /** @brief Macros to enable the SmartCard DMA request. * @param __HANDLE__: specifies the SmartCard Handle. * @param __REQUEST__: specifies the SmartCard DMA request. * This parameter can be one of the following values: * @arg SMARTCARD_DMAREQ_TX: SmartCard DMA transmit request * @arg SMARTCARD_DMAREQ_RX: SmartCard DMA receive request */ #define __HAL_SMARTCARD_DMA_REQUEST_ENABLE(__HANDLE__, __REQUEST__) ((__HANDLE__)->Instance->CR3 |= (__REQUEST__)) /** @brief Macros to disable the SmartCard DMA request. * @param __HANDLE__: specifies the SmartCard Handle. * @param __REQUEST__: specifies the SmartCard DMA request. * This parameter can be one of the following values: * @arg SMARTCARD_DMAREQ_TX: SmartCard DMA transmit request * @arg SMARTCARD_DMAREQ_RX: SmartCard DMA receive request */ #define __HAL_SMARTCARD_DMA_REQUEST_DISABLE(__HANDLE__, __REQUEST__) ((__HANDLE__)->Instance->CR3 &= ~(__REQUEST__)) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup SMARTCARD_Exported_Functions * @{ */ /** @addtogroup SMARTCARD_Exported_Functions_Group1 * @{ */ /* Initialization/de-initialization functions **********************************/ HAL_StatusTypeDef HAL_SMARTCARD_Init(SMARTCARD_HandleTypeDef *hsc); HAL_StatusTypeDef HAL_SMARTCARD_ReInit(SMARTCARD_HandleTypeDef *hsc); HAL_StatusTypeDef HAL_SMARTCARD_DeInit(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_MspInit(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_MspDeInit(SMARTCARD_HandleTypeDef *hsc); /** * @} */ /** @addtogroup SMARTCARD_Exported_Functions_Group2 * @{ */ /* IO operation functions *******************************************************/ HAL_StatusTypeDef HAL_SMARTCARD_Transmit(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SMARTCARD_Receive(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size, uint32_t Timeout); HAL_StatusTypeDef HAL_SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SMARTCARD_Transmit_DMA(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); HAL_StatusTypeDef HAL_SMARTCARD_Receive_DMA(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); /* Transfer Abort functions */ HAL_StatusTypeDef HAL_SMARTCARD_Abort(SMARTCARD_HandleTypeDef *hsc); HAL_StatusTypeDef HAL_SMARTCARD_AbortTransmit(SMARTCARD_HandleTypeDef *hsc); HAL_StatusTypeDef HAL_SMARTCARD_AbortReceive(SMARTCARD_HandleTypeDef *hsc); HAL_StatusTypeDef HAL_SMARTCARD_Abort_IT(SMARTCARD_HandleTypeDef *hsc); HAL_StatusTypeDef HAL_SMARTCARD_AbortTransmit_IT(SMARTCARD_HandleTypeDef *hsc); HAL_StatusTypeDef HAL_SMARTCARD_AbortReceive_IT(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_IRQHandler(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_TxCpltCallback(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_RxCpltCallback(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_ErrorCallback(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_AbortCpltCallback(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_AbortTransmitCpltCallback(SMARTCARD_HandleTypeDef *hsc); void HAL_SMARTCARD_AbortReceiveCpltCallback(SMARTCARD_HandleTypeDef *hsc); /** * @} */ /** @addtogroup SMARTCARD_Exported_Functions_Group3 * @{ */ /* Peripheral State functions **************************************************/ HAL_SMARTCARD_StateTypeDef HAL_SMARTCARD_GetState(SMARTCARD_HandleTypeDef *hsc); uint32_t HAL_SMARTCARD_GetError(SMARTCARD_HandleTypeDef *hsc); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @defgroup SMARTCARD_Private_Constants SMARTCARD Private Constants * @{ */ /** @brief SMARTCARD interruptions flag mask * */ #define SMARTCARD_IT_MASK 0x0000FFFFU #define SMARTCARD_CR1_REG_INDEX 1U #define SMARTCARD_CR3_REG_INDEX 3U /** * @} */ /* Private macros --------------------------------------------------------*/ /** @defgroup SMARTCARD_Private_Macros SMARTCARD Private Macros * @{ */ #define IS_SMARTCARD_WORD_LENGTH(LENGTH) ((LENGTH) == SMARTCARD_WORDLENGTH_9B) #define IS_SMARTCARD_STOPBITS(STOPBITS) (((STOPBITS) == SMARTCARD_STOPBITS_0_5) || \ ((STOPBITS) == SMARTCARD_STOPBITS_1_5)) #define IS_SMARTCARD_PARITY(PARITY) (((PARITY) == SMARTCARD_PARITY_EVEN) || \ ((PARITY) == SMARTCARD_PARITY_ODD)) #define IS_SMARTCARD_MODE(MODE) ((((MODE) & 0x0000FFF3U) == 0x00U) && ((MODE) != 0x000000U)) #define IS_SMARTCARD_POLARITY(CPOL) (((CPOL) == SMARTCARD_POLARITY_LOW) || ((CPOL) == SMARTCARD_POLARITY_HIGH)) #define IS_SMARTCARD_PHASE(CPHA) (((CPHA) == SMARTCARD_PHASE_1EDGE) || ((CPHA) == SMARTCARD_PHASE_2EDGE)) #define IS_SMARTCARD_LASTBIT(LASTBIT) (((LASTBIT) == SMARTCARD_LASTBIT_DISABLE) || \ ((LASTBIT) == SMARTCARD_LASTBIT_ENABLE)) #define IS_SMARTCARD_NACK_STATE(NACK) (((NACK) == SMARTCARD_NACK_ENABLE) || \ ((NACK) == SMARTCARD_NACK_DISABLE)) #define IS_SMARTCARD_BAUDRATE(BAUDRATE) ((BAUDRATE) < 4500001U) #define SMARTCARD_DIV(_PCLK_, _BAUD_) (((_PCLK_)*25U)/(4U*(_BAUD_))) #define SMARTCARD_DIVMANT(_PCLK_, _BAUD_) (SMARTCARD_DIV((_PCLK_), (_BAUD_))/100U) #define SMARTCARD_DIVFRAQ(_PCLK_, _BAUD_) (((SMARTCARD_DIV((_PCLK_), (_BAUD_)) - (SMARTCARD_DIVMANT((_PCLK_), (_BAUD_)) * 100U)) * 16U + 50U) / 100U) /* SMARTCARD BRR = mantissa + overflow + fraction = (SMARTCARD DIVMANT << 4) + (SMARTCARD DIVFRAQ & 0xF0) + (SMARTCARD DIVFRAQ & 0x0FU) */ #define SMARTCARD_BRR(_PCLK_, _BAUD_) (((SMARTCARD_DIVMANT((_PCLK_), (_BAUD_)) << 4U) + \ (SMARTCARD_DIVFRAQ((_PCLK_), (_BAUD_)) & 0xF0U)) + \ (SMARTCARD_DIVFRAQ((_PCLK_), (_BAUD_)) & 0x0FU)) /** * @} */ /* Private functions ---------------------------------------------------------*/ /** @defgroup SMARTCARD_Private_Functions SMARTCARD Private Functions * @{ */ /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F1xx_HAL_SMARTCARD_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
51.600583
212
0.604949
[ "object" ]
b11aea6c2d47ae29a5dff242f962d9f34c2ba980
1,080
h
C
main/util.h
ayumu-bekki/irrigation_system
630341215ab524bd7e9f908ab18949e2788c8609
[ "MIT" ]
null
null
null
main/util.h
ayumu-bekki/irrigation_system
630341215ab524bd7e9f908ab18949e2788c8609
[ "MIT" ]
1
2021-08-16T07:48:25.000Z
2021-08-16T07:48:25.000Z
main/util.h
ayumu-bekki/irrigation_system
630341215ab524bd7e9f908ab18949e2788c8609
[ "MIT" ]
null
null
null
#ifndef UTIL_H_ #define UTIL_H_ // ESP32 Irrigation system // (C)2021 bekki.jp // Utilities // Include ---------------------- #include <string> #include <vector> #include <chrono> namespace IrrigationSystem { namespace Util { /// Sleep void SleepMillisecond(const unsigned int sleepMillisecond); /// SyncTime void SyncSntpObtainTime(); /// GetEpoch std::time_t GetEpoch(); /// Epoch To Local Time std::tm EpochToLocalTime(std::time_t epoch); /// GetLocalTime std::tm GetLocalTime(); /// Get Time To String (yyyy/dd/mm hh:mm:ss) std::string TimeToStr(const std::tm& timeInfo); /// Get Now Date String (yyyy/dd/mm hh:mm:ss) std::string GetNowTimeStr(); /// Initialie Local Time Zone void InitTimeZone(); /// Gregorian calendar to Modified Julian Date(修正ユリウス日) int GregToMJD(const std::tm& timeInfo); /// Get ChronoMinutes from hours and minutes. std::chrono::minutes GetChronoHourMinutes(const std::tm& timeInfo); /// Split Text std::vector<std::string> SplitString(const std::string &str, const char delim); } // Util } // IrrigationSystem #endif // UTIL_H_ // EOF
20.377358
79
0.709259
[ "vector" ]
b11c769643a29fb67cb34c6733c8ac3c737b66a7
124,288
c
C
arch/arm/src/stm32f7/stm32_ethernet.c
adamfeuer/incubator-nuttx
0b90ad3dd4e549cfca3416b223974a08fb03fa1c
[ "Apache-2.0" ]
1
2021-01-07T20:54:15.000Z
2021-01-07T20:54:15.000Z
arch/arm/src/stm32f7/stm32_ethernet.c
adamfeuer/incubator-nuttx
0b90ad3dd4e549cfca3416b223974a08fb03fa1c
[ "Apache-2.0" ]
null
null
null
arch/arm/src/stm32f7/stm32_ethernet.c
adamfeuer/incubator-nuttx
0b90ad3dd4e549cfca3416b223974a08fb03fa1c
[ "Apache-2.0" ]
1
2019-12-24T07:25:49.000Z
2019-12-24T07:25:49.000Z
/**************************************************************************** * arch/arm/src/stm32f7/stm32_ethernet.c * * Copyright (C) 2015-2018 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <gnutt@nuttx.org> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <stdint.h> #include <stdbool.h> #include <time.h> #include <string.h> #include <debug.h> #include <queue.h> #include <errno.h> #include <arpa/inet.h> #include <nuttx/arch.h> #include <nuttx/irq.h> #include <nuttx/wdog.h> #include <nuttx/wqueue.h> #include <nuttx/signal.h> #include <nuttx/net/mii.h> #include <nuttx/net/arp.h> #include <nuttx/net/netdev.h> #include <crc64.h> #if defined(CONFIG_NET_PKT) # include <nuttx/net/pkt.h> #endif #include "arm_internal.h" #include "barriers.h" #include "hardware/stm32_syscfg.h" #include "hardware/stm32_pinmap.h" #include "stm32_gpio.h" #include "stm32_rcc.h" #include "stm32_ethernet.h" #include "stm32_uid.h" #include <arch/board/board.h> /* STM32F7_NETHERNET determines the number of physical interfaces that can * be supported by the hardware. CONFIG_STM32F7_ETHMAC will defined if * any STM32F7 Ethernet support is enabled in the configuration. */ #if STM32F7_NETHERNET > 0 && defined(CONFIG_STM32F7_ETHMAC) /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* Memory synchronization */ #define MEMORY_SYNC() do { ARM_DSB(); ARM_ISB(); } while (0) /* Configuration ************************************************************/ /* See boards/arm/stm32/stm3240g-eval/README.txt for an explanation of the * configuration settings. */ #if STM32F7_NETHERNET > 1 # error "Logic to support multiple Ethernet interfaces is incomplete" #endif /* If processing is not done at the interrupt level, then work queue support * is required. */ #if !defined(CONFIG_SCHED_WORKQUEUE) # error Work queue support is required #endif /* The low priority work queue is preferred. If it is not enabled, LPWORK * will be the same as HPWORK. * * NOTE: However, the network should NEVER run on the high priority work * queue! That queue is intended only to service short back end interrupt * processing that never suspends. Suspending the high priority work queue * may bring the system to its knees! */ #define ETHWORK LPWORK #ifndef CONFIG_STM32F7_PHYADDR # error "CONFIG_STM32F7_PHYADDR must be defined in the NuttX configuration" #endif #if !defined(CONFIG_STM32F7_MII) && !defined(CONFIG_STM32F7_RMII) # warning "Neither CONFIG_STM32F7_MII nor CONFIG_STM32F7_RMII defined" #endif #if defined(CONFIG_STM32F7_MII) && defined(CONFIG_STM32F7_RMII) # error "Both CONFIG_STM32F7_MII and CONFIG_STM32F7_RMII defined" #endif #ifdef CONFIG_STM32F7_MII # if !defined(CONFIG_STM32F7_MII_MCO1) && !defined(CONFIG_STM32F7_MII_MCO2) && \ !defined(CONFIG_STM32F7_MII_EXTCLK) # warning "Neither CONFIG_STM32F7_MII_MCO1, CONFIG_STM32F7_MII_MCO2, nor CONFIG_STM32F7_MII_EXTCLK defined" # endif # if defined(CONFIG_STM32F7_MII_MCO1) && defined(CONFIG_STM32F7_MII_MCO2) # error "Both CONFIG_STM32F7_MII_MCO1 and CONFIG_STM32F7_MII_MCO2 defined" # endif #endif #ifdef CONFIG_STM32F7_RMII # if !defined(CONFIG_STM32F7_RMII_MCO1) && !defined(CONFIG_STM32F7_RMII_MCO2) && \ !defined(CONFIG_STM32F7_RMII_EXTCLK) # warning "Neither CONFIG_STM32F7_RMII_MCO1, CONFIG_STM32F7_RMII_MCO2, nor CONFIG_STM32F7_RMII_EXTCLK defined" # endif # if defined(CONFIG_STM32F7_RMII_MCO1) && defined(CONFIG_STM32F7_RMII_MCO2) # error "Both CONFIG_STM32F7_RMII_MCO1 and CONFIG_STM32F7_RMII_MCO2 defined" # endif #endif #ifdef CONFIG_STM32F7_AUTONEG # ifndef CONFIG_STM32F7_PHYSR # error "CONFIG_STM32F7_PHYSR must be defined in the NuttX configuration" # endif # ifdef CONFIG_STM32F7_PHYSR_ALTCONFIG # ifndef CONFIG_STM32F7_PHYSR_ALTMODE # error "CONFIG_STM32F7_PHYSR_ALTMODE must be defined in the NuttX configuration" # endif # ifndef CONFIG_STM32F7_PHYSR_10HD # error "CONFIG_STM32F7_PHYSR_10HD must be defined in the NuttX configuration" # endif # ifndef CONFIG_STM32F7_PHYSR_100HD # error "CONFIG_STM32F7_PHYSR_100HD must be defined in the NuttX configuration" # endif # ifndef CONFIG_STM32F7_PHYSR_10FD # error "CONFIG_STM32F7_PHYSR_10FD must be defined in the NuttX configuration" # endif # ifndef CONFIG_STM32F7_PHYSR_100FD # error "CONFIG_STM32F7_PHYSR_100FD must be defined in the NuttX configuration" # endif # else # ifndef CONFIG_STM32F7_PHYSR_SPEED # error "CONFIG_STM32F7_PHYSR_SPEED must be defined in the NuttX configuration" # endif # ifndef CONFIG_STM32F7_PHYSR_100MBPS # error "CONFIG_STM32F7_PHYSR_100MBPS must be defined in the NuttX configuration" # endif # ifndef CONFIG_STM32F7_PHYSR_MODE # error "CONFIG_STM32F7_PHYSR_MODE must be defined in the NuttX configuration" # endif # ifndef CONFIG_STM32F7_PHYSR_FULLDUPLEX # error "CONFIG_STM32F7_PHYSR_FULLDUPLEX must be defined in the NuttX configuration" # endif # endif #endif #ifdef CONFIG_STM32F7_ETH_PTP # warning "CONFIG_STM32F7_ETH_PTP is not yet supported" #endif /* This driver does not use enhanced descriptors. Enhanced descriptors must * be used, however, if time stamping or and/or IPv4 checksum offload is * supported. */ #undef CONFIG_STM32F7_ETH_ENHANCEDDESC #undef CONFIG_STM32F7_ETH_HWCHECKSUM /* Add 4 to the configured buffer size to account for the 2 byte checksum * memory needed at the end of the maximum size packet. Buffer sizes must * be an even multiple of 4, 8, or 16 bytes (depending on buswidth). We * will use the 16-byte alignment in all cases. */ #define OPTIMAL_ETH_BUFSIZE ((CONFIG_NET_ETH_PKTSIZE + 4 + 15) & ~15) #ifdef CONFIG_STM32F7_ETH_BUFSIZE # define ETH_BUFSIZE CONFIG_STM32F7_ETH_BUFSIZE #else # define ETH_BUFSIZE OPTIMAL_ETH_BUFSIZE #endif #if ETH_BUFSIZE > ETH_TDES1_TBS1_MASK # error "ETH_BUFSIZE is too large" #endif #if (ETH_BUFSIZE & 15) != 0 # error "ETH_BUFSIZE must be aligned" #endif #if ETH_BUFSIZE != OPTIMAL_ETH_BUFSIZE # warning "You using an incomplete/untested configuration" #endif #ifndef CONFIG_STM32F7_ETH_NRXDESC # define CONFIG_STM32F7_ETH_NRXDESC 8 #endif #ifndef CONFIG_STM32F7_ETH_NTXDESC # define CONFIG_STM32F7_ETH_NTXDESC 4 #endif /* We need at least one more free buffer than transmit buffers */ #define STM32_ETH_NFREEBUFFERS (CONFIG_STM32F7_ETH_NTXDESC+1) /* Buffers use for DMA access must begin on an address aligned with the * D-Cache line and must be an even multiple of the D-Cache line size. * These size/alignment requirements are necessary so that D-Cache flush * and invalidate operations will not have any additional effects. * * The TX and RX descriptors are normally 16 bytes in size but could be * 32 bytes in size if the enhanced descriptor format is used (it is not). */ #define DMA_BUFFER_MASK (ARMV7M_DCACHE_LINESIZE - 1) #define DMA_ALIGN_UP(n) (((n) + DMA_BUFFER_MASK) & ~DMA_BUFFER_MASK) #define DMA_ALIGN_DOWN(n) ((n) & ~DMA_BUFFER_MASK) #ifndef CONFIG_STM32F7_ETH_ENHANCEDDESC # define RXDESC_SIZE 16 # define TXDESC_SIZE 16 #else # define RXDESC_SIZE 32 # define TXDESC_SIZE 32 #endif #define RXDESC_PADSIZE DMA_ALIGN_UP(RXDESC_SIZE) #define TXDESC_PADSIZE DMA_ALIGN_UP(TXDESC_SIZE) #define ALIGNED_BUFSIZE DMA_ALIGN_UP(ETH_BUFSIZE) #define RXTABLE_SIZE (STM32F7_NETHERNET * CONFIG_STM32F7_ETH_NRXDESC) #define TXTABLE_SIZE (STM32F7_NETHERNET * CONFIG_STM32F7_ETH_NTXDESC) #define RXBUFFER_SIZE (CONFIG_STM32F7_ETH_NRXDESC * ALIGNED_BUFSIZE) #define RXBUFFER_ALLOC (STM32F7_NETHERNET * RXBUFFER_SIZE) #define TXBUFFER_SIZE (STM32_ETH_NFREEBUFFERS * ALIGNED_BUFSIZE) #define TXBUFFER_ALLOC (STM32F7_NETHERNET * TXBUFFER_SIZE) /* Extremely detailed register debug that you would normally never want * enabled. */ #ifndef CONFIG_DEBUG_NET_INFO # undef CONFIG_STM32F7_ETHMAC_REGDEBUG #endif /* Clocking *****************************************************************/ /* Set MACMIIAR CR bits depending on HCLK setting */ #if STM32_HCLK_FREQUENCY >= 20000000 && STM32_HCLK_FREQUENCY < 35000000 # define ETH_MACMIIAR_CR ETH_MACMIIAR_CR_DIV16 #elif STM32_HCLK_FREQUENCY >= 35000000 && STM32_HCLK_FREQUENCY < 60000000 # define ETH_MACMIIAR_CR ETH_MACMIIAR_CR_DIV26 #elif STM32_HCLK_FREQUENCY >= 60000000 && STM32_HCLK_FREQUENCY < 100000000 # define ETH_MACMIIAR_CR ETH_MACMIIAR_CR_DIV42 #elif STM32_HCLK_FREQUENCY >= 100000000 && STM32_HCLK_FREQUENCY < 150000000 # define ETH_MACMIIAR_CR ETH_MACMIIAR_CR_DIV62 #elif STM32_HCLK_FREQUENCY >= 150000000 && STM32_HCLK_FREQUENCY <= 216000000 # define ETH_MACMIIAR_CR ETH_MACMIIAR_CR_DIV102 #else # error "STM32_HCLK_FREQUENCY not supportable" #endif /* Timing *******************************************************************/ /* TX poll delay = 1 seconds. CLK_TCK is the number of clock ticks per * second */ #define STM32_WDDELAY (1*CLK_TCK) /* TX timeout = 1 minute */ #define STM32_TXTIMEOUT (60*CLK_TCK) /* PHY reset/configuration delays in milliseconds */ #define PHY_RESET_DELAY (65) #define PHY_CONFIG_DELAY (1000) /* PHY read/write delays in loop counts */ #define PHY_READ_TIMEOUT (0x0004ffff) #define PHY_WRITE_TIMEOUT (0x0004ffff) #define PHY_RETRY_TIMEOUT (0x00000ccc) /* MAC reset ready delays in loop counts */ #define MAC_READY_USTIMEOUT (100) /* Register values **********************************************************/ /* Clear the MACCR bits that will be setup during MAC initialization (or that * are cleared unconditionally). Per the reference manual, all reserved bits * must be retained at their reset value. * * ETH_MACCR_RE Bit 2: Receiver enable * ETH_MACCR_TE Bit 3: Transmitter enable * ETH_MACCR_DC Bit 4: Deferral check * ETH_MACCR_BL Bits 5-6: Back-off limit * ETH_MACCR_APCS Bit 7: Automatic pad/CRC stripping * ETH_MACCR_RD Bit 9: Retry disable * ETH_MACCR_IPCO Bit 10: IPv4 checksum offload * ETH_MACCR_DM Bit 11: Duplex mode * ETH_MACCR_LM Bit 12: Loopback mode * ETH_MACCR_ROD Bit 13: Receive own disable * ETH_MACCR_FES Bit 14: Fast Ethernet speed * ETH_MACCR_CSD Bit 16: Carrier sense disable * ETH_MACCR_IFG Bits 17-19: Interframe gap * ETH_MACCR_JD Bit 22: Jabber disable * ETH_MACCR_WD Bit 23: Watchdog disable * ETH_MACCR_CSTF Bits 25: CRC stripping for Type frames (F2/F4 only) */ #define MACCR_CLEAR_BITS \ (ETH_MACCR_RE | ETH_MACCR_TE | ETH_MACCR_DC | ETH_MACCR_BL_MASK | \ ETH_MACCR_APCS | ETH_MACCR_RD | ETH_MACCR_IPCO | ETH_MACCR_DM | \ ETH_MACCR_LM | ETH_MACCR_ROD | ETH_MACCR_FES | ETH_MACCR_CSD | \ ETH_MACCR_IFG_MASK | ETH_MACCR_JD | ETH_MACCR_WD | ETH_MACCR_CSTF) /* The following bits are set or left zero unconditionally in all modes. * * ETH_MACCR_RE Receiver enable 0 (disabled) * ETH_MACCR_TE Transmitter enable 0 (disabled) * ETH_MACCR_DC Deferral check 0 (disabled) * ETH_MACCR_BL Back-off limit 0 (10) * ETH_MACCR_APCS Automatic pad/CRC stripping 0 (disabled) * ETH_MACCR_RD Retry disable 1 (disabled) * ETH_MACCR_IPCO IPv4 checksum offload Depends on CONFIG_STM32F7_ETH_HWCHECKSUM * ETH_MACCR_LM Loopback mode 0 (disabled) * ETH_MACCR_ROD Receive own disable 0 (enabled) * ETH_MACCR_CSD Carrier sense disable 0 (enabled) * ETH_MACCR_IFG Interframe gap 0 (96 bits) * ETH_MACCR_JD Jabber disable 0 (enabled) * ETH_MACCR_WD Watchdog disable 0 (enabled) * ETH_MACCR_CSTF CRC stripping for Type frames 0 (disabled, F2/F4 only) * * The following are set conditionally based on mode and speed. * * ETH_MACCR_DM Duplex mode Depends on priv->fduplex * ETH_MACCR_FES Fast Ethernet speed Depends on priv->mbps100 */ #ifdef CONFIG_STM32F7_ETH_HWCHECKSUM # define MACCR_SET_BITS \ (ETH_MACCR_BL_10 | ETH_MACCR_RD | ETH_MACCR_IPCO | ETH_MACCR_IFG(96)) #else # define MACCR_SET_BITS \ (ETH_MACCR_BL_10 | ETH_MACCR_RD | ETH_MACCR_IFG(96)) #endif /* Clear the MACCR bits that will be setup during MAC initialization (or that * are cleared unconditionally). Per the reference manual, all reserved bits * must be retained at their reset value. * * ETH_MACFFR_PM Bit 0: Promiscuous mode * ETH_MACFFR_HU Bit 1: Hash unicast * ETH_MACFFR_HM Bit 2: Hash multicast * ETH_MACFFR_DAIF Bit 3: Destination address inverse filtering * ETH_MACFFR_PAM Bit 4: Pass all multicast * ETH_MACFFR_BFD Bit 5: Broadcast frames disable * ETH_MACFFR_PCF Bits 6-7: Pass control frames * ETH_MACFFR_SAIF Bit 8: Source address inverse filtering * ETH_MACFFR_SAF Bit 9: Source address filter * ETH_MACFFR_HPF Bit 10: Hash or perfect filter * ETH_MACFFR_RA Bit 31: Receive all */ #define MACFFR_CLEAR_BITS \ (ETH_MACFFR_PM | ETH_MACFFR_HU | ETH_MACFFR_HM | ETH_MACFFR_DAIF | \ ETH_MACFFR_PAM | ETH_MACFFR_BFD | ETH_MACFFR_PCF_MASK | ETH_MACFFR_SAIF | \ ETH_MACFFR_SAF | ETH_MACFFR_HPF | ETH_MACFFR_RA) /* The following bits are set or left zero unconditionally in all modes. * * ETH_MACFFR_PM Promiscuous mode 0 (disabled) * ETH_MACFFR_HU Hash unicast 0 (perfect dest filtering) * ETH_MACFFR_HM Hash multicast 0 (perfect dest filtering) * ETH_MACFFR_DAIF Destination address inverse filtering 0 (normal) * ETH_MACFFR_PAM Pass all multicast 0 (Depends on HM bit) * ETH_MACFFR_BFD Broadcast frames disable 0 (enabled) * ETH_MACFFR_PCF Pass control frames 1 (block all but PAUSE) * ETH_MACFFR_SAIF Source address inverse filtering 0 (not used) * ETH_MACFFR_SAF Source address filter 0 (disabled) * ETH_MACFFR_HPF Hash or perfect filter 0 (Only matching frames passed) * ETH_MACFFR_RA Receive all 0 (disabled) */ #define MACFFR_SET_BITS (ETH_MACFFR_PCF_PAUSE) /* Clear the MACFCR bits that will be setup during MAC initialization (or that * are cleared unconditionally). Per the reference manual, all reserved bits * must be retained at their reset value. * * ETH_MACFCR_FCB_BPA Bit 0: Flow control busy/back pressure activate * ETH_MACFCR_TFCE Bit 1: Transmit flow control enable * ETH_MACFCR_RFCE Bit 2: Receive flow control enable * ETH_MACFCR_UPFD Bit 3: Unicast pause frame detect * ETH_MACFCR_PLT Bits 4-5: Pause low threshold * ETH_MACFCR_ZQPD Bit 7: Zero-quanta pause disable * ETH_MACFCR_PT Bits 16-31: Pause time */ #define MACFCR_CLEAR_MASK \ (ETH_MACFCR_FCB_BPA | ETH_MACFCR_TFCE | ETH_MACFCR_RFCE | ETH_MACFCR_UPFD | \ ETH_MACFCR_PLT_MASK | ETH_MACFCR_ZQPD | ETH_MACFCR_PT_MASK) /* The following bits are set or left zero unconditionally in all modes. * * ETH_MACFCR_FCB_BPA Flow control busy/back pressure activate 0 (no pause control frame) * ETH_MACFCR_TFCE Transmit flow control enable 0 (disabled) * ETH_MACFCR_RFCE Receive flow control enable 0 (disabled) * ETH_MACFCR_UPFD Unicast pause frame detect 0 (disabled) * ETH_MACFCR_PLT Pause low threshold 0 (pause time - 4) * ETH_MACFCR_ZQPD Zero-quanta pause disable 1 (disabled) * ETH_MACFCR_PT Pause time 0 */ #define MACFCR_SET_MASK (ETH_MACFCR_PLT_M4 | ETH_MACFCR_ZQPD) /* Clear the DMAOMR bits that will be setup during MAC initialization (or that * are cleared unconditionally). Per the reference manual, all reserved bits * must be retained at their reset value. * * ETH_DMAOMR_SR Bit 1: Start/stop receive * TH_DMAOMR_OSF Bit 2: Operate on second frame * ETH_DMAOMR_RTC Bits 3-4: Receive threshold control * ETH_DMAOMR_FUGF Bit 6: Forward undersized good frames * ETH_DMAOMR_FEF Bit 7: Forward error frames * ETH_DMAOMR_ST Bit 13: Start/stop transmission * ETH_DMAOMR_TTC Bits 14-16: Transmit threshold control * ETH_DMAOMR_FTF Bit 20: Flush transmit FIFO * ETH_DMAOMR_TSF Bit 21: Transmit store and forward * ETH_DMAOMR_DFRF Bit 24: Disable flushing of received frames * ETH_DMAOMR_RSF Bit 25: Receive store and forward * TH_DMAOMR_DTCEFD Bit 26: Dropping of TCP/IP checksum error frames disable */ #define DMAOMR_CLEAR_MASK \ (ETH_DMAOMR_SR | ETH_DMAOMR_OSF | ETH_DMAOMR_RTC_MASK | ETH_DMAOMR_FUGF | \ ETH_DMAOMR_FEF | ETH_DMAOMR_ST | ETH_DMAOMR_TTC_MASK | ETH_DMAOMR_FTF | \ ETH_DMAOMR_TSF | ETH_DMAOMR_DFRF | ETH_DMAOMR_RSF | ETH_DMAOMR_DTCEFD) /* The following bits are set or left zero unconditionally in all modes. * * ETH_DMAOMR_SR Start/stop receive 0 (not running) * TH_DMAOMR_OSF Operate on second frame 1 (enabled) * ETH_DMAOMR_RTC Receive threshold control 0 (64 bytes) * ETH_DMAOMR_FUGF Forward undersized good frames 0 (disabled) * ETH_DMAOMR_FEF Forward error frames 0 (disabled) * ETH_DMAOMR_ST Start/stop transmission 0 (not running) * ETH_DMAOMR_TTC Transmit threshold control 0 (64 bytes) * ETH_DMAOMR_FTF Flush transmit FIFO 0 (no flush) * ETH_DMAOMR_TSF Transmit store and forward Depends on CONFIG_STM32F7_ETH_HWCHECKSUM * ETH_DMAOMR_DFRF Disable flushing of received frames 0 (enabled) * ETH_DMAOMR_RSF Receive store and forward Depends on CONFIG_STM32F7_ETH_HWCHECKSUM * TH_DMAOMR_DTCEFD Dropping of TCP/IP checksum error Depends on CONFIG_STM32F7_ETH_HWCHECKSUM * frames disable * * When the checksum offload feature is enabled, we need to enable the Store * and Forward mode: the store and forward guarantee that a whole frame is * stored in the FIFO, so the MAC can insert/verify the checksum, if the * checksum is OK the DMA can handle the frame otherwise the frame is dropped */ #ifdef CONFIG_STM32F7_ETH_HWCHECKSUM # define DMAOMR_SET_MASK \ (ETH_DMAOMR_OSF | ETH_DMAOMR_RTC_64 | ETH_DMAOMR_TTC_64 | \ ETH_DMAOMR_TSF | ETH_DMAOMR_RSF) #else # define DMAOMR_SET_MASK \ (ETH_DMAOMR_OSF | ETH_DMAOMR_RTC_64 | ETH_DMAOMR_TTC_64 | \ ETH_DMAOMR_DTCEFD) #endif /* Clear the DMABMR bits that will be setup during MAC initialization (or that * are cleared unconditionally). Per the reference manual, all reserved bits * must be retained at their reset value. * * ETH_DMABMR_SR Bit 0: Software reset * ETH_DMABMR_DA Bit 1: DMA Arbitration * ETH_DMABMR_DSL Bits 2-6: Descriptor skip length * ETH_DMABMR_EDFE Bit 7: Enhanced descriptor format enable * ETH_DMABMR_PBL Bits 8-13: Programmable burst length * ETH_DMABMR_RTPR Bits 14-15: RX TX priority ratio * ETH_DMABMR_FB Bit 16: Fixed burst * ETH_DMABMR_RDP Bits 17-22: RX DMA PBL * ETH_DMABMR_USP Bit 23: Use separate PBL * ETH_DMABMR_FPM Bit 24: 4xPBL mode * ETH_DMABMR_AAB Bit 25: Address-aligned beats * ETH_DMABMR_MB Bit 26: Mixed burst (F2/F4 only) */ #define DMABMR_CLEAR_MASK \ (ETH_DMABMR_SR | ETH_DMABMR_DA | ETH_DMABMR_DSL_MASK | ETH_DMABMR_EDFE | \ ETH_DMABMR_PBL_MASK | ETH_DMABMR_PM_MASK | ETH_DMABMR_FB | ETH_DMABMR_RDP_MASK | \ ETH_DMABMR_USP | ETH_DMABMR_FPM | ETH_DMABMR_AAB | ETH_DMABMR_MB) /* The following bits are set or left zero unconditionally in all modes. * * * ETH_DMABMR_SR Software reset 0 (no reset) * ETH_DMABMR_DA DMA Arbitration 0 (round robin) * ETH_DMABMR_DSL Descriptor skip length 0 * ETH_DMABMR_EDFE Enhanced descriptor format enable Depends on CONFIG_STM32F7_ETH_ENHANCEDDESC * ETH_DMABMR_PBL Programmable burst length 32 beats * ETH_DMABMR_RTPR RX TX priority ratio 2:1 * ETH_DMABMR_FB Fixed burst 1 (enabled) * ETH_DMABMR_RDP RX DMA PBL 32 beats * ETH_DMABMR_USP Use separate PBL 1 (enabled) * ETH_DMABMR_FPM 4xPBL mode 0 (disabled) * ETH_DMABMR_AAB Address-aligned beats 1 (enabled) * ETH_DMABMR_MB Mixed burst 0 (disabled, F2/F4 only) */ #ifdef CONFIG_STM32F7_ETH_ENHANCEDDESC # define DMABMR_SET_MASK \ (ETH_DMABMR_DSL(0) | ETH_DMABMR_PBL(32) | ETH_DMABMR_EDFE | ETH_DMABMR_RTPR_2TO1 | \ ETH_DMABMR_FB | ETH_DMABMR_RDP(32) | ETH_DMABMR_USP | ETH_DMABMR_AAB) #else # define DMABMR_SET_MASK \ (ETH_DMABMR_DSL(0) | ETH_DMABMR_PBL(32) | ETH_DMABMR_RTPR_2TO1 | ETH_DMABMR_FB | \ ETH_DMABMR_RDP(32) | ETH_DMABMR_USP | ETH_DMABMR_AAB) #endif /* Interrupt bit sets *******************************************************/ /* All interrupts in the normal and abnormal interrupt summary. Early transmit * interrupt (ETI) is excluded from the abnormal set because it causes too * many interrupts and is not interesting. */ #define ETH_DMAINT_NORMAL \ (ETH_DMAINT_TI | ETH_DMAINT_TBUI | ETH_DMAINT_RI | ETH_DMAINT_ERI) #define ETH_DMAINT_ABNORMAL \ (ETH_DMAINT_TPSI | ETH_DMAINT_TJTI | ETH_DMAINT_ROI | ETH_DMAINT_TUI | \ ETH_DMAINT_RBUI | ETH_DMAINT_RPSI | ETH_DMAINT_RWTI | /* ETH_DMAINT_ETI | */ \ ETH_DMAINT_FBEI) /* Normal receive, transmit, error interrupt enable bit sets */ #define ETH_DMAINT_RECV_ENABLE (ETH_DMAINT_NIS | ETH_DMAINT_RI) #define ETH_DMAINT_XMIT_ENABLE (ETH_DMAINT_NIS | ETH_DMAINT_TI) #define ETH_DMAINT_XMIT_DISABLE (ETH_DMAINT_TI) #ifdef CONFIG_DEBUG_NET # define ETH_DMAINT_ERROR_ENABLE (ETH_DMAINT_AIS | ETH_DMAINT_ABNORMAL) #else # define ETH_DMAINT_ERROR_ENABLE (0) #endif /* Helpers ******************************************************************/ /* This is a helper pointer for accessing the contents of the Ethernet * header */ #define BUF ((struct eth_hdr_s *)priv->dev.d_buf) /**************************************************************************** * Private Types ****************************************************************************/ /* This union type forces the allocated size of RX descriptors to be the * padded to a exact multiple of the Cortex-M7 D-Cache line size. */ union stm32_txdesc_u { uint8_t pad[TXDESC_PADSIZE]; struct eth_txdesc_s txdesc; }; union stm32_rxdesc_u { uint8_t pad[RXDESC_PADSIZE]; struct eth_rxdesc_s rxdesc; }; /* The stm32_ethmac_s encapsulates all state information for a single hardware * interface */ struct stm32_ethmac_s { uint8_t ifup : 1; /* true:ifup false:ifdown */ uint8_t mbps100 : 1; /* 100MBps operation (vs 10 MBps) */ uint8_t fduplex : 1; /* Full (vs. half) duplex */ uint8_t intf; /* Ethernet interface number */ WDOG_ID txpoll; /* TX poll timer */ WDOG_ID txtimeout; /* TX timeout timer */ struct work_s irqwork; /* For deferring interrupt work to the work queue */ struct work_s pollwork; /* For deferring poll work to the work queue */ /* This holds the information visible to the NuttX network */ struct net_driver_s dev; /* Interface understood by the network */ /* Used to track transmit and receive descriptors */ struct eth_txdesc_s *txhead; /* Next available TX descriptor */ struct eth_rxdesc_s *rxhead; /* Next available RX descriptor */ struct eth_txdesc_s *txtail; /* First "in_flight" TX descriptor */ struct eth_rxdesc_s *rxcurr; /* First RX descriptor of the segment */ uint16_t segments; /* RX segment count */ uint16_t inflight; /* Number of TX transfers "in_flight" */ sq_queue_t freeb; /* The free buffer list */ }; /**************************************************************************** * Private Data ****************************************************************************/ /* DMA buffers. DMA buffers must: * * 1. Be a multiple of the D-Cache line size. This requirement is assured * by the definition of RXDMA buffer size above. * 2. Be aligned a D-Cache line boundaries, and * 3. Be positioned in DMA-able memory. This must be managed by logic * in the linker script file. * * These DMA buffers are defined sequentially here to best assure optimal * packing of the buffers. */ /* Descriptor allocations */ static union stm32_rxdesc_u g_rxtable[RXTABLE_SIZE] __attribute__((aligned(ARMV7M_DCACHE_LINESIZE))); static union stm32_txdesc_u g_txtable[TXTABLE_SIZE] __attribute__((aligned(ARMV7M_DCACHE_LINESIZE))); /* Buffer allocations */ static uint8_t g_rxbuffer[RXBUFFER_ALLOC] __attribute__((aligned(ARMV7M_DCACHE_LINESIZE))); static uint8_t g_txbuffer[TXBUFFER_ALLOC] __attribute__((aligned(ARMV7M_DCACHE_LINESIZE))); /* These are the pre-allocated Ethernet device structures */ static struct stm32_ethmac_s g_stm32ethmac[STM32F7_NETHERNET]; /**************************************************************************** * Private Function Prototypes ****************************************************************************/ /* Register operations ******************************************************/ #ifdef CONFIG_STM32F7_ETHMAC_REGDEBUG static uint32_t stm32_getreg(uint32_t addr); static void stm32_putreg(uint32_t val, uint32_t addr); static void stm32_checksetup(void); #else # define stm32_getreg(addr) getreg32(addr) # define stm32_putreg(val,addr) putreg32(val,addr) # define stm32_checksetup() #endif /* Free buffer management */ static void stm32_initbuffer(struct stm32_ethmac_s *priv, uint8_t *txbuffer); static inline uint8_t *stm32_allocbuffer(struct stm32_ethmac_s *priv); static inline void stm32_freebuffer(struct stm32_ethmac_s *priv, uint8_t *buffer); static inline bool stm32_isfreebuffer(struct stm32_ethmac_s *priv); /* Common TX logic */ static int stm32_transmit(struct stm32_ethmac_s *priv); static int stm32_txpoll(struct net_driver_s *dev); static void stm32_dopoll(struct stm32_ethmac_s *priv); /* Interrupt handling */ static void stm32_enableint(struct stm32_ethmac_s *priv, uint32_t ierbit); static void stm32_disableint(struct stm32_ethmac_s *priv, uint32_t ierbit); static void stm32_freesegment(struct stm32_ethmac_s *priv, struct eth_rxdesc_s *rxfirst, int segments); static int stm32_recvframe(struct stm32_ethmac_s *priv); static void stm32_receive(struct stm32_ethmac_s *priv); static void stm32_freeframe(struct stm32_ethmac_s *priv); static void stm32_txdone(struct stm32_ethmac_s *priv); static void stm32_interrupt_work(void *arg); static int stm32_interrupt(int irq, void *context, FAR void *arg); /* Watchdog timer expirations */ static void stm32_txtimeout_work(void *arg); static void stm32_txtimeout_expiry(int argc, uint32_t arg, ...); static void stm32_poll_work(void *arg); static void stm32_poll_expiry(int argc, uint32_t arg, ...); /* NuttX callback functions */ static int stm32_ifup(struct net_driver_s *dev); static int stm32_ifdown(struct net_driver_s *dev); static void stm32_txavail_work(void *arg); static int stm32_txavail(struct net_driver_s *dev); #if defined(CONFIG_NET_MCASTGROUP) || defined(CONFIG_NET_ICMPv6) static int stm32_addmac(struct net_driver_s *dev, const uint8_t *mac); #endif #ifdef CONFIG_NET_MCASTGROUP static int stm32_rmmac(struct net_driver_s *dev, const uint8_t *mac); #endif #ifdef CONFIG_NETDEV_IOCTL static int stm32_ioctl(struct net_driver_s *dev, int cmd, unsigned long arg); #endif /* Descriptor Initialization */ static void stm32_txdescinit(struct stm32_ethmac_s *priv, union stm32_txdesc_u *txtable); static void stm32_rxdescinit(struct stm32_ethmac_s *priv, union stm32_rxdesc_u *rxtable, uint8_t *rxbuffer); /* PHY Initialization */ #if defined(CONFIG_NETDEV_PHY_IOCTL) && defined(CONFIG_ARCH_PHY_INTERRUPT) static int stm32_phyintenable(struct stm32_ethmac_s *priv); #endif static int stm32_phyread(uint16_t phydevaddr, uint16_t phyregaddr, uint16_t *value); static int stm32_phywrite(uint16_t phydevaddr, uint16_t phyregaddr, uint16_t value); #ifdef CONFIG_ETH0_PHY_DM9161 static inline int stm32_dm9161(struct stm32_ethmac_s *priv); #endif static int stm32_phyinit(struct stm32_ethmac_s *priv); /* MAC/DMA Initialization */ #ifdef CONFIG_STM32F7_MII static inline void stm32_selectmii(void); #endif #ifdef CONFIG_STM32F7_RMII static inline void stm32_selectrmii(void); #endif static inline void stm32_ethgpioconfig(struct stm32_ethmac_s *priv); static void stm32_ethreset(struct stm32_ethmac_s *priv); static int stm32_macconfig(struct stm32_ethmac_s *priv); static void stm32_macaddress(struct stm32_ethmac_s *priv); #ifdef CONFIG_NET_ICMPv6 static void stm32_ipv6multicast(struct stm32_ethmac_s *priv); #endif static int stm32_macenable(struct stm32_ethmac_s *priv); static int stm32_ethconfig(struct stm32_ethmac_s *priv); /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: stm32_getreg * * Description: * This function may to used to intercept an monitor all register accesses. * Clearly this is nothing you would want to do unless you are debugging * this driver. * * Input Parameters: * addr - The register address to read * * Returned Value: * The value read from the register * ****************************************************************************/ #ifdef CONFIG_STM32F7_ETHMAC_REGDEBUG static uint32_t stm32_getreg(uint32_t addr) { static uint32_t prevaddr = 0; static uint32_t preval = 0; static uint32_t count = 0; /* Read the value from the register */ uint32_t val = getreg32(addr); /* Is this the same value that we read from the same register last time? * Are we polling the register? If so, suppress some of the output. */ if (addr == prevaddr && val == preval) { if (count == 0xffffffff || ++count > 3) { if (count == 4) { ninfo("...\n"); } return val; } } /* No this is a new address or value */ else { /* Did we print "..." for the previous value? */ if (count > 3) { /* Yes.. then show how many times the value repeated */ ninfo("[repeats %d more times]\n", count - 3); } /* Save the new address, value, and count */ prevaddr = addr; preval = val; count = 1; } /* Show the register value read */ ninfo("%08x->%08x\n", addr, val); return val; } #endif /**************************************************************************** * Name: stm32_putreg * * Description: * This function may to used to intercept an monitor all register accesses. * Clearly this is nothing you would want to do unless you are debugging * this driver. * * Input Parameters: * val - The value to write to the register * addr - The register address to read * * Returned Value: * None * ****************************************************************************/ #ifdef CONFIG_STM32F7_ETHMAC_REGDEBUG static void stm32_putreg(uint32_t val, uint32_t addr) { /* Show the register value being written */ ninfo("%08x<-%08x\n", addr, val); /* Write the value */ putreg32(val, addr); } #endif /**************************************************************************** * Name: stm32_checksetup * * Description: * Show the state of critical configuration registers. * * Input Parameters: * None * * Returned Value: * None * ****************************************************************************/ #ifdef CONFIG_STM32F7_ETHMAC_REGDEBUG static void stm32_checksetup(void) { } #endif /**************************************************************************** * Function: stm32_initbuffer * * Description: * Initialize the free buffer list. * * Input Parameters: * priv - Reference to the driver state structure * txbuffer - DMA memory allocated for TX buffers. * * Returned Value: * None * * Assumptions: * Called during early driver initialization before Ethernet interrupts * are enabled. * ****************************************************************************/ static void stm32_initbuffer(struct stm32_ethmac_s *priv, uint8_t *txbuffer) { uint8_t *buffer; int i; /* Initialize the head of the free buffer list */ sq_init(&priv->freeb); /* Add all of the pre-allocated buffers to the free buffer list */ for (i = 0, buffer = txbuffer; i < STM32_ETH_NFREEBUFFERS; i++, buffer += ALIGNED_BUFSIZE) { sq_addlast((sq_entry_t *)buffer, &priv->freeb); } } /**************************************************************************** * Function: stm32_allocbuffer * * Description: * Allocate one buffer from the free buffer list. * * Input Parameters: * priv - Reference to the driver state structure * * Returned Value: * Pointer to the allocated buffer on success; NULL on failure * * Assumptions: * May or may not be called from an interrupt handler. In either case, * global interrupts are disabled, either explicitly or indirectly through * interrupt handling logic. * ****************************************************************************/ static inline uint8_t *stm32_allocbuffer(struct stm32_ethmac_s *priv) { /* Allocate a buffer by returning the head of the free buffer list */ return (uint8_t *)sq_remfirst(&priv->freeb); } /**************************************************************************** * Function: stm32_freebuffer * * Description: * Return a buffer to the free buffer list. * * Input Parameters: * priv - Reference to the driver state structure * buffer - A pointer to the buffer to be freed * * Returned Value: * None * * Assumptions: * May or may not be called from an interrupt handler. In either case, * global interrupts are disabled, either explicitly or indirectly through * interrupt handling logic. * ****************************************************************************/ static inline void stm32_freebuffer(struct stm32_ethmac_s *priv, uint8_t *buffer) { /* Free the buffer by adding it to the end of the free buffer list */ sq_addlast((sq_entry_t *)buffer, &priv->freeb); } /**************************************************************************** * Function: stm32_isfreebuffer * * Description: * Return TRUE if the free buffer list is not empty. * * Input Parameters: * priv - Reference to the driver state structure * * Returned Value: * True if there are one or more buffers in the free buffer list; * false if the free buffer list is empty * * Assumptions: * None. * ****************************************************************************/ static inline bool stm32_isfreebuffer(struct stm32_ethmac_s *priv) { /* Return TRUE if the free buffer list is not empty */ return !sq_empty(&priv->freeb); } /**************************************************************************** * Function: stm32_transmit * * Description: * Start hardware transmission. Called either from the txdone interrupt * handling or from watchdog based polling. * * Input Parameters: * priv - Reference to the driver state structure * * Returned Value: * OK on success; a negated errno on failure * * Assumptions: * May or may not be called from an interrupt handler. In either case, * global interrupts are disabled, either explicitly or indirectly through * interrupt handling logic. * ****************************************************************************/ static int stm32_transmit(struct stm32_ethmac_s *priv) { struct eth_txdesc_s *txdesc; struct eth_txdesc_s *txfirst; /* The internal (optimal) network buffer size may be configured to be larger * than the Ethernet buffer size. */ #if OPTIMAL_ETH_BUFSIZE > ALIGNED_BUFSIZE uint8_t *buffer; int bufcount; int lastsize; int i; #endif /* Verify that the hardware is ready to send another packet. If we get * here, then we are committed to sending a packet; Higher level logic * must have assured that there is no transmission in progress. */ txdesc = priv->txhead; txfirst = txdesc; ninfo("d_len: %d d_buf: %p txhead: %p tdes0: %08x\n", priv->dev.d_len, priv->dev.d_buf, txdesc, txdesc->tdes0); DEBUGASSERT(txdesc && (txdesc->tdes0 & ETH_TDES0_OWN) == 0); /* Flush the contents of the TX buffer into physical memory */ up_clean_dcache((uintptr_t)priv->dev.d_buf, (uintptr_t)priv->dev.d_buf + priv->dev.d_len); /* Is the size to be sent greater than the size of the Ethernet buffer? */ DEBUGASSERT(priv->dev.d_len > 0 && priv->dev.d_buf != NULL); #if OPTIMAL_ETH_BUFSIZE > ALIGNED_BUFSIZE if (priv->dev.d_len > ALIGNED_BUFSIZE) { /* Yes... how many buffers will be need to send the packet? */ bufcount = (priv->dev.d_len + (ALIGNED_BUFSIZE - 1)) / ALIGNED_BUFSIZE; lastsize = priv->dev.d_len - (bufcount - 1) * ALIGNED_BUFSIZE; ninfo("bufcount: %d lastsize: %d\n", bufcount, lastsize); /* Set the first segment bit in the first TX descriptor */ txdesc->tdes0 |= ETH_TDES0_FS; /* Set up all but the last TX descriptor */ buffer = priv->dev.d_buf; for (i = 0; i < bufcount; i++) { /* This could be a normal event but the design does not handle it */ DEBUGASSERT((txdesc->tdes0 & ETH_TDES0_OWN) == 0); /* Set the Buffer1 address pointer */ txdesc->tdes2 = (uint32_t)buffer; /* Set the buffer size in all TX descriptors */ if (i == (bufcount - 1)) { /* This is the last segment. Set the last segment bit in the * last TX descriptor and ask for an interrupt when this * segment transfer completes. */ txdesc->tdes0 |= (ETH_TDES0_LS | ETH_TDES0_IC); /* This segment is, most likely, of fractional buffersize */ txdesc->tdes1 = lastsize; buffer += lastsize; } else { /* This is not the last segment. We don't want an interrupt * when this segment transfer completes. */ txdesc->tdes0 &= ~ETH_TDES0_IC; /* The size of the transfer is the whole buffer */ txdesc->tdes1 = ALIGNED_BUFSIZE; buffer += ALIGNED_BUFSIZE; } /* Give the descriptor to DMA */ txdesc->tdes0 |= ETH_TDES0_OWN; /* Flush the contents of the modified TX descriptor into physical * memory. */ up_clean_dcache((uintptr_t)txdesc, (uintptr_t)txdesc + sizeof(struct eth_txdesc_s)); /* Get the next descriptor in the link list */ txdesc = (struct eth_txdesc_s *)txdesc->tdes3; } } else #endif { /* The single descriptor is both the first and last segment. And we do * want an interrupt when the transfer completes. */ txdesc->tdes0 |= (ETH_TDES0_FS | ETH_TDES0_LS | ETH_TDES0_IC); /* Set frame size */ DEBUGASSERT(priv->dev.d_len <= CONFIG_NET_ETH_PKTSIZE); txdesc->tdes1 = priv->dev.d_len; /* Set the Buffer1 address pointer */ txdesc->tdes2 = (uint32_t)priv->dev.d_buf; /* Set OWN bit of the TX descriptor tdes0. This gives the buffer to * Ethernet DMA */ txdesc->tdes0 |= ETH_TDES0_OWN; /* Flush the contents of the modified TX descriptor into physical * memory. */ up_clean_dcache((uintptr_t)txdesc, (uintptr_t)txdesc + sizeof(struct eth_txdesc_s)); /* Point to the next available TX descriptor */ txdesc = (struct eth_txdesc_s *)txdesc->tdes3; } /* Remember where we left off in the TX descriptor chain */ priv->txhead = txdesc; /* Detach the buffer from priv->dev structure. That buffer is now * "in-flight". */ priv->dev.d_buf = NULL; priv->dev.d_len = 0; /* If there is no other TX buffer, in flight, then remember the location * of the TX descriptor. This is the location to check for TX done events. */ if (!priv->txtail) { DEBUGASSERT(priv->inflight == 0); priv->txtail = txfirst; } /* Increment the number of TX transfer in-flight */ priv->inflight++; ninfo("txhead: %p txtail: %p inflight: %d\n", priv->txhead, priv->txtail, priv->inflight); /* If all TX descriptors are in-flight, then we have to disable receive interrupts * too. This is because receive events can trigger more un-stoppable transmit * events. */ if (priv->inflight >= CONFIG_STM32F7_ETH_NTXDESC) { stm32_disableint(priv, ETH_DMAINT_RI); } /* Check if the TX Buffer unavailable flag is set */ MEMORY_SYNC(); if ((stm32_getreg(STM32_ETH_DMASR) & ETH_DMAINT_TBUI) != 0) { /* Clear TX Buffer unavailable flag */ stm32_putreg(ETH_DMAINT_TBUI, STM32_ETH_DMASR); /* Resume DMA transmission */ stm32_putreg(0, STM32_ETH_DMATPDR); } /* Enable TX interrupts */ stm32_enableint(priv, ETH_DMAINT_TI); /* Setup the TX timeout watchdog (perhaps restarting the timer) */ wd_start(priv->txtimeout, STM32_TXTIMEOUT, stm32_txtimeout_expiry, 1, (uint32_t)priv); return OK; } /**************************************************************************** * Function: stm32_txpoll * * Description: * The transmitter is available, check if the network has any outgoing packets ready * to send. This is a callback from devif_poll(). devif_poll() may be called: * * 1. When the preceding TX packet send is complete, * 2. When the preceding TX packet send timesout and the interface is reset * 3. During normal TX polling * * Input Parameters: * dev - Reference to the NuttX driver state structure * * Returned Value: * OK on success; a negated errno on failure * * Assumptions: * May or may not be called from an interrupt handler. In either case, * global interrupts are disabled, either explicitly or indirectly through * interrupt handling logic. * ****************************************************************************/ static int stm32_txpoll(struct net_driver_s *dev) { struct stm32_ethmac_s *priv = (struct stm32_ethmac_s *)dev->d_private; DEBUGASSERT(priv->dev.d_buf != NULL); /* If the polling resulted in data that should be sent out on the network, * the field d_len is set to a value > 0. */ if (priv->dev.d_len > 0) { /* Look up the destination MAC address and add it to the Ethernet * header. */ #ifdef CONFIG_NET_IPv4 #ifdef CONFIG_NET_IPv6 if (IFF_IS_IPv4(priv->dev.d_flags)) #endif { arp_out(&priv->dev); } #endif /* CONFIG_NET_IPv4 */ #ifdef CONFIG_NET_IPv6 #ifdef CONFIG_NET_IPv4 else #endif { neighbor_out(&priv->dev); } #endif /* CONFIG_NET_IPv6 */ if (!devif_loopback(&priv->dev)) { /* Send the packet */ stm32_transmit(priv); DEBUGASSERT(dev->d_len == 0 && dev->d_buf == NULL); /* Check if the next TX descriptor is owned by the Ethernet DMA or CPU. We * cannot perform the TX poll if we are unable to accept another packet for * transmission. * * In a race condition, ETH_TDES0_OWN may be cleared BUT still not available * because stm32_freeframe() has not yet run. If stm32_freeframe() has run, * the buffer1 pointer (tdes2) will be nullified (and inflight should be < * CONFIG_STM32F7_ETH_NTXDESC). */ if ((priv->txhead->tdes0 & ETH_TDES0_OWN) != 0 || priv->txhead->tdes2 != 0) { /* We have to terminate the poll if we have no more descriptors * available for another transfer. */ return -EBUSY; } /* We have the descriptor, we can continue the poll. Allocate a new * buffer for the poll. */ dev->d_buf = stm32_allocbuffer(priv); /* We can't continue the poll if we have no buffers */ if (dev->d_buf == NULL) { /* Terminate the poll. */ return -ENOMEM; } } } /* If zero is returned, the polling will continue until all connections have * been examined. */ return 0; } /**************************************************************************** * Function: stm32_dopoll * * Description: * The function is called in order to perform an out-of-sequence TX poll. * This is done: * * 1. After completion of a transmission (stm32_txdone), * 2. When new TX data is available (stm32_txavail_process), and * 3. After a TX timeout to restart the sending process * (stm32_txtimeout_process). * * Input Parameters: * priv - Reference to the driver state structure * * Returned Value: * None * * Assumptions: * Global interrupts are disabled by interrupt handling logic. * ****************************************************************************/ static void stm32_dopoll(struct stm32_ethmac_s *priv) { struct net_driver_s *dev = &priv->dev; /* Check if the next TX descriptor is owned by the Ethernet DMA or * CPU. We cannot perform the TX poll if we are unable to accept * another packet for transmission. * * In a race condition, ETH_TDES0_OWN may be cleared BUT still not available * because stm32_freeframe() has not yet run. If stm32_freeframe() has run, * the buffer1 pointer (tdes2) will be nullified (and inflight should be < * CONFIG_STM32F7_ETH_NTXDESC). */ if ((priv->txhead->tdes0 & ETH_TDES0_OWN) == 0 && priv->txhead->tdes2 == 0) { /* If we have the descriptor, then poll the network for new XMIT data. * Allocate a buffer for the poll. */ DEBUGASSERT(dev->d_len == 0 && dev->d_buf == NULL); dev->d_buf = stm32_allocbuffer(priv); /* We can't poll if we have no buffers */ if (dev->d_buf) { devif_poll(dev, stm32_txpoll); /* We will, most likely end up with a buffer to be freed. But it * might not be the same one that we allocated above. */ if (dev->d_buf) { DEBUGASSERT(dev->d_len == 0); stm32_freebuffer(priv, dev->d_buf); dev->d_buf = NULL; } } } } /**************************************************************************** * Function: stm32_enableint * * Description: * Enable a "normal" interrupt * * Input Parameters: * priv - Reference to the driver state structure * * Returned Value: * None * * Assumptions: * Global interrupts are disabled by interrupt handling logic. * ****************************************************************************/ static void stm32_enableint(struct stm32_ethmac_s *priv, uint32_t ierbit) { uint32_t regval; /* Enable the specified "normal" interrupt */ regval = stm32_getreg(STM32_ETH_DMAIER); regval |= (ETH_DMAINT_NIS | ierbit); stm32_putreg(regval, STM32_ETH_DMAIER); } /**************************************************************************** * Function: stm32_disableint * * Description: * Disable a normal interrupt. * * Input Parameters: * priv - Reference to the driver state structure * * Returned Value: * None * * Assumptions: * Global interrupts are disabled by interrupt handling logic. * ****************************************************************************/ static void stm32_disableint(struct stm32_ethmac_s *priv, uint32_t ierbit) { uint32_t regval; /* Disable the "normal" interrupt */ regval = stm32_getreg(STM32_ETH_DMAIER); regval &= ~ierbit; /* Are all "normal" interrupts now disabled? */ if ((regval & ETH_DMAINT_NORMAL) == 0) { /* Yes.. disable normal interrupts */ regval &= ~ETH_DMAINT_NIS; } stm32_putreg(regval, STM32_ETH_DMAIER); } /**************************************************************************** * Function: stm32_freesegment * * Description: * The function is called when a frame is received using the DMA receive * interrupt. It scans the RX descriptors to the received frame. * * Input Parameters: * priv - Reference to the driver state structure * * Returned Value: * None * * Assumptions: * Global interrupts are disabled by interrupt handling logic. * ****************************************************************************/ static void stm32_freesegment(struct stm32_ethmac_s *priv, struct eth_rxdesc_s *rxfirst, int segments) { struct eth_rxdesc_s *rxdesc; int i; ninfo("rxfirst: %p segments: %d\n", rxfirst, segments); /* Give the freed RX buffers back to the Ethernet MAC to be refilled */ rxdesc = rxfirst; for (i = 0; i < segments; i++) { /* Set OWN bit in RX descriptors. This gives the buffers back to DMA */ rxdesc->rdes0 = ETH_RDES0_OWN; /* Make sure that the modified RX descriptor is written to physical * memory. */ up_clean_dcache((uintptr_t)rxdesc, (uintptr_t)rxdesc + sizeof(struct eth_rxdesc_s)); /* Get the next RX descriptor in the chain (cache coherency should not * be an issue because the link address is constant. */ rxdesc = (struct eth_rxdesc_s *)rxdesc->rdes3; } /* Reset the segment management logic */ priv->rxcurr = NULL; priv->segments = 0; /* Check if the RX Buffer unavailable flag is set */ if ((stm32_getreg(STM32_ETH_DMASR) & ETH_DMAINT_RBUI) != 0) { /* Clear RBUS Ethernet DMA flag */ stm32_putreg(ETH_DMAINT_RBUI, STM32_ETH_DMASR); /* Resume DMA reception */ stm32_putreg(0, STM32_ETH_DMARPDR); } } /**************************************************************************** * Function: stm32_recvframe * * Description: * The function is called when a frame is received using the DMA receive * interrupt. It scans the RX descriptors of the received frame. * * NOTE: This function will silently discard any packets containing errors. * * Input Parameters: * priv - Reference to the driver state structure * * Returned Value: * OK if a packet was successfully returned; -EAGAIN if there are no * further packets available * * Assumptions: * Global interrupts are disabled by interrupt handling logic. * ****************************************************************************/ static int stm32_recvframe(struct stm32_ethmac_s *priv) { struct eth_rxdesc_s *rxdesc; struct eth_rxdesc_s *rxcurr; uint8_t *buffer; int i; ninfo("rxhead: %p rxcurr: %p segments: %d\n", priv->rxhead, priv->rxcurr, priv->segments); /* Check if there are free buffers. We cannot receive new frames in this * design unless there is at least one free buffer. */ if (!stm32_isfreebuffer(priv)) { nerr("ERROR: No free buffers\n"); return -ENOMEM; } /* Scan descriptors owned by the CPU. Scan until: * * 1) We find a descriptor still owned by the DMA, * 2) We have examined all of the RX descriptors, or * 3) All of the TX descriptors are in flight. * * This last case is obscure. It is due to that fact that each packet * that we receive can generate an unstoppable transmisson. So we have * to stop receiving when we can not longer transmit. In this case, the * transmit logic should also have disabled further RX interrupts. */ rxdesc = priv->rxhead; /* Forces the first RX descriptor to be re-read from physical memory */ up_invalidate_dcache((uintptr_t)rxdesc, (uintptr_t)rxdesc + sizeof(struct eth_rxdesc_s)); for (i = 0; (rxdesc->rdes0 & ETH_RDES0_OWN) == 0 && i < CONFIG_STM32F7_ETH_NRXDESC && priv->inflight < CONFIG_STM32F7_ETH_NTXDESC; i++) { /* Check if this is the first segment in the frame */ if ((rxdesc->rdes0 & ETH_RDES0_FS) != 0 && (rxdesc->rdes0 & ETH_RDES0_LS) == 0) { priv->rxcurr = rxdesc; priv->segments = 1; } /* Check if this is an intermediate segment in the frame */ else if (((rxdesc->rdes0 & ETH_RDES0_LS) == 0) && ((rxdesc->rdes0 & ETH_RDES0_FS) == 0)) { priv->segments++; } /* Otherwise, it is the last segment in the frame */ else { priv->segments++; /* Check if there is only one segment in the frame */ if (priv->segments == 1) { rxcurr = rxdesc; } else { rxcurr = priv->rxcurr; } ninfo("rxhead: %p rxcurr: %p segments: %d\n", priv->rxhead, priv->rxcurr, priv->segments); /* Check if any errors are reported in the frame */ if ((rxdesc->rdes0 & ETH_RDES0_ES) == 0) { struct net_driver_s *dev = &priv->dev; /* Get the Frame Length of the received packet: subtract 4 * bytes of the CRC */ dev->d_len = ((rxdesc->rdes0 & ETH_RDES0_FL_MASK) >> ETH_RDES0_FL_SHIFT) - 4; /* Get a buffer from the free list. We don't even check if * this is successful because we already assure the free * list is not empty above. */ buffer = stm32_allocbuffer(priv); /* Take the buffer from the RX descriptor of the first free * segment, put it into the network device structure, then replace * the buffer in the RX descriptor with the newly allocated * buffer. */ DEBUGASSERT(dev->d_buf == NULL); dev->d_buf = (uint8_t *)rxcurr->rdes2; rxcurr->rdes2 = (uint32_t)buffer; /* Make sure that the modified RX descriptor is written to * physical memory. */ up_clean_dcache((uintptr_t)rxcurr, (uintptr_t)rxdesc + sizeof(struct eth_rxdesc_s)); /* Remember where we should re-start scanning and reset the segment * scanning logic */ priv->rxhead = (struct eth_rxdesc_s *)rxdesc->rdes3; stm32_freesegment(priv, rxcurr, priv->segments); /* Force the completed RX DMA buffer to be re-read from * physical memory. */ up_invalidate_dcache((uintptr_t)dev->d_buf, (uintptr_t)dev->d_buf + dev->d_len); ninfo("rxhead: %p d_buf: %p d_len: %d\n", priv->rxhead, dev->d_buf, dev->d_len); /* Return success */ return OK; } else { /* Drop the frame that contains the errors, reset the segment * scanning logic, and continue scanning with the next frame. */ nwarn("WARNING: DROPPED RX descriptor errors: %08x\n", rxdesc->rdes0); stm32_freesegment(priv, rxcurr, priv->segments); } } /* Try the next descriptor */ rxdesc = (struct eth_rxdesc_s *)rxdesc->rdes3; /* Force the next RX descriptor to be re-read from physical memory */ up_invalidate_dcache((uintptr_t)rxdesc, (uintptr_t)rxdesc + sizeof(struct eth_rxdesc_s)); } /* We get here after all of the descriptors have been scanned or when rxdesc points * to the first descriptor owned by the DMA. Remember where we left off. */ priv->rxhead = rxdesc; ninfo("rxhead: %p rxcurr: %p segments: %d\n", priv->rxhead, priv->rxcurr, priv->segments); return -EAGAIN; } /**************************************************************************** * Function: stm32_receive * * Description: * An interrupt was received indicating the availability of a new RX packet * * Input Parameters: * priv - Reference to the driver state structure * * Returned Value: * None * * Assumptions: * Global interrupts are disabled by interrupt handling logic. * ****************************************************************************/ static void stm32_receive(struct stm32_ethmac_s *priv) { struct net_driver_s *dev = &priv->dev; /* Loop while while stm32_recvframe() successfully retrieves valid * Ethernet frames. */ while (stm32_recvframe(priv) == OK) { #ifdef CONFIG_NET_PKT /* When packet sockets are enabled, feed the frame into the packet tap */ pkt_input(&priv->dev); #endif /* Check if the packet is a valid size for the network buffer configuration * (this should not happen) */ if (dev->d_len > CONFIG_NET_ETH_PKTSIZE) { nwarn("WARNING: DROPPED Too big: %d\n", dev->d_len); /* Free dropped packet buffer */ if (dev->d_buf) { stm32_freebuffer(priv, dev->d_buf); dev->d_buf = NULL; dev->d_len = 0; } continue; } /* We only accept IP packets of the configured type and ARP packets */ #ifdef CONFIG_NET_IPv4 if (BUF->type == HTONS(ETHTYPE_IP)) { ninfo("IPv4 frame\n"); /* Handle ARP on input then give the IPv4 packet to the network * layer */ arp_ipin(&priv->dev); ipv4_input(&priv->dev); /* If the above function invocation resulted in data that should be * sent out on the network, the field d_len will set to a value > 0. */ if (priv->dev.d_len > 0) { /* Update the Ethernet header with the correct MAC address */ #ifdef CONFIG_NET_IPv6 if (IFF_IS_IPv4(priv->dev.d_flags)) #endif { arp_out(&priv->dev); } #ifdef CONFIG_NET_IPv6 else { neighbor_out(&priv->dev); } #endif /* And send the packet */ stm32_transmit(priv); } } else #endif #ifdef CONFIG_NET_IPv6 if (BUF->type == HTONS(ETHTYPE_IP6)) { ninfo("IPv6 frame\n"); /* Give the IPv6 packet to the network layer */ ipv6_input(&priv->dev); /* If the above function invocation resulted in data that should be * sent out on the network, the field d_len will set to a value > 0. */ if (priv->dev.d_len > 0) { /* Update the Ethernet header with the correct MAC address */ #ifdef CONFIG_NET_IPv4 if (IFF_IS_IPv4(priv->dev.d_flags)) { arp_out(&priv->dev); } else #endif #ifdef CONFIG_NET_IPv6 { neighbor_out(&priv->dev); } #endif /* And send the packet */ stm32_transmit(priv); } } else #endif #ifdef CONFIG_NET_ARP if (BUF->type == htons(ETHTYPE_ARP)) { ninfo("ARP frame\n"); /* Handle ARP packet */ arp_arpin(&priv->dev); /* If the above function invocation resulted in data that should be * sent out on the network, the field d_len will set to a value > 0. */ if (priv->dev.d_len > 0) { stm32_transmit(priv); } } else #endif { nwarn("WARNING: DROPPED Unknown type: %04x\n", BUF->type); } /* We are finished with the RX buffer. NOTE: If the buffer is * re-used for transmission, the dev->d_buf field will have been * nullified. */ if (dev->d_buf) { /* Free the receive packet buffer */ stm32_freebuffer(priv, dev->d_buf); dev->d_buf = NULL; dev->d_len = 0; } } } /**************************************************************************** * Function: stm32_freeframe * * Description: * Scans the TX descriptors and frees the buffers of completed TX transfers. * * Input Parameters: * priv - Reference to the driver state structure * * Returned Value: * None. * * Assumptions: * Global interrupts are disabled by interrupt handling logic. * ****************************************************************************/ static void stm32_freeframe(struct stm32_ethmac_s *priv) { struct eth_txdesc_s *txdesc; int i; ninfo("txhead: %p txtail: %p inflight: %d\n", priv->txhead, priv->txtail, priv->inflight); /* Scan for "in-flight" descriptors owned by the CPU */ txdesc = priv->txtail; if (txdesc) { DEBUGASSERT(priv->inflight > 0); /* Force re-reading of the TX descriptor for physical memory */ up_invalidate_dcache((uintptr_t)txdesc, (uintptr_t)txdesc + sizeof(struct eth_txdesc_s)); for (i = 0; (txdesc->tdes0 & ETH_TDES0_OWN) == 0; i++) { /* There should be a buffer assigned to all in-flight * TX descriptors. */ ninfo("txtail: %p tdes0: %08x tdes2: %08x tdes3: %08x\n", txdesc, txdesc->tdes0, txdesc->tdes2, txdesc->tdes3); DEBUGASSERT(txdesc->tdes2 != 0); /* Check if this is the first segment of a TX frame. */ if ((txdesc->tdes0 & ETH_TDES0_FS) != 0) { /* Yes.. Free the buffer */ stm32_freebuffer(priv, (uint8_t *)txdesc->tdes2); } /* In any event, make sure that TDES2 is nullified. */ txdesc->tdes2 = 0; /* Flush the contents of the modified TX descriptor into * physical memory. */ up_clean_dcache((uintptr_t)txdesc, (uintptr_t)txdesc + sizeof(struct eth_txdesc_s)); /* Check if this is the last segment of a TX frame */ if ((txdesc->tdes0 & ETH_TDES0_LS) != 0) { /* Yes.. Decrement the number of frames "in-flight". */ priv->inflight--; /* If all of the TX descriptors were in-flight, then RX interrupts * may have been disabled... we can re-enable them now. */ stm32_enableint(priv, ETH_DMAINT_RI); /* If there are no more frames in-flight, then bail. */ if (priv->inflight <= 0) { priv->txtail = NULL; priv->inflight = 0; return; } } /* Try the next descriptor in the TX chain */ txdesc = (struct eth_txdesc_s *)txdesc->tdes3; /* Force re-reading of the TX descriptor for physical memory */ up_invalidate_dcache((uintptr_t)txdesc, (uintptr_t)txdesc + sizeof(struct eth_txdesc_s)); } /* We get here if (1) there are still frames "in-flight". Remember * where we left off. */ priv->txtail = txdesc; ninfo("txhead: %p txtail: %p inflight: %d\n", priv->txhead, priv->txtail, priv->inflight); } } /**************************************************************************** * Function: stm32_txdone * * Description: * An interrupt was received indicating that the last TX packet(s) is done * * Input Parameters: * priv - Reference to the driver state structure * * Returned Value: * None * * Assumptions: * Global interrupts are disabled by the watchdog logic. * ****************************************************************************/ static void stm32_txdone(struct stm32_ethmac_s *priv) { DEBUGASSERT(priv->txtail != NULL); /* Scan the TX descriptor change, returning buffers to free list */ stm32_freeframe(priv); /* If no further xmits are pending, then cancel the TX timeout */ if (priv->inflight <= 0) { /* Cancel the TX timeout */ wd_cancel(priv->txtimeout); /* And disable further TX interrupts. */ stm32_disableint(priv, ETH_DMAINT_TI); } /* Then poll the network for new XMIT data */ stm32_dopoll(priv); } /**************************************************************************** * Function: stm32_interrupt_work * * Description: * Perform interrupt related work from the worker thread * * Input Parameters: * arg - The argument passed when work_queue() was called. * * Returned Value: * OK on success * * Assumptions: * Ethernet interrupts are disabled * ****************************************************************************/ static void stm32_interrupt_work(void *arg) { struct stm32_ethmac_s *priv = (struct stm32_ethmac_s *)arg; uint32_t dmasr; DEBUGASSERT(priv); /* Process pending Ethernet interrupts */ net_lock(); /* Get the DMA interrupt status bits (no MAC interrupts are expected) */ dmasr = stm32_getreg(STM32_ETH_DMASR); /* Mask only enabled interrupts. This depends on the fact that the interrupt * related bits (0-16) correspond in these two registers. */ dmasr &= stm32_getreg(STM32_ETH_DMAIER); /* Check if there are pending "normal" interrupts */ if ((dmasr & ETH_DMAINT_NIS) != 0) { /* Yes.. Check if we received an incoming packet, if so, call * stm32_receive() */ if ((dmasr & ETH_DMAINT_RI) != 0) { /* Clear the pending receive interrupt */ stm32_putreg(ETH_DMAINT_RI, STM32_ETH_DMASR); /* Handle the received package */ stm32_receive(priv); } /* Check if a packet transmission just completed. If so, call * stm32_txdone(). This may disable further TX interrupts if there * are no pending transmissions. */ if ((dmasr & ETH_DMAINT_TI) != 0) { /* Clear the pending receive interrupt */ stm32_putreg(ETH_DMAINT_TI, STM32_ETH_DMASR); /* Check if there are pending transmissions */ stm32_txdone(priv); } /* Clear the pending normal summary interrupt */ stm32_putreg(ETH_DMAINT_NIS, STM32_ETH_DMASR); } /* Handle error interrupt only if CONFIG_DEBUG_NET is eanbled */ #ifdef CONFIG_DEBUG_NET /* Check if there are pending "abnormal" interrupts */ if ((dmasr & ETH_DMAINT_AIS) != 0) { /* Just let the user know what happened */ nerr("ERROR: Abormal event(s): %08x\n", dmasr); /* Clear all pending abnormal events */ stm32_putreg(ETH_DMAINT_ABNORMAL, STM32_ETH_DMASR); /* Clear the pending abnormal summary interrupt */ stm32_putreg(ETH_DMAINT_AIS, STM32_ETH_DMASR); } #endif net_unlock(); /* Re-enable Ethernet interrupts at the NVIC */ up_enable_irq(STM32_IRQ_ETH); } /**************************************************************************** * Function: stm32_interrupt * * Description: * Hardware interrupt handler * * Input Parameters: * irq - Number of the IRQ that generated the interrupt * context - Interrupt register state save info (architecture-specific) * * Returned Value: * OK on success * * Assumptions: * ****************************************************************************/ static int stm32_interrupt(int irq, void *context, FAR void *arg) { struct stm32_ethmac_s *priv = &g_stm32ethmac[0]; uint32_t dmasr; /* Get the DMA interrupt status bits (no MAC interrupts are expected) */ dmasr = stm32_getreg(STM32_ETH_DMASR); if (dmasr != 0) { /* Disable further Ethernet interrupts. Because Ethernet interrupts * are also disabled if the TX timeout event occurs, there can be no * race condition here. */ up_disable_irq(STM32_IRQ_ETH); /* Check if a packet transmission just completed. */ if ((dmasr & ETH_DMAINT_TI) != 0) { /* If a TX transfer just completed, then cancel the TX timeout so * there will be no race condition between any subsequent timeout * expiration and the deferred interrupt processing. */ wd_cancel(priv->txtimeout); } DEBUGASSERT(work_available(&priv->irqwork)); /* Schedule to perform the interrupt processing on the worker thread. */ work_queue(ETHWORK, &priv->irqwork, stm32_interrupt_work, priv, 0); } return OK; } /**************************************************************************** * Function: stm32_txtimeout_work * * Description: * Perform TX timeout related work from the worker thread * * Input Parameters: * arg - The argument passed when work_queue() as called. * * Returned Value: * OK on success * * Assumptions: * Ethernet interrupts are disabled * ****************************************************************************/ static void stm32_txtimeout_work(void *arg) { struct stm32_ethmac_s *priv = (struct stm32_ethmac_s *)arg; /* Reset the hardware. Just take the interface down, then back up again. */ net_lock(); stm32_ifdown(&priv->dev); stm32_ifup(&priv->dev); /* Then poll for new XMIT data */ stm32_dopoll(priv); net_unlock(); } /**************************************************************************** * Function: stm32_txtimeout_expiry * * Description: * Our TX watchdog timed out. Called from the timer interrupt handler. * The last TX never completed. Reset the hardware and start again. * * Input Parameters: * argc - The number of available arguments * arg - The first argument * * Returned Value: * None * * Assumptions: * Global interrupts are disabled by the watchdog logic. * ****************************************************************************/ static void stm32_txtimeout_expiry(int argc, uint32_t arg, ...) { struct stm32_ethmac_s *priv = (struct stm32_ethmac_s *)arg; nerr("ERROR: Timeout!\n"); /* Disable further Ethernet interrupts. This will prevent some race * conditions with interrupt work. There is still a potential race * condition with interrupt work that is already queued and in progress. * * Interrupts will be re-enabled when stm32_ifup() is called. */ up_disable_irq(STM32_IRQ_ETH); /* Schedule to perform the TX timeout processing on the worker thread. */ DEBUGASSERT(work_available(&priv->irqwork)); work_queue(ETHWORK, &priv->irqwork, stm32_txtimeout_work, priv, 0); } /**************************************************************************** * Function: stm32_poll_work * * Description: * Perform periodic polling from the worker thread * * Input Parameters: * arg - The argument passed when work_queue() as called. * * Returned Value: * OK on success * * Assumptions: * Ethernet interrupts are disabled * ****************************************************************************/ static void stm32_poll_work(void *arg) { struct stm32_ethmac_s *priv = (struct stm32_ethmac_s *)arg; struct net_driver_s *dev = &priv->dev; /* Check if the next TX descriptor is owned by the Ethernet DMA or CPU. We * cannot perform the timer poll if we are unable to accept another packet * for transmission. Hmmm.. might be bug here. Does this mean if there is * a transmit in progress, we will miss TCP time state updates? * * In a race condition, ETH_TDES0_OWN may be cleared BUT still not available * because stm32_freeframe() has not yet run. If stm32_freeframe() has run, * the buffer1 pointer (tdes2) will be nullified (and inflight should be < * CONFIG_STM32F7_ETH_NTXDESC). */ net_lock(); if ((priv->txhead->tdes0 & ETH_TDES0_OWN) == 0 && priv->txhead->tdes2 == 0) { /* If we have the descriptor, then perform the timer poll. Allocate a * buffer for the poll. */ DEBUGASSERT(dev->d_len == 0 && dev->d_buf == NULL); dev->d_buf = stm32_allocbuffer(priv); /* We can't poll if we have no buffers */ if (dev->d_buf) { /* Update TCP timing states and poll the network for new XMIT data. */ devif_timer(dev, STM32_WDDELAY, stm32_txpoll); /* We will, most likely end up with a buffer to be freed. But it * might not be the same one that we allocated above. */ if (dev->d_buf) { DEBUGASSERT(dev->d_len == 0); stm32_freebuffer(priv, dev->d_buf); dev->d_buf = NULL; } } } /* Setup the watchdog poll timer again */ wd_start(priv->txpoll, STM32_WDDELAY, stm32_poll_expiry, 1, priv); net_unlock(); } /**************************************************************************** * Function: stm32_poll_expiry * * Description: * Periodic timer handler. Called from the timer interrupt handler. * * Input Parameters: * argc - The number of available arguments * arg - The first argument * * Returned Value: * None * * Assumptions: * Global interrupts are disabled by the watchdog logic. * ****************************************************************************/ static void stm32_poll_expiry(int argc, uint32_t arg, ...) { struct stm32_ethmac_s *priv = (struct stm32_ethmac_s *)arg; /* Schedule to perform the interrupt processing on the worker thread. */ if (work_available(&priv->pollwork)) { work_queue(ETHWORK, &priv->pollwork, stm32_poll_work, priv, 0); } else { wd_start(priv->txpoll, STM32_WDDELAY, stm32_poll_expiry, 1, priv); } } /**************************************************************************** * Function: stm32_ifup * * Description: * NuttX Callback: Bring up the Ethernet interface when an IP address is * provided * * Input Parameters: * dev - Reference to the NuttX driver state structure * * Returned Value: * None * * Assumptions: * ****************************************************************************/ static int stm32_ifup(struct net_driver_s *dev) { struct stm32_ethmac_s *priv = (struct stm32_ethmac_s *)dev->d_private; int ret; #ifdef CONFIG_NET_IPv4 ninfo("Bringing up: %d.%d.%d.%d\n", dev->d_ipaddr & 0xff, (dev->d_ipaddr >> 8) & 0xff, (dev->d_ipaddr >> 16) & 0xff, dev->d_ipaddr >> 24); #endif #ifdef CONFIG_NET_IPv6 ninfo("Bringing up: %04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x\n", dev->d_ipv6addr[0], dev->d_ipv6addr[1], dev->d_ipv6addr[2], dev->d_ipv6addr[3], dev->d_ipv6addr[4], dev->d_ipv6addr[5], dev->d_ipv6addr[6], dev->d_ipv6addr[7]); #endif /* Configure the Ethernet interface for DMA operation. */ ret = stm32_ethconfig(priv); if (ret < 0) { return ret; } /* Set and activate a timer process */ wd_start(priv->txpoll, STM32_WDDELAY, stm32_poll_expiry, 1, (uint32_t)priv); /* Enable the Ethernet interrupt */ priv->ifup = true; up_enable_irq(STM32_IRQ_ETH); stm32_checksetup(); return OK; } /**************************************************************************** * Function: stm32_ifdown * * Description: * NuttX Callback: Stop the interface. * * Input Parameters: * dev - Reference to the NuttX driver state structure * * Returned Value: * None * * Assumptions: * ****************************************************************************/ static int stm32_ifdown(struct net_driver_s *dev) { struct stm32_ethmac_s *priv = (struct stm32_ethmac_s *)dev->d_private; irqstate_t flags; ninfo("Taking the network down\n"); /* Disable the Ethernet interrupt */ flags = enter_critical_section(); up_disable_irq(STM32_IRQ_ETH); /* Cancel the TX poll timer and TX timeout timers */ wd_cancel(priv->txpoll); wd_cancel(priv->txtimeout); /* Put the EMAC in its reset, non-operational state. This should be * a known configuration that will guarantee the stm32_ifup() always * successfully brings the interface back up. */ stm32_ethreset(priv); /* Mark the device "down" */ priv->ifup = false; leave_critical_section(flags); return OK; } /**************************************************************************** * Function: stm32_txavail_work * * Description: * Perform an out-of-cycle poll on the worker thread. * * Input Parameters: * arg - Reference to the NuttX driver state structure (cast to void*) * * Returned Value: * None * * Assumptions: * Called on the higher priority worker thread. * ****************************************************************************/ static void stm32_txavail_work(void *arg) { struct stm32_ethmac_s *priv = (struct stm32_ethmac_s *)arg; ninfo("ifup: %d\n", priv->ifup); /* Ignore the notification if the interface is not yet up */ net_lock(); if (priv->ifup) { /* Poll the network for new XMIT data */ stm32_dopoll(priv); } net_unlock(); } /**************************************************************************** * Function: stm32_txavail * * Description: * Driver callback invoked when new TX data is available. This is a * stimulus perform an out-of-cycle poll and, thereby, reduce the TX * latency. * * Input Parameters: * dev - Reference to the NuttX driver state structure * * Returned Value: * None * * Assumptions: * Called in normal user mode * ****************************************************************************/ static int stm32_txavail(struct net_driver_s *dev) { struct stm32_ethmac_s *priv = (struct stm32_ethmac_s *)dev->d_private; /* Is our single work structure available? It may not be if there are * pending interrupt actions and we will have to ignore the Tx * availability action. */ if (work_available(&priv->pollwork)) { /* Schedule to serialize the poll on the worker thread. */ work_queue(ETHWORK, &priv->pollwork, stm32_txavail_work, priv, 0); } return OK; } /**************************************************************************** * Function: stm32_calcethcrc * * Description: * Function to calculate the CRC used by STM32 to check an ethernet frame * * Input Parameters: * data - the data to be checked * length - length of the data * * Returned Value: * None * * Assumptions: * ****************************************************************************/ #if defined(CONFIG_NET_MCASTGROUP) || defined(CONFIG_NET_ICMPv6) static uint32_t stm32_calcethcrc(const uint8_t *data, size_t length) { uint32_t crc = 0xffffffff; size_t i; int j; for (i = 0; i < length; i++) { for (j = 0; j < 8; j++) { if (((crc >> 31) ^ (data[i] >> j)) & 0x01) { /* x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1 */ crc = (crc << 1) ^ 0x04c11db7; } else { crc = crc << 1; } } } return ~crc; } #endif /**************************************************************************** * Function: stm32_addmac * * Description: * NuttX Callback: Add the specified MAC address to the hardware multicast * address filtering * * Input Parameters: * dev - Reference to the NuttX driver state structure * mac - The MAC address to be added * * Returned Value: * None * * Assumptions: * ****************************************************************************/ #if defined(CONFIG_NET_MCASTGROUP) || defined(CONFIG_NET_ICMPv6) static int stm32_addmac(struct net_driver_s *dev, const uint8_t *mac) { uint32_t crc; uint32_t hashindex; uint32_t temp; uint32_t registeraddress; ninfo("MAC: %02x:%02x:%02x:%02x:%02x:%02x\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); /* Add the MAC address to the hardware multicast hash table */ crc = stm32_calcethcrc(mac, 6); hashindex = (crc >> 26) & 0x3f; if (hashindex > 31) { registeraddress = STM32_ETH_MACHTHR; hashindex -= 32; } else { registeraddress = STM32_ETH_MACHTLR; } temp = stm32_getreg(registeraddress); temp |= 1 << hashindex; stm32_putreg(temp, registeraddress); temp = stm32_getreg(STM32_ETH_MACFFR); temp |= (ETH_MACFFR_HM | ETH_MACFFR_HPF); stm32_putreg(temp, STM32_ETH_MACFFR); return OK; } #endif /* CONFIG_NET_MCASTGROUP || CONFIG_NET_ICMPv6 */ /**************************************************************************** * Function: stm32_rmmac * * Description: * NuttX Callback: Remove the specified MAC address from the hardware multicast * address filtering * * Input Parameters: * dev - Reference to the NuttX driver state structure * mac - The MAC address to be removed * * Returned Value: * None * * Assumptions: * ****************************************************************************/ #ifdef CONFIG_NET_MCASTGROUP static int stm32_rmmac(struct net_driver_s *dev, const uint8_t *mac) { uint32_t crc; uint32_t hashindex; uint32_t temp; uint32_t registeraddress; ninfo("MAC: %02x:%02x:%02x:%02x:%02x:%02x\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); /* Remove the MAC address to the hardware multicast hash table */ crc = stm32_calcethcrc(mac, 6); hashindex = (crc >> 26) & 0x3f; if (hashindex > 31) { registeraddress = STM32_ETH_MACHTHR; hashindex -= 32; } else { registeraddress = STM32_ETH_MACHTLR; } temp = stm32_getreg(registeraddress); temp &= ~(1 << hashindex); stm32_putreg(temp, registeraddress); /* If there is no address registered any more, delete multicast filtering */ if (stm32_getreg(STM32_ETH_MACHTHR) == 0 && stm32_getreg(STM32_ETH_MACHTLR) == 0) { temp = stm32_getreg(STM32_ETH_MACFFR); temp &= ~(ETH_MACFFR_HM | ETH_MACFFR_HPF); stm32_putreg(temp, STM32_ETH_MACFFR); } return OK; } #endif /**************************************************************************** * Function: stm32_txdescinit * * Description: * Initializes the DMA TX descriptors in chain mode. * * Input Parameters: * priv - Reference to the driver state structure * txtable - List of pre-allocated TX descriptors for the Ethernet * interface * * Returned Value: * None * * Assumptions: * ****************************************************************************/ static void stm32_txdescinit(struct stm32_ethmac_s *priv, union stm32_txdesc_u *txtable) { struct eth_txdesc_s *txdesc; int i; /* priv->txhead will point to the first, available TX descriptor in the chain. * Set the priv->txhead pointer to the first descriptor in the table. */ priv->txhead = &txtable[0].txdesc; /* priv->txtail will point to the first segment of the oldest pending * "in-flight" TX transfer. NULL means that there are no active TX * transfers. */ priv->txtail = NULL; priv->inflight = 0; /* Initialize each TX descriptor */ for (i = 0; i < CONFIG_STM32F7_ETH_NTXDESC; i++) { txdesc = &txtable[i].txdesc; /* Set Second Address Chained bit */ txdesc->tdes0 = ETH_TDES0_TCH; #ifdef CHECKSUM_BY_HARDWARE /* Enable the checksum insertion for the TX frames */ txdesc->tdes0 |= ETH_TDES0_CIC_ALL; #endif /* Clear Buffer1 address pointer (buffers will be assigned as they * are used) */ txdesc->tdes2 = 0; /* Initialize the next descriptor with the Next Descriptor Polling Enable */ if (i < (CONFIG_STM32F7_ETH_NTXDESC - 1)) { /* Set next descriptor address register with next descriptor base * address */ txdesc->tdes3 = (uint32_t)&txtable[i + 1].txdesc; } else { /* For last descriptor, set next descriptor address register equal * to the first descriptor base address */ txdesc->tdes3 = (uint32_t)&txtable[0].txdesc; } } /* Flush all of the initialized TX descriptors to physical memory */ up_clean_dcache((uintptr_t)txtable, (uintptr_t)txtable + TXTABLE_SIZE * sizeof(union stm32_txdesc_u)); /* Set Transmit Descriptor List Address Register */ stm32_putreg((uint32_t)&txtable[0].txdesc, STM32_ETH_DMATDLAR); } /**************************************************************************** * Function: stm32_rxdescinit * * Description: * Initializes the DMA RX descriptors in chain mode. * * Input Parameters: * priv - Reference to the driver state structure * rxtable - List of pre-allocated RX descriptors for the Ethernet * interface * txbuffer - List of pre-allocated DMA buffers for the Ethernet interface * * Returned Value: * None * * Assumptions: * ****************************************************************************/ static void stm32_rxdescinit(struct stm32_ethmac_s *priv, union stm32_rxdesc_u *rxtable, uint8_t *rxbuffer) { struct eth_rxdesc_s *rxdesc; int i; /* priv->rxhead will point to the first, RX descriptor in the chain. * This will be where we receive the first incomplete frame. */ priv->rxhead = &rxtable[0].rxdesc; /* If we accumulate the frame in segments, priv->rxcurr points to the * RX descriptor of the first segment in the current TX frame. */ priv->rxcurr = NULL; priv->segments = 0; /* Initialize each RX descriptor */ for (i = 0; i < CONFIG_STM32F7_ETH_NRXDESC; i++) { rxdesc = &rxtable[i].rxdesc; /* Set Own bit of the RX descriptor rdes0 */ rxdesc->rdes0 = ETH_RDES0_OWN; /* Set Buffer1 size and Second Address Chained bit and enabled DMA * RX desc receive interrupt */ rxdesc->rdes1 = ETH_RDES1_RCH | (uint32_t)ALIGNED_BUFSIZE; /* Set Buffer1 address pointer */ rxdesc->rdes2 = (uint32_t)&rxbuffer[i * ALIGNED_BUFSIZE]; /* Initialize the next descriptor with the Next Descriptor Polling Enable */ if (i < (CONFIG_STM32F7_ETH_NRXDESC - 1)) { /* Set next descriptor address register with next descriptor base * address */ rxdesc->rdes3 = (uint32_t)&rxtable[i + 1].rxdesc; } else { /* For last descriptor, set next descriptor address register equal * to the first descriptor base address */ rxdesc->rdes3 = (uint32_t)&rxtable[0].rxdesc; } } /* Flush all of the initialized RX descriptors to physical memory */ up_clean_dcache((uintptr_t)rxtable, (uintptr_t)rxtable + RXTABLE_SIZE * sizeof(union stm32_rxdesc_u)); /* Set Receive Descriptor List Address Register */ stm32_putreg((uint32_t)&rxtable[0].rxdesc, STM32_ETH_DMARDLAR); } /**************************************************************************** * Function: stm32_ioctl * * Description: * Executes the SIOCxMIIxxx command and responds using the request struct * that must be provided as its 2nd parameter. * * When called with SIOCGMIIPHY it will get the PHY address for the device * and write it to the req->phy_id field of the request struct. * * When called with SIOCGMIIREG it will read a register of the PHY that is * specified using the req->reg_no struct field and then write its output * to the req->val_out field. * * When called with SIOCSMIIREG it will write to a register of the PHY that * is specified using the req->reg_no struct field and use req->val_in as * its input. * * Input Parameters: * dev - Ethernet device structure * cmd - SIOCxMIIxxx command code * arg - Request structure also used to return values * * Returned Value: Negated errno on failure. * * Assumptions: * ****************************************************************************/ #ifdef CONFIG_NETDEV_IOCTL static int stm32_ioctl(struct net_driver_s *dev, int cmd, unsigned long arg) { #if defined(CONFIG_NETDEV_PHY_IOCTL) && defined(CONFIG_ARCH_PHY_INTERRUPT) struct stm32_ethmac_s *priv = (struct stm32_ethmac_s *)dev->d_private; #endif int ret; switch (cmd) { #ifdef CONFIG_NETDEV_PHY_IOCTL #ifdef CONFIG_ARCH_PHY_INTERRUPT case SIOCMIINOTIFY: /* Set up for PHY event notifications */ { struct mii_ioctl_notify_s *req = (struct mii_ioctl_notify_s *)((uintptr_t)arg); ret = phy_notify_subscribe(dev->d_ifname, req->pid, &req->event); if (ret == OK) { /* Enable PHY link up/down interrupts */ ret = stm32_phyintenable(priv); } } break; #endif case SIOCGMIIPHY: /* Get MII PHY address */ { struct mii_ioctl_data_s *req = (struct mii_ioctl_data_s *)((uintptr_t)arg); req->phy_id = CONFIG_STM32F7_PHYADDR; ret = OK; } break; case SIOCGMIIREG: /* Get register from MII PHY */ { struct mii_ioctl_data_s *req = (struct mii_ioctl_data_s *)((uintptr_t)arg); ret = stm32_phyread(req->phy_id, req->reg_num, &req->val_out); } break; case SIOCSMIIREG: /* Set register in MII PHY */ { struct mii_ioctl_data_s *req = (struct mii_ioctl_data_s *)((uintptr_t)arg); ret = stm32_phywrite(req->phy_id, req->reg_num, req->val_in); } break; #endif /* CONFIG_NETDEV_PHY_IOCTL */ default: ret = -ENOTTY; break; } return ret; } #endif /* CONFIG_NETDEV_IOCTL */ /**************************************************************************** * Function: stm32_phyintenable * * Description: * Enable link up/down PHY interrupts. The interrupt protocol is like this: * * - Interrupt status is cleared when the interrupt is enabled. * - Interrupt occurs. Interrupt is disabled (at the processor level) when * is received. * - Interrupt status is cleared when the interrupt is re-enabled. * * Input Parameters: * priv - A reference to the private driver state structure * * Returned Value: * OK on success; Negated errno (-ETIMEDOUT) on failure. * ****************************************************************************/ #if defined(CONFIG_NETDEV_PHY_IOCTL) && defined(CONFIG_ARCH_PHY_INTERRUPT) static int stm32_phyintenable(struct stm32_ethmac_s *priv) { #warning Missing logic return -ENOSYS; } #endif /**************************************************************************** * Function: stm32_phyread * * Description: * Read a PHY register. * * Input Parameters: * phydevaddr - The PHY device address * phyregaddr - The PHY register address * value - The location to return the 16-bit PHY register value. * * Returned Value: * OK on success; Negated errno on failure. * * Assumptions: * ****************************************************************************/ static int stm32_phyread(uint16_t phydevaddr, uint16_t phyregaddr, uint16_t *value) { volatile uint32_t timeout; uint32_t regval; /* Configure the MACMIIAR register, preserving CSR Clock Range CR[2:0] bits */ regval = stm32_getreg(STM32_ETH_MACMIIAR); regval &= ETH_MACMIIAR_CR_MASK; /* Set the PHY device address, PHY register address, and set the buy bit. * the ETH_MACMIIAR_MW is clear, indicating a read operation. */ regval |= (((uint32_t)phydevaddr << ETH_MACMIIAR_PA_SHIFT) & ETH_MACMIIAR_PA_MASK); regval |= (((uint32_t)phyregaddr << ETH_MACMIIAR_MR_SHIFT) & ETH_MACMIIAR_MR_MASK); regval |= ETH_MACMIIAR_MB; stm32_putreg(regval, STM32_ETH_MACMIIAR); /* Wait for the transfer to complete */ for (timeout = 0; timeout < PHY_READ_TIMEOUT; timeout++) { if ((stm32_getreg(STM32_ETH_MACMIIAR) & ETH_MACMIIAR_MB) == 0) { *value = (uint16_t)stm32_getreg(STM32_ETH_MACMIIDR); return OK; } } ninfo("MII transfer timed out: phydevaddr: %04x phyregaddr: %04x\n", phydevaddr, phyregaddr); return -ETIMEDOUT; } /**************************************************************************** * Function: stm32_phywrite * * Description: * Write to a PHY register. * * Input Parameters: * phydevaddr - The PHY device address * phyregaddr - The PHY register address * value - The 16-bit value to write to the PHY register value. * * Returned Value: * OK on success; Negated errno on failure. * * Assumptions: * ****************************************************************************/ static int stm32_phywrite(uint16_t phydevaddr, uint16_t phyregaddr, uint16_t value) { volatile uint32_t timeout; uint32_t regval; /* Configure the MACMIIAR register, preserving CSR Clock Range CR[2:0] bits */ regval = stm32_getreg(STM32_ETH_MACMIIAR); regval &= ETH_MACMIIAR_CR_MASK; /* Set the PHY device address, PHY register address, and set the busy bit. * the ETH_MACMIIAR_MW is set, indicating a write operation. */ regval |= (((uint32_t)phydevaddr << ETH_MACMIIAR_PA_SHIFT) & ETH_MACMIIAR_PA_MASK); regval |= (((uint32_t)phyregaddr << ETH_MACMIIAR_MR_SHIFT) & ETH_MACMIIAR_MR_MASK); regval |= (ETH_MACMIIAR_MB | ETH_MACMIIAR_MW); /* Write the value into the MACIIDR register before setting the new MACMIIAR * register value. */ stm32_putreg(value, STM32_ETH_MACMIIDR); stm32_putreg(regval, STM32_ETH_MACMIIAR); /* Wait for the transfer to complete */ for (timeout = 0; timeout < PHY_WRITE_TIMEOUT; timeout++) { if ((stm32_getreg(STM32_ETH_MACMIIAR) & ETH_MACMIIAR_MB) == 0) { return OK; } } ninfo("MII transfer timed out: phydevaddr: %04x phyregaddr: %04x value: %04x\n", phydevaddr, phyregaddr, value); return -ETIMEDOUT; } /**************************************************************************** * Function: stm32_dm9161 * * Description: * Special workaround for the Davicom DM9161 PHY is required. On power, * up, the PHY is not usually configured correctly but will work after * a powered-up reset. This is really a workaround for some more * fundamental issue with the PHY clocking initialization, but the * root cause has not been studied (nor will it be with this workaround). * * Input Parameters: * priv - A reference to the private driver state structure * * Returned Value: * None * ****************************************************************************/ #ifdef CONFIG_ETH0_PHY_DM9161 static inline int stm32_dm9161(struct stm32_ethmac_s *priv) { uint16_t phyval; int ret; /* Read the PHYID1 register; A failure to read the PHY ID is one * indication that check if the DM9161 PHY CHIP is not ready. */ ret = stm32_phyread(CONFIG_STM32F7_PHYADDR, MII_PHYID1, &phyval); if (ret < 0) { nerr("ERROR: Failed to read the PHY ID1: %d\n", ret); return ret; } /* If we failed to read the PHY ID1 register, the reset the MCU to recover */ else if (phyval == 0xffff) { up_systemreset(); } ninfo("PHY ID1: 0x%04X\n", phyval); /* Now check the "DAVICOM Specified Configuration Register (DSCR)", Register 16 */ ret = stm32_phyread(CONFIG_STM32F7_PHYADDR, 16, &phyval); if (ret < 0) { nerr("ERROR: Failed to read the PHY Register 0x10: %d\n", ret); return ret; } /* Bit 8 of the DSCR register is zero, then the DM9161 has not selected RMII. * If RMII is not selected, then reset the MCU to recover. */ else if ((phyval & (1 << 8)) == 0) { up_systemreset(); } return OK; } #endif /**************************************************************************** * Function: stm32_phyinit * * Description: * Configure the PHY and determine the link speed/duplex. * * Input Parameters: * priv - A reference to the private driver state structure * * Returned Value: * OK on success; Negated errno on failure. * * Assumptions: * ****************************************************************************/ static int stm32_phyinit(struct stm32_ethmac_s *priv) { volatile uint32_t timeout; uint32_t regval; uint16_t phyval; int ret; /* Assume 10MBps and half duplex */ priv->mbps100 = 0; priv->fduplex = 0; /* Setup up PHY clocking by setting the SR field in the MACMIIAR register */ regval = stm32_getreg(STM32_ETH_MACMIIAR); regval &= ~ETH_MACMIIAR_CR_MASK; regval |= ETH_MACMIIAR_CR; stm32_putreg(regval, STM32_ETH_MACMIIAR); /* Put the PHY in reset mode */ ret = stm32_phywrite(CONFIG_STM32F7_PHYADDR, MII_MCR, MII_MCR_RESET); if (ret < 0) { nerr("ERROR: Failed to reset the PHY: %d\n", ret); return ret; } up_mdelay(PHY_RESET_DELAY); /* Perform any necessary, board-specific PHY initialization */ #ifdef CONFIG_STM32F7_PHYINIT ret = stm32_phy_boardinitialize(0); if (ret < 0) { nerr("ERROR: Failed to initialize the PHY: %d\n", ret); return ret; } #endif /* Special workaround for the Davicom DM9161 PHY is required. */ #ifdef CONFIG_ETH0_PHY_DM9161 ret = stm32_dm9161(priv); if (ret < 0) { return ret; } #endif /* Perform auto-negotiation if so configured */ #ifdef CONFIG_STM32F7_AUTONEG /* Wait for link status */ for (timeout = 0; timeout < PHY_RETRY_TIMEOUT; timeout++) { ret = stm32_phyread(CONFIG_STM32F7_PHYADDR, MII_MSR, &phyval); if (ret < 0) { nerr("ERROR: Failed to read the PHY MSR: %d\n", ret); return ret; } else if ((phyval & MII_MSR_LINKSTATUS) != 0) { break; } nxsig_usleep(100); } if (timeout >= PHY_RETRY_TIMEOUT) { nerr("ERROR: Timed out waiting for link status: %04x\n", phyval); return -ETIMEDOUT; } /* Enable auto-negotiation */ ret = stm32_phywrite(CONFIG_STM32F7_PHYADDR, MII_MCR, MII_MCR_ANENABLE); if (ret < 0) { nerr("ERROR: Failed to enable auto-negotiation: %d\n", ret); return ret; } /* Wait until auto-negotiation completes */ for (timeout = 0; timeout < PHY_RETRY_TIMEOUT; timeout++) { ret = stm32_phyread(CONFIG_STM32F7_PHYADDR, MII_MSR, &phyval); if (ret < 0) { nerr("ERROR: Failed to read the PHY MSR: %d\n", ret); return ret; } else if ((phyval & MII_MSR_ANEGCOMPLETE) != 0) { break; } nxsig_usleep(100); } if (timeout >= PHY_RETRY_TIMEOUT) { nerr("ERROR: Timed out waiting for auto-negotiation\n"); return -ETIMEDOUT; } /* Read the result of the auto-negotiation from the PHY-specific register */ ret = stm32_phyread(CONFIG_STM32F7_PHYADDR, CONFIG_STM32F7_PHYSR, &phyval); if (ret < 0) { nerr("ERROR: Failed to read PHY status register\n"); return ret; } /* Remember the selected speed and duplex modes */ ninfo("PHYSR[%d]: %04x\n", CONFIG_STM32F7_PHYSR, phyval); /* Different PHYs present speed and mode information in different ways. IF * This CONFIG_STM32F7_PHYSR_ALTCONFIG is selected, this indicates that the PHY * represents speed and mode information are combined, for example, with * separate bits for 10HD, 100HD, 10FD and 100FD. */ #ifdef CONFIG_STM32F7_PHYSR_ALTCONFIG switch (phyval & CONFIG_STM32F7_PHYSR_ALTMODE) { default: nerr("ERROR: Unrecognized PHY status setting\n"); /* Falls through */ case CONFIG_STM32F7_PHYSR_10HD: priv->fduplex = 0; priv->mbps100 = 0; break; case CONFIG_STM32F7_PHYSR_100HD: priv->fduplex = 0; priv->mbps100 = 1; break; case CONFIG_STM32F7_PHYSR_10FD: priv->fduplex = 1; priv->mbps100 = 0; break; case CONFIG_STM32F7_PHYSR_100FD: priv->fduplex = 1; priv->mbps100 = 1; break; } /* Different PHYs present speed and mode information in different ways. Some * will present separate information for speed and mode (this is the default). * Those PHYs, for example, may provide a 10/100 Mbps indication and a separate * full/half duplex indication. */ #else if ((phyval & CONFIG_STM32F7_PHYSR_MODE) == CONFIG_STM32F7_PHYSR_FULLDUPLEX) { priv->fduplex = 1; } if ((phyval & CONFIG_STM32F7_PHYSR_SPEED) == CONFIG_STM32F7_PHYSR_100MBPS) { priv->mbps100 = 1; } #endif #else /* Auto-negotiation not selected */ phyval = 0; #ifdef CONFIG_STM32F7_ETHFD phyval |= MII_MCR_FULLDPLX; #endif #ifdef CONFIG_STM32F7_ETH100MBPS phyval |= MII_MCR_SPEED100; #endif ret = stm32_phywrite(CONFIG_STM32F7_PHYADDR, MII_MCR, phyval); if (ret < 0) { nerr("ERROR: Failed to write the PHY MCR: %d\n", ret); return ret; } up_mdelay(PHY_CONFIG_DELAY); /* Remember the selected speed and duplex modes */ #ifdef CONFIG_STM32F7_ETHFD priv->fduplex = 1; #endif #ifdef CONFIG_STM32F7_ETH100MBPS priv->mbps100 = 1; #endif #endif ninfo("Duplex: %s Speed: %d MBps\n", priv->fduplex ? "FULL" : "HALF", priv->mbps100 ? 100 : 10); return OK; } /************************************************************************************ * Name: stm32_selectmii * * Description: * Selects the MII interface. * * Input Parameters: * None * * Returned Value: * None * ************************************************************************************/ #ifdef CONFIG_STM32F7_MII static inline void stm32_selectmii(void) { uint32_t regval; regval = getreg32(STM32_SYSCFG_PMC); regval &= ~SYSCFG_PMC_MII_RMII_SEL; putreg32(regval, STM32_SYSCFG_PMC); } #endif /************************************************************************************ * Name: stm32_selectrmii * * Description: * Selects the RMII interface. * * Input Parameters: * None * * Returned Value: * None * ************************************************************************************/ static inline void stm32_selectrmii(void) { uint32_t regval; regval = getreg32(STM32_SYSCFG_PMC); regval |= SYSCFG_PMC_MII_RMII_SEL; putreg32(regval, STM32_SYSCFG_PMC); } /**************************************************************************** * Function: stm32_ethgpioconfig * * Description: * Configure GPIOs for the Ethernet interface. * * Input Parameters: * priv - A reference to the private driver state structure * * Returned Value: * None. * * Assumptions: * ****************************************************************************/ static inline void stm32_ethgpioconfig(struct stm32_ethmac_s *priv) { /* Configure GPIO pins to support Ethernet */ #if defined(CONFIG_STM32F7_MII) || defined(CONFIG_STM32F7_RMII) /* MDC and MDIO are common to both modes */ stm32_configgpio(GPIO_ETH_MDC); stm32_configgpio(GPIO_ETH_MDIO); /* Set up the MII interface */ # if defined(CONFIG_STM32F7_MII) /* Select the MII interface */ stm32_selectmii(); /* Provide clocking via MCO, MCO1 or MCO2: * * "MCO1 (microcontroller clock output), used to output HSI, LSE, HSE or PLL * clock (through a configurable prescaler) on PA8 pin." * * "MCO2 (microcontroller clock output), used to output HSE, PLL, SYSCLK or * PLLI2S clock (through a configurable prescaler) on PC9 pin." */ # if defined(CONFIG_STM32F7_MII_MCO1) /* Configure MC01 to drive the PHY. Board logic must provide MC01 clocking * info. */ stm32_configgpio(GPIO_MCO1); stm32_mco1config(BOARD_CFGR_MC01_SOURCE, BOARD_CFGR_MC01_DIVIDER); # elif defined(CONFIG_STM32F7_MII_MCO2) /* Configure MC02 to drive the PHY. Board logic must provide MC02 clocking * info. */ stm32_configgpio(GPIO_MCO2); stm32_mco2config(BOARD_CFGR_MC02_SOURCE, BOARD_CFGR_MC02_DIVIDER); # elif defined(CONFIG_STM32F7_MII_MCO) /* Setup MCO pin for alternative usage */ stm32_configgpio(GPIO_MCO); stm32_mcoconfig(BOARD_CFGR_MCO_SOURCE); # endif /* MII interface pins (17): * * MII_TX_CLK, MII_TXD[3:0], MII_TX_EN, MII_RX_CLK, MII_RXD[3:0], MII_RX_ER, * MII_RX_DV, MII_CRS, MII_COL, MDC, MDIO */ stm32_configgpio(GPIO_ETH_MII_COL); stm32_configgpio(GPIO_ETH_MII_CRS); stm32_configgpio(GPIO_ETH_MII_RXD0); stm32_configgpio(GPIO_ETH_MII_RXD1); stm32_configgpio(GPIO_ETH_MII_RXD2); stm32_configgpio(GPIO_ETH_MII_RXD3); stm32_configgpio(GPIO_ETH_MII_RX_CLK); stm32_configgpio(GPIO_ETH_MII_RX_DV); stm32_configgpio(GPIO_ETH_MII_RX_ER); stm32_configgpio(GPIO_ETH_MII_TXD0); stm32_configgpio(GPIO_ETH_MII_TXD1); stm32_configgpio(GPIO_ETH_MII_TXD2); stm32_configgpio(GPIO_ETH_MII_TXD3); stm32_configgpio(GPIO_ETH_MII_TX_CLK); stm32_configgpio(GPIO_ETH_MII_TX_EN); /* Set up the RMII interface. */ # elif defined(CONFIG_STM32F7_RMII) /* Select the RMII interface */ stm32_selectrmii(); /* Provide clocking via MCO, MCO1 or MCO2: * * "MCO1 (microcontroller clock output), used to output HSI, LSE, HSE or PLL * clock (through a configurable prescaler) on PA8 pin." * * "MCO2 (microcontroller clock output), used to output HSE, PLL, SYSCLK or * PLLI2S clock (through a configurable prescaler) on PC9 pin." */ # if defined(CONFIG_STM32F7_RMII_MCO1) /* Configure MC01 to drive the PHY. Board logic must provide MC01 clocking * info. */ stm32_configgpio(GPIO_MCO1); stm32_mco1config(BOARD_CFGR_MC01_SOURCE, BOARD_CFGR_MC01_DIVIDER); # elif defined(CONFIG_STM32F7_RMII_MCO2) /* Configure MC02 to drive the PHY. Board logic must provide MC02 clocking * info. */ stm32_configgpio(GPIO_MCO2); stm32_mco2config(BOARD_CFGR_MC02_SOURCE, BOARD_CFGR_MC02_DIVIDER); # elif defined(CONFIG_STM32F7_RMII_MCO) /* Setup MCO pin for alternative usage */ stm32_configgpio(GPIO_MCO); stm32_mcoconfig(BOARD_CFGR_MCO_SOURCE); # endif /* RMII interface pins (7): * * RMII_TXD[1:0], RMII_TX_EN, RMII_RXD[1:0], RMII_CRS_DV, MDC, MDIO, * RMII_REF_CLK */ stm32_configgpio(GPIO_ETH_RMII_CRS_DV); stm32_configgpio(GPIO_ETH_RMII_REF_CLK); stm32_configgpio(GPIO_ETH_RMII_RXD0); stm32_configgpio(GPIO_ETH_RMII_RXD1); stm32_configgpio(GPIO_ETH_RMII_TXD0); stm32_configgpio(GPIO_ETH_RMII_TXD1); stm32_configgpio(GPIO_ETH_RMII_TX_EN); # endif #endif #ifdef CONFIG_STM32F7_ETH_PTP /* Enable pulse-per-second (PPS) output signal */ stm32_configgpio(GPIO_ETH_PPS_OUT); #endif } /**************************************************************************** * Function: stm32_ethreset * * Description: * Reset the Ethernet block. * * Input Parameters: * priv - A reference to the private driver state structure * * Returned Value: * None. * * Assumptions: * ****************************************************************************/ static void stm32_ethreset(struct stm32_ethmac_s *priv) { uint32_t regval; volatile uint32_t timeout; /* Reset the Ethernet on the AHB bus (F1 Connectivity Line) or AHB1 bus (F2 * and F4) */ regval = stm32_getreg(STM32_RCC_AHB1RSTR); regval |= RCC_AHB1RSTR_ETHMACRST; stm32_putreg(regval, STM32_RCC_AHB1RSTR); regval &= ~RCC_AHB1RSTR_ETHMACRST; stm32_putreg(regval, STM32_RCC_AHB1RSTR); /* Perform a software reset by setting the SR bit in the DMABMR register. * This Resets all MAC subsystem internal registers and logic. After this * reset all the registers holds their reset values. */ regval = stm32_getreg(STM32_ETH_DMABMR); regval |= ETH_DMABMR_SR; stm32_putreg(regval, STM32_ETH_DMABMR); /* Wait for software reset to complete. The SR bit is cleared automatically * after the reset operation has completed in all of the core clock domains. */ timeout = MAC_READY_USTIMEOUT; while (timeout-- && (stm32_getreg(STM32_ETH_DMABMR) & ETH_DMABMR_SR) != 0) { up_udelay(1); } } /**************************************************************************** * Function: stm32_macconfig * * Description: * Configure the Ethernet MAC for DMA operation. * * Input Parameters: * priv - A reference to the private driver state structure * * Returned Value: * OK on success; Negated errno on failure. * * Assumptions: * ****************************************************************************/ static int stm32_macconfig(struct stm32_ethmac_s *priv) { uint32_t regval; /* Set up the MACCR register */ regval = stm32_getreg(STM32_ETH_MACCR); regval &= ~MACCR_CLEAR_BITS; regval |= MACCR_SET_BITS; if (priv->fduplex) { /* Set the DM bit for full duplex support */ regval |= ETH_MACCR_DM; } if (priv->mbps100) { /* Set the FES bit for 100Mbps fast ethernet support */ regval |= ETH_MACCR_FES; } stm32_putreg(regval, STM32_ETH_MACCR); /* Set up the MACFFR register */ regval = stm32_getreg(STM32_ETH_MACFFR); regval &= ~MACFFR_CLEAR_BITS; regval |= MACFFR_SET_BITS; stm32_putreg(regval, STM32_ETH_MACFFR); /* Set up the MACHTHR and MACHTLR registers */ stm32_putreg(0, STM32_ETH_MACHTHR); stm32_putreg(0, STM32_ETH_MACHTLR); /* Setup up the MACFCR register */ regval = stm32_getreg(STM32_ETH_MACFCR); regval &= ~MACFCR_CLEAR_MASK; regval |= MACFCR_SET_MASK; stm32_putreg(regval, STM32_ETH_MACFCR); /* Setup up the MACVLANTR register */ stm32_putreg(0, STM32_ETH_MACVLANTR); /* DMA Configuration */ /* Set up the DMAOMR register */ regval = stm32_getreg(STM32_ETH_DMAOMR); regval &= ~DMAOMR_CLEAR_MASK; regval |= DMAOMR_SET_MASK; stm32_putreg(regval, STM32_ETH_DMAOMR); /* Set up the DMABMR register */ regval = stm32_getreg(STM32_ETH_DMABMR); regval &= ~DMABMR_CLEAR_MASK; regval |= DMABMR_SET_MASK; stm32_putreg(regval, STM32_ETH_DMABMR); return OK; } /**************************************************************************** * Function: stm32_macaddress * * Description: * Configure the selected MAC address. * * Input Parameters: * priv - A reference to the private driver state structure * * Returned Value: * OK on success; Negated errno on failure. * * Assumptions: * ****************************************************************************/ static void stm32_macaddress(struct stm32_ethmac_s *priv) { struct net_driver_s *dev = &priv->dev; uint32_t regval; ninfo("%s MAC: %02x:%02x:%02x:%02x:%02x:%02x\n", dev->d_ifname, dev->d_mac.ether.ether_addr_octet[0], dev->d_mac.ether.ether_addr_octet[1], dev->d_mac.ether.ether_addr_octet[2], dev->d_mac.ether.ether_addr_octet[3], dev->d_mac.ether.ether_addr_octet[4], dev->d_mac.ether.ether_addr_octet[5]); /* Set the MAC address high register */ regval = ((uint32_t)dev->d_mac.ether.ether_addr_octet[5] << 8) | (uint32_t)dev->d_mac.ether.ether_addr_octet[4]; stm32_putreg(regval, STM32_ETH_MACA0HR); /* Set the MAC address low register */ regval = ((uint32_t)dev->d_mac.ether.ether_addr_octet[3] << 24) | ((uint32_t)dev->d_mac.ether.ether_addr_octet[2] << 16) | ((uint32_t)dev->d_mac.ether.ether_addr_octet[1] << 8) | (uint32_t)dev->d_mac.ether.ether_addr_octet[0]; stm32_putreg(regval, STM32_ETH_MACA0LR); } /**************************************************************************** * Function: stm32_ipv6multicast * * Description: * Configure the IPv6 multicast MAC address. * * Input Parameters: * priv - A reference to the private driver state structure * * Returned Value: * OK on success; Negated errno on failure. * * Assumptions: * ****************************************************************************/ #ifdef CONFIG_NET_ICMPv6 static void stm32_ipv6multicast(struct stm32_ethmac_s *priv) { struct net_driver_s *dev; uint16_t tmp16; uint8_t mac[6]; /* For ICMPv6, we need to add the IPv6 multicast address * * For IPv6 multicast addresses, the Ethernet MAC is derived by * the four low-order octets OR'ed with the MAC 33:33:00:00:00:00, * so for example the IPv6 address FF02:DEAD:BEEF::1:3 would map * to the Ethernet MAC address 33:33:00:01:00:03. * * NOTES: This appears correct for the ICMPv6 Router Solicitation * Message, but the ICMPv6 Neighbor Solicitation message seems to * use 33:33:ff:01:00:03. */ mac[0] = 0x33; mac[1] = 0x33; dev = &priv->dev; tmp16 = dev->d_ipv6addr[6]; mac[2] = 0xff; mac[3] = tmp16 >> 8; tmp16 = dev->d_ipv6addr[7]; mac[4] = tmp16 & 0xff; mac[5] = tmp16 >> 8; ninfo("IPv6 Multicast: %02x:%02x:%02x:%02x:%02x:%02x\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); stm32_addmac(dev, mac); #ifdef CONFIG_NET_ICMPv6_AUTOCONF /* Add the IPv6 all link-local nodes Ethernet address. This is the * address that we expect to receive ICMPv6 Router Advertisement * packets. */ stm32_addmac(dev, g_ipv6_ethallnodes.ether_addr_octet); #endif /* CONFIG_NET_ICMPv6_AUTOCONF */ #ifdef CONFIG_NET_ICMPv6_ROUTER /* Add the IPv6 all link-local routers Ethernet address. This is the * address that we expect to receive ICMPv6 Router Solicitation * packets. */ stm32_addmac(dev, g_ipv6_ethallrouters.ether_addr_octet); #endif /* CONFIG_NET_ICMPv6_ROUTER */ } #endif /* CONFIG_NET_ICMPv6 */ /**************************************************************************** * Function: stm32_macenable * * Description: * Enable normal MAC operation. * * Input Parameters: * priv - A reference to the private driver state structure * * Returned Value: * OK on success; Negated errno on failure. * * Assumptions: * ****************************************************************************/ static int stm32_macenable(struct stm32_ethmac_s *priv) { uint32_t regval; /* Set the MAC address */ stm32_macaddress(priv); #ifdef CONFIG_NET_ICMPv6 /* Set up the IPv6 multicast address */ stm32_ipv6multicast(priv); #endif /* Enable transmit state machine of the MAC for transmission on the MII */ regval = stm32_getreg(STM32_ETH_MACCR); regval |= ETH_MACCR_TE; stm32_putreg(regval, STM32_ETH_MACCR); /* Flush Transmit FIFO */ regval = stm32_getreg(STM32_ETH_DMAOMR); regval |= ETH_DMAOMR_FTF; stm32_putreg(regval, STM32_ETH_DMAOMR); /* Enable receive state machine of the MAC for reception from the MII */ /* Enables or disables the MAC reception. */ regval = stm32_getreg(STM32_ETH_MACCR); regval |= ETH_MACCR_RE; stm32_putreg(regval, STM32_ETH_MACCR); /* Start DMA transmission */ regval = stm32_getreg(STM32_ETH_DMAOMR); regval |= ETH_DMAOMR_ST; stm32_putreg(regval, STM32_ETH_DMAOMR); /* Start DMA reception */ regval = stm32_getreg(STM32_ETH_DMAOMR); regval |= ETH_DMAOMR_SR; stm32_putreg(regval, STM32_ETH_DMAOMR); /* Enable Ethernet DMA interrupts. * * The STM32 hardware supports two interrupts: (1) one dedicated to normal * Ethernet operations and the other, used only for the Ethernet wakeup * event. The wake-up interrupt is not used by this driver. * * The first Ethernet vector is reserved for interrupts generated by the * MAC and the DMA. The MAC provides PMT and time stamp trigger interrupts, * neither of which are used by this driver. */ stm32_putreg(ETH_MACIMR_ALLINTS, STM32_ETH_MACIMR); /* Ethernet DMA supports two classes of interrupts: Normal interrupt * summary (NIS) and Abnormal interrupt summary (AIS) with a variety * individual normal and abnormal interrupting events. Here only * the normal receive event is enabled (unless DEBUG is enabled). Transmit * events will only be enabled when a transmit interrupt is expected. */ stm32_putreg((ETH_DMAINT_RECV_ENABLE | ETH_DMAINT_ERROR_ENABLE), STM32_ETH_DMAIER); return OK; } /**************************************************************************** * Function: stm32_ethconfig * * Description: * Configure the Ethernet interface for DMA operation. * * Input Parameters: * priv - A reference to the private driver state structure * * Returned Value: * OK on success; Negated errno on failure. * * Assumptions: * ****************************************************************************/ static int stm32_ethconfig(struct stm32_ethmac_s *priv) { int ret; /* NOTE: The Ethernet clocks were initialized early in the boot-up * sequence in stm32_rcc.c. */ /* Reset the Ethernet block */ ninfo("Reset the Ethernet block\n"); stm32_ethreset(priv); /* Initialize the PHY */ ninfo("Initialize the PHY\n"); ret = stm32_phyinit(priv); if (ret < 0) { return ret; } /* Initialize the MAC and DMA */ ninfo("Initialize the MAC and DMA\n"); ret = stm32_macconfig(priv); if (ret < 0) { return ret; } /* Initialize the free buffer list */ stm32_initbuffer(priv, &g_txbuffer[priv->intf * TXBUFFER_SIZE]); /* Initialize TX Descriptors list: Chain Mode */ stm32_txdescinit(priv, &g_txtable[priv->intf * CONFIG_STM32F7_ETH_NTXDESC]); /* Initialize RX Descriptors list: Chain Mode */ stm32_rxdescinit(priv, &g_rxtable[priv->intf * CONFIG_STM32F7_ETH_NRXDESC], &g_rxbuffer[priv->intf * RXBUFFER_SIZE]); /* Enable normal MAC operation */ ninfo("Enable normal operation\n"); return stm32_macenable(priv); } /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Function: stm32_ethinitialize * * Description: * Initialize the Ethernet driver for one interface. If the STM32 chip * supports multiple Ethernet controllers, then board specific logic * must implement arm_netinitialize() and call this function to initialize * the desired interfaces. * * Input Parameters: * intf - In the case where there are multiple EMACs, this value * identifies which EMAC is to be initialized. * * Returned Value: * OK on success; Negated errno on failure. * * Assumptions: * ****************************************************************************/ #if STM32F7_NETHERNET == 1 || defined(CONFIG_NETDEV_LATEINIT) static inline #endif int stm32_ethinitialize(int intf) { struct stm32_ethmac_s *priv; uint8_t uid[12]; uint64_t crc; ninfo("intf: %d\n", intf); /* Get the interface structure associated with this interface number. */ DEBUGASSERT(intf < STM32F7_NETHERNET); priv = &g_stm32ethmac[intf]; /* Initialize the driver structure */ memset(priv, 0, sizeof(struct stm32_ethmac_s)); priv->dev.d_ifup = stm32_ifup; /* I/F up (new IP address) callback */ priv->dev.d_ifdown = stm32_ifdown; /* I/F down callback */ priv->dev.d_txavail = stm32_txavail; /* New TX data callback */ #ifdef CONFIG_NET_MCASTGROUP priv->dev.d_addmac = stm32_addmac; /* Add multicast MAC address */ priv->dev.d_rmmac = stm32_rmmac; /* Remove multicast MAC address */ #endif #ifdef CONFIG_NETDEV_IOCTL priv->dev.d_ioctl = stm32_ioctl; /* Support PHY ioctl() calls */ #endif priv->dev.d_private = (void *)g_stm32ethmac; /* Used to recover private state from dev */ priv->intf = intf; /* Remember the interface number */ /* Create a watchdog for timing polling for and timing of transmissions */ priv->txpoll = wd_create(); /* Create periodic poll timer */ priv->txtimeout = wd_create(); /* Create TX timeout timer */ stm32_get_uniqueid(uid); crc = crc64(uid, 12); /* Specify as localy administrated address */ priv->dev.d_mac.ether.ether_addr_octet[0] = (crc >> 0) | 0x02; priv->dev.d_mac.ether.ether_addr_octet[0] &= ~0x1; priv->dev.d_mac.ether.ether_addr_octet[1] = crc >> 8; priv->dev.d_mac.ether.ether_addr_octet[2] = crc >> 16; priv->dev.d_mac.ether.ether_addr_octet[3] = crc >> 24; priv->dev.d_mac.ether.ether_addr_octet[4] = crc >> 32; priv->dev.d_mac.ether.ether_addr_octet[5] = crc >> 40; /* Configure GPIO pins to support Ethernet */ stm32_ethgpioconfig(priv); /* Attach the IRQ to the driver */ if (irq_attach(STM32_IRQ_ETH, stm32_interrupt, NULL)) { /* We could not attach the ISR to the interrupt */ return -EAGAIN; } /* Put the interface in the down state. */ stm32_ifdown(&priv->dev); /* Register the device with the OS so that socket IOCTLs can be performed */ netdev_register(&priv->dev, NET_LL_ETHERNET); return OK; } /**************************************************************************** * Function: arm_netinitialize * * Description: * This is the "standard" network initialization logic called from the * low-level initialization logic in arm_initialize.c. If STM32F7_NETHERNET * greater than one, then board specific logic will have to supply a * version of arm_netinitialize() that calls stm32_ethinitialize() with * the appropriate interface number. * * Input Parameters: * None. * * Returned Value: * None. * * Assumptions: * ****************************************************************************/ #if STM32F7_NETHERNET == 1 && !defined(CONFIG_NETDEV_LATEINIT) void arm_netinitialize(void) { stm32_ethinitialize(0); } #endif #endif /* STM32F7_NETHERNET > 0 && CONFIG_STM32F7_ETHMAC */
29.473085
113
0.617904
[ "vector" ]
b11f88e5929d11f06718b4d3e1a50514dece8adb
21,629
h
C
libretro/libretro_core_options.h
Ryunam/Genesis-Plus-GX-Wide
0742b9a65f14c1d87538b64e0b2daa08c3925b53
[ "BSD-3-Clause" ]
null
null
null
libretro/libretro_core_options.h
Ryunam/Genesis-Plus-GX-Wide
0742b9a65f14c1d87538b64e0b2daa08c3925b53
[ "BSD-3-Clause" ]
null
null
null
libretro/libretro_core_options.h
Ryunam/Genesis-Plus-GX-Wide
0742b9a65f14c1d87538b64e0b2daa08c3925b53
[ "BSD-3-Clause" ]
null
null
null
#ifndef LIBRETRO_CORE_OPTIONS_H__ #define LIBRETRO_CORE_OPTIONS_H__ #include <stdlib.h> #include <string.h> #include <libretro.h> #include <retro_inline.h> #ifndef HAVE_NO_LANGEXTRA #include "libretro_core_options_intl.h" #endif /* ******************************** * VERSION: 1.3 ******************************** * * - 1.3: Move translations to libretro_core_options_intl.h * - libretro_core_options_intl.h includes BOM and utf-8 * fix for MSVC 2010-2013 * - Added HAVE_NO_LANGEXTRA flag to disable translations * on platforms/compilers without BOM support * - 1.2: Use core options v1 interface when * RETRO_ENVIRONMENT_GET_CORE_OPTIONS_VERSION is >= 1 * (previously required RETRO_ENVIRONMENT_GET_CORE_OPTIONS_VERSION == 1) * - 1.1: Support generation of core options v0 retro_core_option_value * arrays containing options with a single value * - 1.0: First commit */ #ifdef __cplusplus extern "C" { #endif /* ******************************** * Core Definitions ******************************** */ #if defined(M68K_OVERCLOCK_SHIFT) || defined(Z80_OVERCLOCK_SHIFT) #define HAVE_OVERCLOCK #endif /* ******************************** * Core Option Definitions ******************************** */ /* RETRO_LANGUAGE_ENGLISH */ /* Default language: * - All other languages must include the same keys and values * - Will be used as a fallback in the event that frontend language * is not available * - Will be used as a fallback for any missing entries in * frontend language definition */ struct retro_core_option_definition option_defs_us[] = { { "genesis_plus_gx_wide_system_hw", "System Hardware", "Runs loaded content with a specific emulated console. 'Auto' will select the most appropriate system for the current game.", { { "auto", "Auto" }, { "sg-1000", "SG-1000" }, { "sg-1000 II", "SG-1000 II" }, { "mark-III", "Mark III" }, { "master system", "Master System" }, { "master system II", "Master System II" }, { "game gear", "Game Gear" }, { "mega drive / genesis", "Mega Drive/Genesis" }, { NULL, NULL }, }, "auto" }, { "genesis_plus_gx_wide_region_detect", "System Region", "Specify which region the system is from. For consoles other than the Game Gear, 'PAL' is 50hz while 'NTSC' is 60hz. Games may run faster or slower than normal if the incorrect region is selected.", { { "auto", "Auto" }, { "ntsc-u", "NTSC-U" }, { "pal", "PAL" }, { "ntsc-j", "NTSC-J" }, { NULL, NULL }, }, "auto" }, { "genesis_plus_gx_wide_force_dtack", "System Lock-Ups", "Emulate system lock-ups that occur on real hardware when performing illegal address access. This should only be disabled when playing certain demos and homebrew that rely on illegal behaviour for correct operation.", { { "enabled", NULL }, { "disabled", NULL }, { NULL, NULL }, }, "enabled" }, { "genesis_plus_gx_wide_bios", "System Boot ROM", "Use official BIOS/bootloader for emulated hardware, if present in RetroArch's system directory. Displays console-specific start-up sequence/animation, then runs loaded content.", { { "disabled", NULL }, { "enabled", NULL }, { NULL, NULL }, }, "disabled" }, { "genesis_plus_gx_wide_bram", "CD System BRAM", "When running Sega CD content, specifies whether to share a single save file between all games from a specific region (Per-BIOS) or to create a separate save file for each game (Per-Game). Note that the Sega CD has limited internal storage, sufficient only for a handful of titles. To avoid running out of space, the 'Per-Game' setting is recommended.", { { "per bios", "Per-BIOS" }, { "per game", "Per-Game" }, { NULL, NULL }, }, "per bios" }, { "genesis_plus_gx_wide_addr_error", "68K Address Error", "The Genesis CPU (Motorola 68000) produces an Address Error (crash) when attempting to perform unaligned memory access. Enabling '68K Address Error' simulates this behaviour. It should only be disabled when playing ROM hacks, since these are typically developed using less accurate emulators and may rely on invalid RAM access for correct operation.", { { "enabled", NULL }, { "disabled", NULL }, { NULL, NULL }, }, "enabled" }, { "genesis_plus_gx_wide_lock_on", "Cartridge Lock-On", "Lock-On Technology is a Genesis feature that allowed an older game to connect to the pass-through port of a special cartridge for extended or altered gameplay. This option specifies which type of special 'lock-on' cartridge to emulate. A corresponding bios file must be present in RetroArch's system directory.", { { "disabled", NULL }, { "game genie", "Game Genie" }, { "action replay (pro)", "Action Replay (Pro)" }, { "sonic & knuckles", "Sonic & Knuckles" }, { NULL, NULL }, }, "disabled" }, { "genesis_plus_gx_wide_ym2413", "Master System FM (YM2413)", "Enable emulation of the FM Sound Unit used by certain Sega Mark III/Master System games for enhanced audio output.", { { "auto", "Auto" }, { "disabled", NULL }, { "enabled", NULL }, { NULL, NULL }, }, "auto" }, { "genesis_plus_gx_wide_ym2413_core", "Master System FM (YM2413) Core", "Select which core should be used for the emulation of the Master System FM Sound Unit.", { { "mame", "MAME" }, { "nuked", "Nuked" }, { NULL, NULL }, }, "mame" }, { "genesis_plus_gx_wide_ym2612", "Mega Drive / Genesis FM", #ifdef HAVE_YM3438_CORE "Select method used to emulate the FM synthesizer (main sound generator) of the Mega Drive/Genesis. 'MAME' options are fast, and run full speed on most systems. 'Nuked' options are cycle accurate, very high quality, and have substantial CPU requirements. The 'YM2612' chip is used by the original Model 1 Genesis. The 'YM3438' is used in later Genesis revisions.", #else "Select method used to emulate the FM synthesizer (main sound generator) of the Mega Drive/Genesis. The 'YM2612' chip is used by the original Model 1 Genesis. The 'YM3438' is used in later Genesis revisions.", #endif { { "mame (ym2612)", "MAME (YM2612)" }, { "mame (asic ym3438)", "MAME (ASIC YM3438)" }, { "mame (enhanced ym3438)", "MAME (Enhanced YM3438)" }, #ifdef HAVE_YM3438_CORE { "nuked (ym2612)", "Nuked (YM2612)" }, { "nuked (ym3438)", "Nuked (YM3438)" }, #endif { NULL, NULL }, }, "mame (ym2612)" }, { "genesis_plus_gx_wide_sound_output", "Sound Output", "Select stereo or mono sound reproduction.", { { "stereo", "Stereo" }, { "mono", "Mono" }, { NULL, NULL }, }, "stereo" }, { "genesis_plus_gx_wide_audio_filter", "Audio Filter", "Enable a low pass audio filter to better simulate the characteristic sound of a Model 1 Genesis.", { { "disabled", NULL }, { "low-pass", "Low-Pass" }, { NULL, NULL }, }, "disabled" }, { "genesis_plus_gx_wide_lowpass_range", "Low-Pass Filter %", "Specify the cut-off frequency of the audio low pass filter. A higher value increases the perceived 'strength' of the filter, since a wider range of the high frequency spectrum is attenuated.", { { "5", NULL }, { "10", NULL }, { "15", NULL }, { "20", NULL }, { "25", NULL }, { "30", NULL }, { "35", NULL }, { "40", NULL }, { "45", NULL }, { "50", NULL }, { "55", NULL }, { "60", NULL }, { "65", NULL }, { "70", NULL }, { "75", NULL }, { "80", NULL }, { "85", NULL }, { "90", NULL }, { "95", NULL }, { NULL, NULL }, }, "60" }, #ifdef HAVE_EQ { "genesis_plus_gx_wide_audio_eq_low", "EQ Low", "Adjust the low range band of the internal audio equaliser.", { { "0", NULL }, { "5", NULL }, { "10", NULL }, { "15", NULL }, { "20", NULL }, { "25", NULL }, { "30", NULL }, { "35", NULL }, { "40", NULL }, { "45", NULL }, { "50", NULL }, { "55", NULL }, { "60", NULL }, { "65", NULL }, { "70", NULL }, { "75", NULL }, { "80", NULL }, { "85", NULL }, { "90", NULL }, { "95", NULL }, { "100", NULL }, { NULL, NULL }, }, "100" }, { "genesis_plus_gx_wide_audio_eq_mid", "EQ Mid", "Adjust the middle range band of the internal audio equaliser.", { { "0", NULL }, { "5", NULL }, { "10", NULL }, { "15", NULL }, { "20", NULL }, { "25", NULL }, { "30", NULL }, { "35", NULL }, { "40", NULL }, { "45", NULL }, { "50", NULL }, { "55", NULL }, { "60", NULL }, { "65", NULL }, { "70", NULL }, { "75", NULL }, { "80", NULL }, { "85", NULL }, { "90", NULL }, { "95", NULL }, { "100", NULL }, { NULL, NULL }, }, "100" }, { "genesis_plus_gx_wide_audio_eq_high", "EQ High", "Adjust the high range band of the internal audio equaliser.", { { "0", NULL }, { "5", NULL }, { "10", NULL }, { "15", NULL }, { "20", NULL }, { "25", NULL }, { "30", NULL }, { "35", NULL }, { "40", NULL }, { "45", NULL }, { "50", NULL }, { "55", NULL }, { "60", NULL }, { "65", NULL }, { "70", NULL }, { "75", NULL }, { "80", NULL }, { "85", NULL }, { "90", NULL }, { "95", NULL }, { "100", NULL }, { NULL, NULL }, }, "100" }, #endif { "genesis_plus_gx_wide_blargg_ntsc_filter", "Blargg NTSC Filter", "Apply a video filter to mimic various NTSC TV signals.", { { "disabled", NULL }, { "monochrome", "Monochrome" }, { "composite", "Composite" }, { "svideo", "S-Video" }, { "rgb", "RGB" }, { NULL, NULL }, }, "disabled" }, { "genesis_plus_gx_wide_lcd_filter", "LCD Ghosting Filter", "Apply an image 'ghosting' filter to mimic the display characteristics of the Game Gear and 'Genesis Nomad' LCD panels.", { { "disabled", NULL }, { "enabled", NULL }, { NULL, NULL }, }, "disabled" }, { "genesis_plus_gx_wide_overscan", "Borders", "Enable this to display the overscan regions at the top/bottom and/or left/right of the screen. These would normally be hidden by the bezel around the edge of a standard-definition television.", { { "disabled", NULL }, { "top/bottom", "Top/Bottom" }, { "left/right", "Left/Right" }, { "full", "Full" }, { NULL, NULL }, }, "disabled" }, { "genesis_plus_gx_wide_gg_extra", "Game Gear Extended Screen", "Forces Game Gear titles to run in 'SMS' mode, with an increased resolution of 256x192. May show additional content, but typically displays a border of corrupt/unwanted image data.", { { "disabled", NULL }, { "enabled", NULL }, { NULL, NULL }, }, "disabled" }, { "genesis_plus_gx_wide_left_border", "Hide Master System Left Border", "Cuts off 8 pixels from both the left and right side of the screen when running Master System games, thereby hiding the border seen on the left side of the screen", { { "disabled", NULL }, { "enabled", NULL }, { NULL, NULL }, }, "disabled" }, { "genesis_plus_gx_wide_aspect_ratio", "Core-Provided Aspect Ratio", "Choose the preferred content aspect ratio. This will only apply when RetroArch's aspect ratio is set to 'Core provided' in the Video settings.", { { "auto", "Auto" }, { "NTSC PAR", NULL }, { "PAL PAR", NULL }, }, "auto" }, { "genesis_plus_gx_wide_render", "Interlaced Mode 2 Output", "Interlaced Mode 2 allows the Genesis to output a double height (high resolution) 320x448 image by drawing alternate scanlines each frame (this is used by 'Sonic the Hedgehog 2' and 'Combat Cars' multiplayer modes). 'Double Field' mimics original hardware, producing a sharp image with flickering/interlacing artefacts. 'Single Field' apples a de-interlacing filter, which stabilises the image but causes mild blurring.", { { "single field", "Single Field" }, { "double field", "Double Field" }, { NULL, NULL }, }, "single field" }, { "genesis_plus_gx_wide_gun_cursor", "Show Light Gun Crosshair", "Display light gun crosshairs when using the 'MD Menacer', 'MD Justifiers' and 'MS Light Phaser' input device types.", { { "disabled", NULL }, { "enabled", NULL }, { NULL, NULL }, }, "disabled" }, { "genesis_plus_gx_wide_invert_mouse", "Invert Mouse Y-Axis", "Inverts the Y-axis of the 'MD Mouse' input device type.", { { "disabled", NULL }, { "enabled", NULL }, { NULL, NULL }, }, "disabled" }, #ifdef HAVE_OVERCLOCK { "genesis_plus_gx_wide_overclock", "CPU Speed", "Overclock the emulated CPU. Can reduce slowdown, but may cause glitches.", { { "100%", NULL }, { "125%", NULL }, { "150%", NULL }, { "175%", NULL }, { "200%", NULL }, { NULL, NULL }, }, "100%" }, #endif { "genesis_plus_gx_wide_no_sprite_limit", "Remove Per-Line Sprite Limit", "Removes the 8 (Master System) or 20 (Genesis) sprite-per-scanline hardware limit. This reduces flickering but can cause visual glitches, as some games exploit the hardware limit to generate special effects.", { { "disabled", NULL }, { "enabled", NULL }, { NULL, NULL }, }, "disabled" }, { "genesis_plus_gx_wide_widescreen_h40", "Force H40 mode to H50 for 16:9", "Forces Widescreen Mode. May cause visual glitches and require game-specific patches for the best results.", { { "disabled", NULL }, { "enabled", NULL }, { NULL, NULL }, }, "enabled" }, { "genesis_plus_gx_wide_vdp_fix_dma_boundary_bug", "Fix 128k DMA Boundary", "Fixes a VDP hardware issue with DMA requests crossing 128k boundaries. Recommended to leave disabled, unless specifically required.", { { "disabled", NULL }, { "enabled", NULL }, { NULL, NULL }, }, "disabled" }, { NULL, NULL, NULL, {{0}}, NULL }, }; /* ******************************** * Language Mapping ******************************** */ #ifndef HAVE_NO_LANGEXTRA struct retro_core_option_definition *option_defs_intl[RETRO_LANGUAGE_LAST] = { option_defs_us, /* RETRO_LANGUAGE_ENGLISH */ NULL, /* RETRO_LANGUAGE_JAPANESE */ NULL, /* RETRO_LANGUAGE_FRENCH */ NULL, /* RETRO_LANGUAGE_SPANISH */ NULL, /* RETRO_LANGUAGE_GERMAN */ NULL, /* RETRO_LANGUAGE_ITALIAN */ NULL, /* RETRO_LANGUAGE_DUTCH */ option_defs_pt_br, /* RETRO_LANGUAGE_PORTUGUESE_BRAZIL */ NULL, /* RETRO_LANGUAGE_PORTUGUESE_PORTUGAL */ NULL, /* RETRO_LANGUAGE_RUSSIAN */ NULL, /* RETRO_LANGUAGE_KOREAN */ NULL, /* RETRO_LANGUAGE_CHINESE_TRADITIONAL */ NULL, /* RETRO_LANGUAGE_CHINESE_SIMPLIFIED */ NULL, /* RETRO_LANGUAGE_ESPERANTO */ NULL, /* RETRO_LANGUAGE_POLISH */ NULL, /* RETRO_LANGUAGE_VIETNAMESE */ NULL, /* RETRO_LANGUAGE_ARABIC */ NULL, /* RETRO_LANGUAGE_GREEK */ option_defs_tr, /* RETRO_LANGUAGE_TURKISH */ }; #endif /* ******************************** * Functions ******************************** */ /* Handles configuration/setting of core options. * Should be called as early as possible - ideally inside * retro_set_environment(), and no later than retro_load_game() * > We place the function body in the header to avoid the * necessity of adding more .c files (i.e. want this to * be as painless as possible for core devs) */ INLINE void libretro_set_core_options(retro_environment_t environ_cb) { unsigned version = 0; if (!environ_cb) return; if (environ_cb(RETRO_ENVIRONMENT_GET_CORE_OPTIONS_VERSION, &version) && (version >= 1)) { #ifndef HAVE_NO_LANGEXTRA struct retro_core_options_intl core_options_intl; unsigned language = 0; core_options_intl.us = option_defs_us; core_options_intl.local = NULL; if (environ_cb(RETRO_ENVIRONMENT_GET_LANGUAGE, &language) && (language < RETRO_LANGUAGE_LAST) && (language != RETRO_LANGUAGE_ENGLISH)) core_options_intl.local = option_defs_intl[language]; environ_cb(RETRO_ENVIRONMENT_SET_CORE_OPTIONS_INTL, &core_options_intl); #else environ_cb(RETRO_ENVIRONMENT_SET_CORE_OPTIONS, &option_defs_us); #endif } else { size_t i; size_t num_options = 0; struct retro_variable *variables = NULL; char **values_buf = NULL; /* Determine number of options */ while (true) { if (option_defs_us[num_options].key) num_options++; else break; } /* Allocate arrays */ variables = (struct retro_variable *)calloc(num_options + 1, sizeof(struct retro_variable)); values_buf = (char **)calloc(num_options, sizeof(char *)); if (!variables || !values_buf) goto error; /* Copy parameters from option_defs_us array */ for (i = 0; i < num_options; i++) { const char *key = option_defs_us[i].key; const char *desc = option_defs_us[i].desc; const char *default_value = option_defs_us[i].default_value; struct retro_core_option_value *values = option_defs_us[i].values; size_t buf_len = 3; size_t default_index = 0; values_buf[i] = NULL; if (desc) { size_t num_values = 0; /* Determine number of values */ while (true) { if (values[num_values].value) { /* Check if this is the default value */ if (default_value) if (strcmp(values[num_values].value, default_value) == 0) default_index = num_values; buf_len += strlen(values[num_values].value); num_values++; } else break; } /* Build values string */ if (num_values > 0) { size_t j; buf_len += num_values - 1; buf_len += strlen(desc); values_buf[i] = (char *)calloc(buf_len, sizeof(char)); if (!values_buf[i]) goto error; strcpy(values_buf[i], desc); strcat(values_buf[i], "; "); /* Default value goes first */ strcat(values_buf[i], values[default_index].value); /* Add remaining values */ for (j = 0; j < num_values; j++) { if (j != default_index) { strcat(values_buf[i], "|"); strcat(values_buf[i], values[j].value); } } } } variables[i].key = key; variables[i].value = values_buf[i]; } /* Set variables */ environ_cb(RETRO_ENVIRONMENT_SET_VARIABLES, variables); error: /* Clean up */ if (values_buf) { for (i = 0; i < num_options; i++) { if (values_buf[i]) { free(values_buf[i]); values_buf[i] = NULL; } } free(values_buf); values_buf = NULL; } if (variables) { free(variables); variables = NULL; } } } #ifdef __cplusplus } #endif #endif
31.667643
427
0.52818
[ "model" ]
b12119f2cc0a8f2c4994f572397c2451a0072be9
4,590
h
C
chromium/media/cast/sender/size_adaptable_video_encoder_base.h
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
27
2016-04-27T01:02:03.000Z
2021-12-13T08:53:19.000Z
chromium/media/cast/sender/size_adaptable_video_encoder_base.h
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
2
2017-03-09T09:00:50.000Z
2017-09-21T15:48:20.000Z
chromium/media/cast/sender/size_adaptable_video_encoder_base.h
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
17
2016-04-27T02:06:39.000Z
2019-12-18T08:07:00.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_CAST_SENDER_SIZE_ADAPTABLE_VIDEO_ENCODER_BASE_H_ #define MEDIA_CAST_SENDER_SIZE_ADAPTABLE_VIDEO_ENCODER_BASE_H_ #include <stdint.h> #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "media/cast/cast_config.h" #include "media/cast/cast_environment.h" #include "media/cast/constants.h" #include "media/cast/sender/video_encoder.h" #include "ui/gfx/geometry/size.h" namespace media { namespace cast { // Creates and owns a VideoEncoder instance. The owned instance is an // implementation that does not support changing frame sizes, and so // SizeAdaptableVideoEncoderBase acts as a proxy to automatically detect when // the owned instance should be replaced with one that can handle the new frame // size. class SizeAdaptableVideoEncoderBase : public VideoEncoder { public: SizeAdaptableVideoEncoderBase( const scoped_refptr<CastEnvironment>& cast_environment, const VideoSenderConfig& video_config, const StatusChangeCallback& status_change_cb); ~SizeAdaptableVideoEncoderBase() override; // VideoEncoder implementation. bool EncodeVideoFrame( const scoped_refptr<media::VideoFrame>& video_frame, const base::TimeTicks& reference_time, const FrameEncodedCallback& frame_encoded_callback) final; void SetBitRate(int new_bit_rate) final; void GenerateKeyFrame() final; scoped_ptr<VideoFrameFactory> CreateVideoFrameFactory() final; void EmitFrames() final; protected: // Accessors for subclasses. CastEnvironment* cast_environment() const { return cast_environment_.get(); } const VideoSenderConfig& video_config() const { return video_config_; } const gfx::Size& frame_size() const { return frame_size_; } uint32_t last_frame_id() const { return last_frame_id_; } // Returns a callback that calls OnEncoderStatusChange(). The callback is // canceled by invalidating its bound weak pointer just before a replacement // encoder is instantiated. In this scheme, OnEncoderStatusChange() can only // be called by the most-recent encoder. StatusChangeCallback CreateEncoderStatusChangeCallback(); // Overridden by subclasses to create a new encoder instance that handles // frames of the size specified by |frame_size()|. virtual scoped_ptr<VideoEncoder> CreateEncoder() = 0; // Overridden by subclasses to perform additional steps when // |replacement_encoder| becomes the active encoder. virtual void OnEncoderReplaced(VideoEncoder* replacement_encoder); // Overridden by subclasses to perform additional steps before/after the // current encoder is destroyed. virtual void DestroyEncoder(); private: // Create and initialize a replacement video encoder, if this not already // in-progress. The replacement will call back to OnEncoderStatusChange() // with success/fail status. void TrySpawningReplacementEncoder(const gfx::Size& size_needed); // Called when a status change is received from an encoder. void OnEncoderStatusChange(OperationalStatus status); // Called by the |encoder_| with the next EncodedFrame. void OnEncodedVideoFrame(const FrameEncodedCallback& frame_encoded_callback, scoped_ptr<SenderEncodedFrame> encoded_frame); const scoped_refptr<CastEnvironment> cast_environment_; // This is not const since |video_config_.starting_bitrate| is modified by // SetBitRate(), for when a replacement encoder is spawned. VideoSenderConfig video_config_; // Run whenever the underlying encoder reports a status change. const StatusChangeCallback status_change_cb_; // The underlying platform video encoder and the frame size it expects. scoped_ptr<VideoEncoder> encoder_; gfx::Size frame_size_; // The number of frames in |encoder_|'s pipeline. If this is set to // kEncoderIsInitializing, |encoder_| is not yet ready to accept frames. enum { kEncoderIsInitializing = -1 }; int frames_in_encoder_; // The ID of the last frame that was emitted from |encoder_|. uint32_t last_frame_id_; // NOTE: Weak pointers must be invalidated before all other member variables. base::WeakPtrFactory<SizeAdaptableVideoEncoderBase> weak_factory_; DISALLOW_COPY_AND_ASSIGN(SizeAdaptableVideoEncoderBase); }; } // namespace cast } // namespace media #endif // MEDIA_CAST_SENDER_SIZE_ADAPTABLE_VIDEO_ENCODER_BASE_H_
37.622951
79
0.774292
[ "geometry" ]
b126422406412bc215614795eb31cd647a1ecae1
7,094
h
C
Win32.Carberp/all source/BJWJ/include/accessibility/AccessibleEditableText.h
010001111/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
2
2021-02-04T06:47:45.000Z
2021-07-28T10:02:10.000Z
Win32.Carberp/all source/BlackJoeWhiteJoe/include/accessibility/AccessibleEditableText.h
010001111/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
null
null
null
Win32.Carberp/all source/BlackJoeWhiteJoe/include/accessibility/AccessibleEditableText.h
010001111/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
null
null
null
/* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 7.00.0500 */ /* at Thu Sep 03 13:55:18 2009 */ /* Compiler settings for e:/builds/moz2_slave/mozilla-1.9.1-win32-xulrunner/build/other-licenses/ia2/AccessibleEditableText.idl: Oicf, W1, Zp8, env=Win32 (32b run) protocol : dce , ms_ext, app_config, c_ext, robust error checks: allocation ref bounds_check enum stub_data VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ //@@MIDL_FILE_HEADING( ) #pragma warning( disable: 4049 ) /* more than 64k source lines */ /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 475 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of <rpcndr.h> #endif // __RPCNDR_H_VERSION__ #ifndef COM_NO_WINDOWS_H #include "windows.h" #include "ole2.h" #endif /*COM_NO_WINDOWS_H*/ #ifndef __AccessibleEditableText_h__ #define __AccessibleEditableText_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef __IAccessibleEditableText_FWD_DEFINED__ #define __IAccessibleEditableText_FWD_DEFINED__ typedef interface IAccessibleEditableText IAccessibleEditableText; #endif /* __IAccessibleEditableText_FWD_DEFINED__ */ /* header files for imported files */ #include "objidl.h" #include "oaidl.h" #include "oleacc.h" #ifdef __cplusplus extern "C"{ #endif #ifndef __IAccessibleEditableText_INTERFACE_DEFINED__ #define __IAccessibleEditableText_INTERFACE_DEFINED__ /* interface IAccessibleEditableText */ /* [uuid][object] */ EXTERN_C const IID IID_IAccessibleEditableText; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("A59AA09A-7011-4b65-939D-32B1FB5547E3") IAccessibleEditableText : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE copyText( /* [in] */ long startOffset, /* [in] */ long endOffset) = 0; virtual HRESULT STDMETHODCALLTYPE deleteText( /* [in] */ long startOffset, /* [in] */ long endOffset) = 0; virtual HRESULT STDMETHODCALLTYPE insertText( /* [in] */ long offset, /* [in] */ BSTR *text) = 0; virtual HRESULT STDMETHODCALLTYPE cutText( /* [in] */ long startOffset, /* [in] */ long endOffset) = 0; virtual HRESULT STDMETHODCALLTYPE pasteText( /* [in] */ long offset) = 0; virtual HRESULT STDMETHODCALLTYPE replaceText( /* [in] */ long startOffset, /* [in] */ long endOffset, /* [in] */ BSTR *text) = 0; virtual HRESULT STDMETHODCALLTYPE setAttributes( /* [in] */ long startOffset, /* [in] */ long endOffset, /* [in] */ BSTR *attributes) = 0; }; #else /* C style interface */ typedef struct IAccessibleEditableTextVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IAccessibleEditableText * This, /* [in] */ REFIID riid, /* [iid_is][out] */ __RPC__deref_out void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IAccessibleEditableText * This); ULONG ( STDMETHODCALLTYPE *Release )( IAccessibleEditableText * This); HRESULT ( STDMETHODCALLTYPE *copyText )( IAccessibleEditableText * This, /* [in] */ long startOffset, /* [in] */ long endOffset); HRESULT ( STDMETHODCALLTYPE *deleteText )( IAccessibleEditableText * This, /* [in] */ long startOffset, /* [in] */ long endOffset); HRESULT ( STDMETHODCALLTYPE *insertText )( IAccessibleEditableText * This, /* [in] */ long offset, /* [in] */ BSTR *text); HRESULT ( STDMETHODCALLTYPE *cutText )( IAccessibleEditableText * This, /* [in] */ long startOffset, /* [in] */ long endOffset); HRESULT ( STDMETHODCALLTYPE *pasteText )( IAccessibleEditableText * This, /* [in] */ long offset); HRESULT ( STDMETHODCALLTYPE *replaceText )( IAccessibleEditableText * This, /* [in] */ long startOffset, /* [in] */ long endOffset, /* [in] */ BSTR *text); HRESULT ( STDMETHODCALLTYPE *setAttributes )( IAccessibleEditableText * This, /* [in] */ long startOffset, /* [in] */ long endOffset, /* [in] */ BSTR *attributes); END_INTERFACE } IAccessibleEditableTextVtbl; interface IAccessibleEditableText { CONST_VTBL struct IAccessibleEditableTextVtbl *lpVtbl; }; #ifdef COBJMACROS #define IAccessibleEditableText_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IAccessibleEditableText_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IAccessibleEditableText_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IAccessibleEditableText_copyText(This,startOffset,endOffset) \ ( (This)->lpVtbl -> copyText(This,startOffset,endOffset) ) #define IAccessibleEditableText_deleteText(This,startOffset,endOffset) \ ( (This)->lpVtbl -> deleteText(This,startOffset,endOffset) ) #define IAccessibleEditableText_insertText(This,offset,text) \ ( (This)->lpVtbl -> insertText(This,offset,text) ) #define IAccessibleEditableText_cutText(This,startOffset,endOffset) \ ( (This)->lpVtbl -> cutText(This,startOffset,endOffset) ) #define IAccessibleEditableText_pasteText(This,offset) \ ( (This)->lpVtbl -> pasteText(This,offset) ) #define IAccessibleEditableText_replaceText(This,startOffset,endOffset,text) \ ( (This)->lpVtbl -> replaceText(This,startOffset,endOffset,text) ) #define IAccessibleEditableText_setAttributes(This,startOffset,endOffset,attributes) \ ( (This)->lpVtbl -> setAttributes(This,startOffset,endOffset,attributes) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IAccessibleEditableText_INTERFACE_DEFINED__ */ /* Additional Prototypes for ALL interfaces */ unsigned long __RPC_USER BSTR_UserSize( unsigned long *, unsigned long , BSTR * ); unsigned char * __RPC_USER BSTR_UserMarshal( unsigned long *, unsigned char *, BSTR * ); unsigned char * __RPC_USER BSTR_UserUnmarshal(unsigned long *, unsigned char *, BSTR * ); void __RPC_USER BSTR_UserFree( unsigned long *, BSTR * ); /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif
30.187234
128
0.638145
[ "object" ]
b12b60b37e9aea3e73c6c9b44799f015a2e8610b
13,053
h
C
GameSparks/include/GameSparks/GS.h
phillipmacon/gamesparks-cpp-marmalade
628c3a6696bd871e18a8277a96259cf604d22116
[ "Apache-2.0" ]
null
null
null
GameSparks/include/GameSparks/GS.h
phillipmacon/gamesparks-cpp-marmalade
628c3a6696bd871e18a8277a96259cf604d22116
[ "Apache-2.0" ]
null
null
null
GameSparks/include/GameSparks/GS.h
phillipmacon/gamesparks-cpp-marmalade
628c3a6696bd871e18a8277a96259cf604d22116
[ "Apache-2.0" ]
1
2021-12-24T03:19:09.000Z
2021-12-24T03:19:09.000Z
// Copyright 2015 GameSparks Ltd 2015, Inc. All Rights Reserved. #ifndef GS_h__ #define GS_h__ #pragma once #include "IGSPlatform.h" #include "GSRequest.h" #include "GSConnection.h" #include <GameSparks/GSLeakDetector.h> #include <GameSparks/GSLinking.h> #include <cassert> #include "./gsstl.h" namespace easywsclient { struct WSError; } //! root GameSparks namespace namespace GameSparks { //! This namespace contains the hand written gist of the SDK namespace Core { class GSConnection; class GSObject; class GSRequest; /*! The Core GS-API Object. * You can either create an instance of this class locally or create it where ever convenient for you. * Please note, that it is discouraged to have multiple instances of this class at the same time. */ class GS_API GS // this naming should be discussed, it was chosen because we need the static object with the name "GS" { public: #if defined(GS_USE_STD_FUNCTION) typedef gsstl::function<void(GS&, bool)> t_AvailableCallback; #else typedef void(*t_AvailableCallback)(GS&, bool); #endif /* GS_USE_STD_FUNCTION */ /// Callback which is triggered whenever the service becomes available or the connection to the service is lost. t_AvailableCallback GameSparksAvailable; #if defined(GS_USE_STD_FUNCTION) typedef gsstl::function<void(GS&,const gsstl::string& userId)> t_AuthenticatedCallback; #else typedef void(*t_AuthenticatedCallback)(GS&, const gsstl::string& userId); #endif /* GS_USE_STD_FUNCTION */ /// Callback which is triggered whenever a new user is authenticated t_AuthenticatedCallback GameSparksAuthenticated; GS(); ~GS(); bool GetDurableQueueRunning(); void SetDurableQueueRunning(bool running); typedef gsstl::list<GSRequest> t_PersistentQueue; /*! This gives you direct access to the items currently in the durable queue. Note, that this is slightly different to the .NET SDK: The .NET SDK is returning a list of references to requests. The C++ SDK is returning an internal reference. */ t_PersistentQueue& GetDurableQueueEntries(); bool RemoveDurableQueueEntry(const GSRequest& request); size_t GetRequestQueueCount(); #if defined(GS_USE_STD_FUNCTION) typedef gsstl::function<void(GS&)> t_OnPersistentQueueLoadedCallback; #else typedef void(*t_OnPersistentQueueLoadedCallback)(GS&); #endif /* GS_USE_STD_FUNCTION */ /*! This callback will be called each time the persistent queue is deserialized. It can be used to re-attach the callbacks to the requests in the persistent queue via request.SetCallback. This is necessary because callbacks cannot be serialized. Be carfull when modifying the passed queue ! */ t_OnPersistentQueueLoadedCallback OnPersistentQueueLoadedCallback; /// Initialize this GS instance. This has to be called before calling any other member functions. void Initialise(IGSPlatform* gSPlatform); void printConnections(); /// shutdown this GS instance. You cannot call any other member function after this call. void ShutDown(); /// Stops all connections. void Disconnect(); /// Reconnect to the GameSparks service. void Reconnect(); /// Stops all connections, resets the authentication token and establishes a new connection to the service. void Reset(); /// True if a connection to the service is available for use. bool GetAvailable() const { return m_Ready; } /// True if a connection is available and the user is authenticated. bool GetAuthenticated() const; /// <summary> /// Send the given request durable. /// Durable requests are persisted automatically. /// If it cannot be send right now the sdk will try to send it later. /// </summary> void SendDurable(GSRequest& request); /// Send the given request. void Send(GSRequest& request); // True if a connection to the service is available for use. // bool GetGameSparksAvailable(); /// Update this GS-instance. This has to be called as often as possible /// @param deltaTimeInSeconds the time since the last call to Update() in seconds void Update(Seconds deltaTimeInSeconds); /*! Registers MessageListener via GS.SetMessageListener(OnAchievementEarnedMessage) if you pass null, the MessageListener is unregistered. Note: the signature could also be written as: void SetMessageListener(const typename MessageType::t_ListenerFunction& listener) but writing out the type (e.g. not using a dependent type name) enabled the compiler to deduce MessageType. So the user can write: GS.SetMessageListener(OnAchievementEarnedMessage) instead of GS.SetMessageListener<GameSparks::Api::Messages::AchievementEarnedMessage>(OnAchievementEarnedMessage); This of cause only works, if the passed MessageListener has the correct Signature: void OnAchievementEarnedMessage(GameSparks::Core::GS& gsInstance, const MessageType& message) @tparam MessageType the type of the message you want to listen for */ template <typename MessageType> #if defined(GS_USE_STD_FUNCTION) void SetMessageListener(const gsstl::function<void(class GS&, const MessageType&)>& listener) #else void SetMessageListener( void(*listener)(class GS&, const MessageType&) ) #endif /* GS_USE_STD_FUNCTION */ { const char* messageTypeName = MessageType::GetTypeName(); t_MessageHandlerMap::iterator pos = m_MessageHandlers.find(messageTypeName); if (pos != m_MessageHandlers.end()) { delete pos->second; m_MessageHandlers.erase(pos); } if (listener) { m_MessageHandlers[ MessageType::GetTypeName() ] = new MessageListener<MessageType>(listener); } } /// returns the Device-Id provided by IGSPlatform instance this GS-instance was initialized with. gsstl::string GetDeviceId() const { // you have to call Initialize with a non-null platform instance first assert(m_GSPlatform); return m_GSPlatform->GetDeviceId(); } /// returns the Device-OS provided by IGSPlatform instance this GS-instance was initialized with. gsstl::string GetDeviceOS() const { // you have to call Initialize with a non-null platform instance first assert(m_GSPlatform); return m_GSPlatform->GetDeviceOS(); } /// change user-data to *to* for all requests that currently have user-data *from* /// If the request was already delivered, but the response is outstanding, the callbacks /// wont be called. This is usefully if the object userData is pointing to gets destroyed void ChangeUserDataForRequests(const void *from, void* to); private: friend class GSConnection; void OnWebSocketClientError(const easywsclient::WSError& errorMessage, GSConnection* connection); void OnMessageReceived(const gsstl::string& message, GSConnection& connection); gsstl::string GetServiceUrl() const { return m_ServiceUrl; } void SetAvailability(bool available); Seconds GetRequestTimeoutSeconds(); void DebugLog(const gsstl::string& message); void NetworkChange(bool available); void UpdateConnections(Seconds deltaTimeInSeconds); void Stop(bool termiante); void NewConnection(); void Handshake(GSObject& response, GSConnection& connection); void SendHandshake(GSObject& response, GSConnection& connection); gsstl::string GetUniqueRequestId(bool durable=false); void ConnectIfRequired(); void ProcessSendQueue(Seconds deltaTimeInSeconds); void CancelRequest(GSRequest& request); void CancelRequest(GSRequest& request, GSConnection* connection); void ProcessQueues(Seconds deltaTimeInSeconds); void TrimOldConnections(); void ProcessReceivedResponse(const GSObject& response, GSConnection* connection); void ProcessReceivedItem(const GSObject& response, GSConnection* connection); void ProcessPendingQueue(Seconds deltaTimeInSeconds); void InitialisePersistentQueue(); void ProcessPersistantQueue(Seconds deltaTimeInSeconds); void WritePersistentQueue(); void SetUserId(const gsstl::string& userId); gsstl::string buildServiceUrl(const IGSPlatform* platform); gsstl::string SerializeRequestQueue(const t_PersistentQueue& q); t_PersistentQueue DeserializeRequestQueue(const gsstl::string& s); IGSPlatform* m_GSPlatform; typedef gsstl::vector<GSConnection*> t_ConnectionContainer; t_ConnectionContainer m_Connections; gsstl::string m_ServiceUrl; typedef gsstl::list<GSRequest> t_SendQueue; t_SendQueue m_SendQueue; t_PersistentQueue m_PersistentQueue; long m_RequestCounter; // BS: we might want to change this to a state enum. they appear to be mutually exclusive. bool m_Ready; bool m_Paused; bool m_Initialized; bool m_durableQueuePaused; // internal value bool m_durableQueueRunning; // user controlled value Seconds m_nextReconnectSeconds; gsstl::string m_SessionId; /* MessageListeners */ // base class - provides the interface struct MessageListenerBase { virtual void CallMessageListener(GS& gsInstance, const GSData& message) const = 0; virtual ~MessageListenerBase(){} private: GS_LEAK_DETECTOR(MessageListenerBase) }; // specialisation for a concrete MessageType template <typename MessageType> struct MessageListener : public MessageListenerBase { #if defined(GS_USE_STD_FUNCTION) typedef gsstl::function<void(class GS&, const MessageType&)> t_ListenerFunction; #else typedef void(*t_ListenerFunction)(class GS&, const MessageType&); #endif /* GS_USE_STD_FUNCTION */ MessageListener(const t_ListenerFunction& listener) :m_Listener(listener) {} virtual void CallMessageListener(GS& gsInstance, const GSData& data) const { MessageType message(data); // convert jelly bean GSData to concrete GSMessage m_Listener(gsInstance, message); // call the listener } t_ListenerFunction m_Listener; GS_LEAK_DETECTOR(MessageListener) }; typedef gsstl::map<gsstl::string, MessageListenerBase*> t_MessageHandlerMap; t_MessageHandlerMap m_MessageHandlers; private: GS_LEAK_DETECTOR(GS) }; // GS_ is deprecated and will be removed in future versions. Use GS instead typedef GS GS_DEPRECATED(GS_); } /* namespace Core */ /// \example sample01Connect.cpp This is an example of how to use the GS class. /// \example sample02ConnectStatic.cpp This is an example of how to use GameSparks via a global GS-objects. /// \example sample03Authentication.cpp This is an example of how to authenticate a user. /// \example sample05Challangerequest.cpp This is an example on how to use CreateChallengeRequest. /// \example sample04Listachievements.cpp This is an example of how to list some achievements. /// \example sample06Stresstest.cpp This is more a test than an example. It shows, that the teardown and assignment works cleanly. // this block is here for doxygen //! This namespace contains the auto-generated classes related to the built-in GameSparks API. //! For more information on the topic visit https://api.gamesparks.net/ namespace Api { //! built-in Messages. namespace Messages {} //! built-in Requests. namespace Requests {} //! built-in Responses. namespace Responses {} //! Types used commonly by the built-in Requests, Responses and Messages namespace Types {} } #if defined(DOXYGEN) /// @defgroup CompileOptions Compile Options /// preprocessor defines that control features of the library #endif } #endif // GS_h__
39.080838
131
0.659006
[ "object", "vector" ]
b12d671ba340df685b1df100e866e2d82a8a5bee
14,026
c
C
bench/scotch/src/libscotch/graph_io_chac.c
jiverson002/bdmpi
11fc719f82a6851644fa21c6b12b0adec84feaf9
[ "Apache-2.0" ]
2
2020-11-25T13:10:11.000Z
2021-03-15T20:26:35.000Z
bench/scotch/src/libscotch/graph_io_chac.c
jiverson002/bdmpi
11fc719f82a6851644fa21c6b12b0adec84feaf9
[ "Apache-2.0" ]
null
null
null
bench/scotch/src/libscotch/graph_io_chac.c
jiverson002/bdmpi
11fc719f82a6851644fa21c6b12b0adec84feaf9
[ "Apache-2.0" ]
1
2018-09-30T19:04:38.000Z
2018-09-30T19:04:38.000Z
/* Copyright 2004,2007,2008,2010,2013 IPB, Universite de Bordeaux, INRIA & CNRS ** ** This file is part of the Scotch software package for static mapping, ** graph partitioning and sparse matrix ordering. ** ** This software is governed by the CeCILL-C license under French law ** and abiding by the rules of distribution of free software. You can ** use, modify and/or redistribute the software under the terms of the ** CeCILL-C license as circulated by CEA, CNRS and INRIA at the following ** URL: "http://www.cecill.info". ** ** As a counterpart to the access to the source code and rights to copy, ** modify and redistribute granted by the license, users are provided ** only with a limited warranty and the software's author, the holder of ** the economic rights, and the successive licensors have only limited ** liability. ** ** In this respect, the user's attention is drawn to the risks associated ** with loading, using, modifying and/or developing or reproducing the ** software by the user in light of its specific status of free software, ** that may mean that it is complicated to manipulate, and that also ** therefore means that it is reserved for developers and experienced ** professionals having in-depth computer knowledge. Users are therefore ** encouraged to load and test the software's suitability as regards ** their requirements in conditions enabling the security of their ** systems and/or data to be ensured and, more generally, to use and ** operate it in the same conditions as regards security. ** ** The fact that you are presently reading this means that you have had ** knowledge of the CeCILL-C license and that you accept its terms. */ /************************************************************/ /** **/ /** NAME : graph_io_chac.c **/ /** **/ /** AUTHORS : Francois PELLEGRINI **/ /** **/ /** FUNCTION : This module contains the I/O routines **/ /** for handling the Chaco graph format. **/ /** **/ /** DATES : # Version 3.2 : from : 06 nov 1997 **/ /** to 26 may 1998 **/ /** # Version 3.3 : from : 13 dec 1998 **/ /** to 24 dec 1998 **/ /** # Version 3.4 : from : 05 oct 1999 **/ /** to : 04 feb 2000 **/ /** # Version 4.0 : from : 18 dec 2001 **/ /** to 19 jan 2004 **/ /** # Version 5.0 : from : 04 feb 2007 **/ /** to 21 may 2008 **/ /** # Version 5.1 : from : 02 dec 2008 **/ /** to 11 aug 2010 **/ /** # Version 6.0 : from : 10 oct 2013 **/ /** to 10 oct 2013 **/ /** **/ /************************************************************/ /* ** The defines and includes. */ #define GRAPH_IO_CHAC #include "module.h" #include "common.h" #include "geom.h" #include "graph.h" /* This routine loads the geometrical graph ** in the Chaco graph format, and allocates ** the proper structures. ** - 0 : on success. ** - !0 : on error. */ int graphGeomLoadChac ( Graph * restrict const grafptr, /* Graph to load */ Geom * restrict const geomptr, /* Geometry to load */ FILE * const filesrcptr, /* Topological data */ FILE * const filegeoptr, /* No use */ const char * const dataptr) /* No use */ { char chalinetab[80]; /* Header line */ long chavertnbr; /* Number of vertices */ Gnum chavertnum; /* Number of vertex read */ long chaedgenbr; /* Number of edges */ long chaflagval; /* Flag on numeric form */ char chaflagstr[4]; /* Flag for optional data */ int chabuffcar; /* Buffer for line processing */ Gnum edgenum; Gnum edlosum; Gnum vertnum; Gnum velosum; Gnum vlblmax; Gnum degrmax; do { /* Skip comment lines */ chabuffcar = getc (filesrcptr); /* Read first character */ if (chabuffcar == '%') { /* If comment line */ fscanf (filesrcptr, "%*[^\n]"); /* Purge line */ getc (filesrcptr); /* Purge newline */ } } while (chabuffcar == '%'); ungetc (chabuffcar, filesrcptr); chaflagval = 0; if ((fscanf (filesrcptr, "%79[^\n]%*[^\n]", chalinetab) != 1) || /* Read graph header */ (sscanf (chalinetab, "%ld%ld%ld", &chavertnbr, &chaedgenbr, &chaflagval) < 2)) { errorPrint ("graphGeomLoadChac: bad input (1)"); return (1); } getc (filesrcptr); /* Purge newline (cannot be merged with above fscanf) */ chaflagstr[0] = /* Pre-set flag array */ chaflagstr[1] = chaflagstr[2] = chaflagstr[3] = '\0'; chaflagstr[0] = '0' + ((chaflagval / 100) % 10); /* Set the flags */ chaflagstr[1] = '0' + ((chaflagval / 10) % 10); chaflagstr[2] = '0' + ((chaflagval) % 10); grafptr->flagval = GRAPHFREETABS; grafptr->baseval = 1; /* Chaco graphs are based */ grafptr->vertnbr = chavertnbr; grafptr->vertnnd = chavertnbr + 1; grafptr->edgenbr = chaedgenbr * 2; /* We are counting arcs */ if (((grafptr->verttax = (Gnum *) memAlloc (grafptr->vertnnd * sizeof (Gnum))) == NULL) || ((grafptr->edgetax = (Gnum *) memAlloc (grafptr->edgenbr * sizeof (Gnum))) == NULL)) { errorPrint ("graphGeomLoadChac: out of memory (1)"); if (grafptr->verttax != NULL) memFree (grafptr->verttax); return (1); } grafptr->edgetax -= grafptr->baseval; grafptr->verttax -= grafptr->baseval; grafptr->vendtax = grafptr->verttax + 1; if (chaflagstr[0] != '0') { if ((grafptr->vlbltax = (Gnum *) memAlloc (chavertnbr * sizeof (Gnum))) == NULL) { errorPrint ("graphGeomLoadChac: out of memory (2)"); memFree (grafptr); return (1); } grafptr->vlbltax -= grafptr->baseval; } velosum = grafptr->vertnbr; /* Assume no vertex loads */ if (chaflagstr[1] != '0') { if ((grafptr->velotax = (Gnum *) memAlloc (chavertnbr * sizeof (Gnum))) == NULL) { errorPrint ("graphGeomLoadChac: out of memory (3)"); memFree (grafptr); return (1); } grafptr->velotax -= grafptr->baseval; velosum = 0; } edlosum = grafptr->edgenbr; if (chaflagstr[2] != '0') { if ((grafptr->edlotax = (Gnum *) memAlloc (grafptr->edgenbr * sizeof (Gnum))) == NULL) { errorPrint ("graphGeomLoadChac: out of memory (4)"); memFree (grafptr); return (1); } grafptr->edlotax -= grafptr->baseval; edlosum = 0; } for (vertnum = edgenum = grafptr->baseval, degrmax = vlblmax = 0; vertnum < grafptr->vertnnd; vertnum ++) { do { /* Skip comment lines */ chabuffcar = getc (filesrcptr); /* Read first character */ if (chabuffcar == '%') { /* If comment line */ fscanf (filesrcptr, "%*[^\n]"); /* Purge line */ getc (filesrcptr); /* Purge newline */ } } while (chabuffcar == '%'); ungetc (chabuffcar, filesrcptr); /* Put character back to filesrcptr */ if (grafptr->vlbltax != NULL) { if ((intLoad (filesrcptr, &grafptr->vlbltax[vertnum]) != 1) || (grafptr->vlbltax[vertnum] < 1) || (grafptr->vlbltax[vertnum] > chavertnbr)) { errorPrint ("graphGeomLoadChac: bad input (2)"); graphFree (grafptr); return (1); } if (grafptr->vlbltax[vertnum] > vlblmax) vlblmax = grafptr->vlbltax[vertnum]; } if (grafptr->velotax != NULL) { if ((intLoad (filesrcptr, &grafptr->velotax[vertnum]) != 1) || (grafptr->velotax[vertnum] < 1)) { errorPrint ("graphGeomLoadChac: bad input (3)"); graphFree (grafptr); return (1); } velosum += grafptr->velotax[vertnum]; } grafptr->verttax[vertnum] = edgenum; /* Set based edge array index */ while (1) { /* Read graph edges */ fscanf (filesrcptr, "%*[ \t\r]"); /* Skip white spaces except '\n' */ chabuffcar = getc (filesrcptr); /* Read next char */ if (chabuffcar == EOF) /* If end of file reached */ chabuffcar = '\n'; /* Indicate line as complete */ if (chabuffcar == '\n') /* Exit loop if line is complete */ break; ungetc (chabuffcar, filesrcptr); /* Else put character back to stream */ if ((intLoad (filesrcptr, &chavertnum) != 1) || (chavertnum < 1) || (chavertnum > chavertnbr) || ((grafptr->edlotax != NULL) && ((intLoad (filesrcptr, &grafptr->edlotax[edgenum]) != 1) || (edlosum += grafptr->edlotax[edgenum], grafptr->edlotax[edgenum] < 1)))) { errorPrint ("graphGeomLoadChac: bad input (4)"); graphFree (grafptr); return (1); } if (edgenum > (grafptr->edgenbr + grafptr-> baseval)) { /* Test edge array overflow */ errorPrint ("graphGeomLoadChac: bad input (5)"); graphFree (grafptr); return (1); } grafptr->edgetax[edgenum ++] = chavertnum; } if ((edgenum - grafptr->verttax[vertnum]) > degrmax) degrmax = edgenum - grafptr->verttax[vertnum]; } grafptr->verttax[vertnum] = edgenum; /* Set end of based vertex array */ grafptr->velosum = velosum; grafptr->edlosum = edlosum; grafptr->degrmax = degrmax; if (grafptr->vlbltax != NULL) { /* If graph has labels */ if (graphLoad2 (grafptr->baseval, grafptr->vertnnd, /* Un-label graph data */ grafptr->verttax, grafptr->vendtax, grafptr->edgetax, vlblmax, grafptr->vlbltax) != 0) { errorPrint ("graphGeomLoadChac: cannot relabel graph"); graphFree (grafptr); return (1); } } #ifdef SCOTCH_DEBUG_GRAPH2 if (graphCheck (grafptr) != 0) { /* Check graph consistency */ errorPrint ("graphGeomLoadChac: internal error"); graphFree (grafptr); return (1); } #endif /* SCOTCH_DEBUG_GRAPH2 */ return (0); } /* This routine saves the geometrical graph ** in the Chaco graph format. ** It returns: ** - 0 : on succes ** - !0 : on error. */ int graphGeomSaveChac ( const Graph * restrict const grafptr, /* Graph to save */ const Geom * restrict const geomptr, /* Geometry to save */ FILE * const filesrcptr, /* Topological data */ FILE * const filegeoptr, /* No use */ const char * const dataptr) /* No use */ { Gnum baseadj; /* Base adjustment */ Gnum vertnum; /* Current vertex */ Gnum edgenum; /* Current edge */ char * sepaptr; /* Separator string */ int o; baseadj = 1 - grafptr->baseval; /* Output base is always 1 */ o = (fprintf (filesrcptr, GNUMSTRING "\t" GNUMSTRING "\t%c%c%c\n", /* Write graph header */ (Gnum) grafptr->vertnbr, (Gnum) (grafptr->edgenbr / 2), ((grafptr->vlbltax != NULL) ? '1' : '0'), ((grafptr->velotax != NULL) ? '1' : '0'), ((grafptr->edlotax != NULL) ? '1' : '0')) < 0); for (vertnum = grafptr->baseval; (o == 0) && (vertnum < grafptr->vertnnd); vertnum ++) { sepaptr = ""; /* Start lines as is */ if (grafptr->vlbltax != NULL) { o |= (fprintf (filesrcptr, GNUMSTRING, (Gnum) (grafptr->vlbltax[vertnum] + baseadj)) < 0); sepaptr = "\t"; } if (grafptr->velotax != NULL) { o |= (fprintf (filesrcptr, "%s" GNUMSTRING, sepaptr, (Gnum) grafptr->velotax[vertnum]) < 0); sepaptr = "\t"; } for (edgenum = grafptr->verttax[vertnum]; (o == 0) && (edgenum < grafptr->vendtax[vertnum]); edgenum ++) { if (grafptr->vlbltax != NULL) o |= (fprintf (filesrcptr, "%s" GNUMSTRING, sepaptr, (Gnum) (grafptr->vlbltax[grafptr->edgetax[edgenum]] + baseadj)) < 0); else o |= (fprintf (filesrcptr, "%s" GNUMSTRING, sepaptr, (Gnum) (grafptr->edgetax[edgenum] + baseadj)) < 0); if (grafptr->edlotax != NULL) o |= (fprintf (filesrcptr, " " GNUMSTRING, (Gnum) grafptr->edlotax[edgenum]) < 0); sepaptr = "\t"; } o |= (fprintf (filesrcptr, "\n") < 0); } if (o != 0) errorPrint ("graphGeomSaveChac: bad output"); return (o); }
42.50303
106
0.495865
[ "geometry" ]
b12d6fa1bb858e387c6dacd627c424a271e215a0
10,240
h
C
OgreMain/include/OgreRibbonTrail.h
akien-mga/ogre
260191a573510a8e3f5eea395e6aa5cb3480243e
[ "MIT" ]
null
null
null
OgreMain/include/OgreRibbonTrail.h
akien-mga/ogre
260191a573510a8e3f5eea395e6aa5cb3480243e
[ "MIT" ]
null
null
null
OgreMain/include/OgreRibbonTrail.h
akien-mga/ogre
260191a573510a8e3f5eea395e6aa5cb3480243e
[ "MIT" ]
null
null
null
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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. ----------------------------------------------------------------------------- */ #ifndef __RibbonTrail_H__ #define __RibbonTrail_H__ #include "OgrePrerequisites.h" #include "OgreBillboardChain.h" #include "OgreNode.h" #include "OgreControllerManager.h" #include "OgreHeaderPrefix.h" namespace Ogre { /** \addtogroup Core * @{ */ /** \addtogroup Effects * @{ */ /** Subclass of BillboardChain which automatically leaves a trail behind one or more Node instances. @remarks An instance of this class will watch one or more Node instances, and automatically generate a trail behind them as they move. Because this class can monitor multiple modes, it generates its own geometry in world space and thus, even though it has to be attached to a SceneNode to be visible, changing the position of the scene node it is attached to makes no difference to the geometry rendered. @par The 'head' element grows smoothly in size until it reaches the required size, then a new element is added. If the segment is full, the tail element shrinks by the same proportion as the head grows before disappearing. @par Elements can be faded out on a time basis, either by altering their colour or altering their alpha. The width can also alter over time. @par 'v' texture coordinates are fixed at 0.0 if used, meaning that you can use a 1D texture to 'smear' a colour pattern along the ribbon if you wish. The 'u' coordinates are by default (0.0, 1.0), but you can alter this using setOtherTexCoordRange if you wish. */ class _OgreExport RibbonTrail : public BillboardChain, public Node::Listener { public: /** Constructor (don't use directly, use factory) @param name The name to give this object @param maxElements The maximum number of elements per chain @param numberOfChains The number of separate chain segments contained in this object, ie the maximum number of nodes that can have trails attached @param useTextureCoords If true, use texture coordinates from the chain elements @param useVertexColours If true, use vertex colours from the chain elements (must be true if you intend to use fading) */ RibbonTrail(const String& name, size_t maxElements = 20, size_t numberOfChains = 1, bool useTextureCoords = true, bool useVertexColours = true); /// destructor virtual ~RibbonTrail(); typedef std::vector<Node*> NodeList; typedef ConstVectorIterator<NodeList> NodeIterator; /** Add a node to be tracked. @param n The node that will be tracked. */ virtual void addNode(Node* n); /** Remove tracking on a given node. */ virtual void removeNode(const Node* n); /** Get an iterator over the nodes which are being tracked. */ virtual NodeIterator getNodeIterator(void) const; /** Get the chain index for a given Node being tracked. */ virtual size_t getChainIndexForNode(const Node* n); /** Set the length of the trail. @remarks This sets the length of the trail, in world units. It also sets how far apart each segment will be, ie length / max_elements. @param len The length of the trail in world units */ virtual void setTrailLength(Real len); /** Get the length of the trail. */ virtual Real getTrailLength(void) const { return mTrailLength; } /** @copydoc BillboardChain::setMaxChainElements */ void setMaxChainElements(size_t maxElements); /** @copydoc BillboardChain::setNumberOfChains */ void setNumberOfChains(size_t numChains); /** @copydoc BillboardChain::clearChain */ void clearChain(size_t chainIndex); /** Set the starting ribbon colour for a given segment. @param chainIndex The index of the chain @param col The initial colour @note Only used if this instance is using vertex colours. */ virtual void setInitialColour(size_t chainIndex, const ColourValue& col); /** Set the starting ribbon colour. @param chainIndex The index of the chain @param r,b,g,a The initial colour @note Only used if this instance is using vertex colours. */ virtual void setInitialColour(size_t chainIndex, Real r, Real g, Real b, Real a = 1.0); /** Get the starting ribbon colour. */ virtual const ColourValue& getInitialColour(size_t chainIndex) const; /** Enables / disables fading the trail using colour. @param chainIndex The index of the chain @param valuePerSecond The amount to subtract from colour each second */ virtual void setColourChange(size_t chainIndex, const ColourValue& valuePerSecond); /** Set the starting ribbon width in world units. @param chainIndex The index of the chain @param width The initial width of the ribbon */ virtual void setInitialWidth(size_t chainIndex, Real width); /** Get the starting ribbon width in world units. */ virtual Real getInitialWidth(size_t chainIndex) const; /** Set the change in ribbon width per second. @param chainIndex The index of the chain @param widthDeltaPerSecond The amount the width will reduce by per second */ virtual void setWidthChange(size_t chainIndex, Real widthDeltaPerSecond); /** Get the change in ribbon width per second. */ virtual Real getWidthChange(size_t chainIndex) const; /** Enables / disables fading the trail using colour. @param chainIndex The index of the chain @param r,g,b,a The amount to subtract from each colour channel per second */ virtual void setColourChange(size_t chainIndex, Real r, Real g, Real b, Real a); /** Get the per-second fading amount */ virtual const ColourValue& getColourChange(size_t chainIndex) const; /// @see Node::Listener::nodeUpdated void nodeUpdated(const Node* node); /// @see Node::Listener::nodeDestroyed void nodeDestroyed(const Node* node); /// Perform any fading / width delta required; internal method virtual void _timeUpdate(Real time); /** Overridden from MovableObject */ const String& getMovableType(void) const; protected: /// List of nodes being trailed NodeList mNodeList; /// Mapping of nodes to chain segments typedef std::vector<size_t> IndexVector; /// Ordered like mNodeList, contains chain index IndexVector mNodeToChainSegment; // chains not in use IndexVector mFreeChains; // fast lookup node->chain index // we use positional map too because that can be useful typedef std::map<const Node*, size_t> NodeToChainSegmentMap; NodeToChainSegmentMap mNodeToSegMap; /// Total length of trail in world units Real mTrailLength; /// length of each element Real mElemLength; /// Squared length of each element Real mSquaredElemLength; typedef std::vector<ColourValue> ColourValueList; typedef std::vector<Real> RealList; /// Initial colour of the ribbon ColourValueList mInitialColour; /// fade amount per second ColourValueList mDeltaColour; /// Initial width of the ribbon RealList mInitialWidth; /// Delta width of the ribbon RealList mDeltaWidth; /// controller used to hook up frame time to fader Controller<Real>* mFadeController; /// controller value for hooking up frame time to fader ControllerValueRealPtr mTimeControllerValue; /// Manage updates to the time controller virtual void manageController(void); /// Node has changed position, update virtual void updateTrail(size_t index, const Node* node); /// Reset the tracked chain to initial state virtual void resetTrail(size_t index, const Node* node); /// Reset all tracked chains to initial state virtual void resetAllTrails(void); }; /** Factory object for creating RibbonTrail instances */ class _OgreExport RibbonTrailFactory : public MovableObjectFactory { protected: MovableObject* createInstanceImpl( const String& name, const NameValuePairList* params); public: RibbonTrailFactory() {} ~RibbonTrailFactory() {} static String FACTORY_TYPE_NAME; const String& getType(void) const; void destroyInstance( MovableObject* obj); }; /** @} */ /** @} */ } #include "OgreHeaderSuffix.h" #endif
41.45749
96
0.664648
[ "geometry", "object", "vector" ]
b13a2798ef46ccbefb3e2209fa24e7e27b09756d
8,106
h
C
third_party/WebKit/Source/core/dom/ExecutionContext.h
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
third_party/WebKit/Source/core/dom/ExecutionContext.h
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/dom/ExecutionContext.h
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
/* * Copyright (C) 2008 Apple Inc. All Rights Reserved. * Copyright (C) 2012 Google Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef ExecutionContext_h #define ExecutionContext_h #include "core/CoreExport.h" #include "core/dom/ContextLifecycleNotifier.h" #include "core/dom/ContextLifecycleObserver.h" #include "core/dom/SecurityContext.h" #include "core/dom/SuspendableTask.h" #include "core/fetch/AccessControlStatus.h" #include "platform/Supplementable.h" #include "platform/heap/Handle.h" #include "platform/weborigin/KURL.h" #include "platform/weborigin/ReferrerPolicy.h" #include "wtf/Deque.h" #include "wtf/Noncopyable.h" #include <memory> namespace blink { class ActiveDOMObject; class ConsoleMessage; class DOMTimerCoordinator; class ErrorEvent; class EventQueue; class EventTarget; class ExecutionContextTask; class LocalDOMWindow; class PublicURLManager; class SecurityOrigin; class SourceLocation; class CORE_EXPORT ExecutionContext : public ContextLifecycleNotifier, public Supplementable<ExecutionContext> { WTF_MAKE_NONCOPYABLE(ExecutionContext); public: DECLARE_VIRTUAL_TRACE(); // Used to specify whether |isSecureContext| should walk the // ancestor tree to decide whether to restrict usage of a powerful // feature. enum SecureContextCheck { StandardSecureContextCheck, WebCryptoSecureContextCheck }; virtual bool isDocument() const { return false; } virtual bool isWorkerGlobalScope() const { return false; } virtual bool isWorkletGlobalScope() const { return false; } virtual bool isMainThreadWorkletGlobalScope() const { return false; } virtual bool isDedicatedWorkerGlobalScope() const { return false; } virtual bool isSharedWorkerGlobalScope() const { return false; } virtual bool isServiceWorkerGlobalScope() const { return false; } virtual bool isCompositorWorkerGlobalScope() const { return false; } virtual bool isPaintWorkletGlobalScope() const { return false; } virtual bool isJSExecutionForbidden() const { return false; } virtual bool isContextThread() const { return true; } SecurityOrigin* getSecurityOrigin(); ContentSecurityPolicy* contentSecurityPolicy(); const KURL& url() const; KURL completeURL(const String& url) const; virtual void disableEval(const String& errorMessage) = 0; virtual LocalDOMWindow* executingWindow() { return 0; } virtual String userAgent() const = 0; virtual void postTask(const WebTraceLocation&, std::unique_ptr<ExecutionContextTask>, const String& taskNameForInstrumentation = emptyString()) = 0; // Executes the task on context's thread asynchronously. // Gets the DOMTimerCoordinator which maintains the "active timer // list" of tasks created by setTimeout and setInterval. The // DOMTimerCoordinator is owned by the ExecutionContext and should // not be used after the ExecutionContext is destroyed. virtual DOMTimerCoordinator* timers() = 0; virtual void reportBlockedScriptExecutionToInspector(const String& directiveText) = 0; virtual SecurityContext& securityContext() = 0; KURL contextURL() const { return virtualURL(); } KURL contextCompleteURL(const String& url) const { return virtualCompleteURL(url); } bool shouldSanitizeScriptError(const String& sourceURL, AccessControlStatus); void reportException(ErrorEvent*, AccessControlStatus); virtual void addConsoleMessage(ConsoleMessage*) = 0; virtual void logExceptionToConsole(const String& errorMessage, std::unique_ptr<SourceLocation>) = 0; PublicURLManager& publicURLManager(); virtual void removeURLFromMemoryCache(const KURL&); void suspendActiveDOMObjects(); void resumeActiveDOMObjects(); void stopActiveDOMObjects(); void postSuspendableTask(std::unique_ptr<SuspendableTask>); void notifyContextDestroyed() override; virtual void suspendScheduledTasks(); virtual void resumeScheduledTasks(); virtual bool tasksNeedSuspension() { return false; } virtual void tasksWereSuspended() { } virtual void tasksWereResumed() { } bool activeDOMObjectsAreSuspended() const { return m_activeDOMObjectsAreSuspended; } bool activeDOMObjectsAreStopped() const { return m_activeDOMObjectsAreStopped; } // Called after the construction of an ActiveDOMObject to synchronize suspend state. void suspendActiveDOMObjectIfNeeded(ActiveDOMObject*); // Gets the next id in a circular sequence from 1 to 2^31-1. int circularSequentialID(); virtual EventTarget* errorEventTarget() = 0; virtual EventQueue* getEventQueue() const = 0; // Methods related to window interaction. It should be used to manage window // focusing and window creation permission for an ExecutionContext. void allowWindowInteraction(); void consumeWindowInteraction(); bool isWindowInteractionAllowed() const; // Decides whether this context is privileged, as described in // https://w3c.github.io/webappsec/specs/powerfulfeatures/#settings-privileged. virtual bool isSecureContext(String& errorMessage, const SecureContextCheck = StandardSecureContextCheck) const = 0; virtual bool isSecureContext(const SecureContextCheck = StandardSecureContextCheck) const; virtual String outgoingReferrer() const; // Parses a comma-separated list of referrer policy tokens, and sets // the context's referrer policy to the last one that is a valid // policy. Logs a message to the console if none of the policy // tokens are valid policies. void parseAndSetReferrerPolicy(const String& policies); void setReferrerPolicy(ReferrerPolicy); ReferrerPolicy getReferrerPolicy() const { return m_referrerPolicy; } protected: ExecutionContext(); virtual ~ExecutionContext(); virtual const KURL& virtualURL() const = 0; virtual KURL virtualCompleteURL(const String&) const = 0; private: bool dispatchErrorEvent(ErrorEvent*, AccessControlStatus); void runSuspendableTasks(); unsigned m_circularSequentialID; bool m_inDispatchErrorEvent; class PendingException; std::unique_ptr<Vector<std::unique_ptr<PendingException>>> m_pendingExceptions; bool m_activeDOMObjectsAreSuspended; bool m_activeDOMObjectsAreStopped; Member<PublicURLManager> m_publicURLManager; // Counter that keeps track of how many window interaction calls are allowed // for this ExecutionContext. Callers are expected to call // |allowWindowInteraction()| and |consumeWindowInteraction()| in order to // increment and decrement the counter. int m_windowInteractionTokens; Deque<std::unique_ptr<SuspendableTask>> m_suspendedTasks; bool m_isRunSuspendableTasksScheduled; ReferrerPolicy m_referrerPolicy; }; } // namespace blink #endif // ExecutionContext_h
41.147208
209
0.762645
[ "vector" ]
b13c723b6c9e3cdd283a331f6fbd0953a441f4dc
7,599
h
C
test/examples/code/3rdparty/assimp/detail/BlenderTessellator.h
maikebing/vpp
efa6c32f898e103d749764ce3a0b7dc29d6e9a51
[ "BSD-2-Clause" ]
null
null
null
test/examples/code/3rdparty/assimp/detail/BlenderTessellator.h
maikebing/vpp
efa6c32f898e103d749764ce3a0b7dc29d6e9a51
[ "BSD-2-Clause" ]
null
null
null
test/examples/code/3rdparty/assimp/detail/BlenderTessellator.h
maikebing/vpp
efa6c32f898e103d749764ce3a0b7dc29d6e9a51
[ "BSD-2-Clause" ]
null
null
null
/* Open Asset Import Library (assimp) ---------------------------------------------------------------------- Copyright (c) 2006-2016, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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. ---------------------------------------------------------------------- */ /** @file BlenderTessellator.h * @brief A simple tessellation wrapper */ #ifndef INCLUDED_AI_BLEND_TESSELLATOR_H #define INCLUDED_AI_BLEND_TESSELLATOR_H // Use these to toggle between GLU Tessellate or poly2tri // Note (acg) keep GLU Tesselate disabled by default - if it is turned on, // assimp needs to be linked against GLU, which is currently not yet // made configurable in CMake and potentially not wanted by most users // as it requires a Gl environment. #ifndef ASSIMP_BLEND_WITH_GLU_TESSELLATE # define ASSIMP_BLEND_WITH_GLU_TESSELLATE 0 #endif #ifndef ASSIMP_BLEND_WITH_POLY_2_TRI # define ASSIMP_BLEND_WITH_POLY_2_TRI 1 #endif #include "LogAux.h" #if ASSIMP_BLEND_WITH_GLU_TESSELLATE #include <GL/glu.h> namespace Assimp { class BlenderBMeshConverter; // TinyFormatter.h namespace Formatter { template < typename T,typename TR, typename A > class basic_formatter; typedef class basic_formatter< char, std::char_traits< char >, std::allocator< char > > format; } // BlenderScene.h namespace Blender { struct MLoop; struct MVert; struct VertexGL { GLdouble X; GLdouble Y; GLdouble Z; int index; int magic; VertexGL( GLdouble X, GLdouble Y, GLdouble Z, int index, int magic ): X( X ), Y( Y ), Z( Z ), index( index ), magic( magic ) { } }; struct DrawCallGL { GLenum drawMode; int baseVertex; int vertexCount; DrawCallGL( GLenum drawMode, int baseVertex ): drawMode( drawMode ), baseVertex( baseVertex ), vertexCount( 0 ) { } }; struct TessDataGL { std::vector< DrawCallGL > drawCalls; std::vector< VertexGL > vertices; }; } class BlenderTessellatorGL: public LogFunctions< BlenderTessellatorGL > { public: BlenderTessellatorGL( BlenderBMeshConverter& converter ); ~BlenderTessellatorGL( ); void Tessellate( const Blender::MLoop* polyLoop, int vertexCount, const std::vector< Blender::MVert >& vertices ); private: void AssertVertexCount( int vertexCount ); void GenerateLoopVerts( std::vector< Blender::VertexGL >& polyLoopGL, const Blender::MLoop* polyLoop, int vertexCount, const std::vector< Blender::MVert >& vertices ); void Tesssellate( std::vector< Blender::VertexGL >& polyLoopGL, Blender::TessDataGL& tessData ); void TriangulateDrawCalls( const Blender::TessDataGL& tessData ); void MakeFacesFromTris( const Blender::VertexGL* vertices, int vertexCount ); void MakeFacesFromTriStrip( const Blender::VertexGL* vertices, int vertexCount ); void MakeFacesFromTriFan( const Blender::VertexGL* vertices, int vertexCount ); static void TessellateBegin( GLenum drawModeGL, void* userData ); static void TessellateEnd( void* userData ); static void TessellateVertex( const void* vtxData, void* userData ); static void TessellateCombine( const GLdouble intersection[ 3 ], const GLdouble* [ 4 ], const GLfloat [ 4 ], GLdouble** out, void* userData ); static void TessellateEdgeFlag( GLboolean edgeFlag, void* userData ); static void TessellateError( GLenum errorCode, void* userData ); BlenderBMeshConverter* converter; }; } // end of namespace Assimp #endif // ASSIMP_BLEND_WITH_GLU_TESSELLATE #if ASSIMP_BLEND_WITH_POLY_2_TRI #include "../contrib/poly2tri/poly2tri.h" namespace Assimp { class BlenderBMeshConverter; // TinyFormatter.h namespace Formatter { template < typename T,typename TR, typename A > class basic_formatter; typedef class basic_formatter< char, std::char_traits< char >, std::allocator< char > > format; } // BlenderScene.h namespace Blender { struct MLoop; struct MVert; struct PointP2T { aiVector3D point3D; p2t::Point point2D; int magic; int index; }; struct PlaneP2T { aiVector3D centre; aiVector3D normal; }; } class BlenderTessellatorP2T: public LogFunctions< BlenderTessellatorP2T > { public: BlenderTessellatorP2T( BlenderBMeshConverter& converter ); ~BlenderTessellatorP2T( ); void Tessellate( const Blender::MLoop* polyLoop, int vertexCount, const std::vector< Blender::MVert >& vertices ); private: void AssertVertexCount( int vertexCount ); void Copy3DVertices( const Blender::MLoop* polyLoop, int vertexCount, const std::vector< Blender::MVert >& vertices, std::vector< Blender::PointP2T >& targetVertices ) const; aiMatrix4x4 GeneratePointTransformMatrix( const Blender::PlaneP2T& plane ) const; void TransformAndFlattenVectices( const aiMatrix4x4& transform, std::vector< Blender::PointP2T >& vertices ) const; void ReferencePoints( std::vector< Blender::PointP2T >& points, std::vector< p2t::Point* >& pointRefs ) const; inline Blender::PointP2T& GetActualPointStructure( p2t::Point& point ) const; void MakeFacesFromTriangles( std::vector< p2t::Triangle* >& triangles ) const; // Adapted from: http://missingbytes.blogspot.co.uk/2012/06/fitting-plane-to-point-cloud.html float FindLargestMatrixElem( const aiMatrix3x3& mtx ) const; aiMatrix3x3 ScaleMatrix( const aiMatrix3x3& mtx, float scale ) const; aiVector3D GetEigenVectorFromLargestEigenValue( const aiMatrix3x3& mtx ) const; Blender::PlaneP2T FindLLSQPlane( const std::vector< Blender::PointP2T >& points ) const; BlenderBMeshConverter* converter; }; } // end of namespace Assimp #endif // ASSIMP_BLEND_WITH_POLY_2_TRI #endif // INCLUDED_AI_BLEND_TESSELLATOR_H
36.88835
182
0.68759
[ "vector", "transform" ]
b141f0751526aa5343be33cbbf8560a36e857bd9
2,337
h
C
SPlisHSPlasH/PF/SimulationDataPF.h
esCharacter/SPlisHSPlasH
139e5fd0e4f0ace801f039ab065a2e5ee72f8f9f
[ "MIT" ]
2
2022-03-04T02:16:35.000Z
2022-03-30T02:05:48.000Z
SPlisHSPlasH/PF/SimulationDataPF.h
HuangChunying/SPlisHSPlasH
139e5fd0e4f0ace801f039ab065a2e5ee72f8f9f
[ "MIT" ]
null
null
null
SPlisHSPlasH/PF/SimulationDataPF.h
HuangChunying/SPlisHSPlasH
139e5fd0e4f0ace801f039ab065a2e5ee72f8f9f
[ "MIT" ]
1
2017-06-27T09:48:20.000Z
2017-06-27T09:48:20.000Z
#ifndef __SimulationDataPF_h__ #define __SimulationDataPF_h__ #include "SPlisHSPlasH/Common.h" #include "SPlisHSPlasH/FluidModel.h" #include <vector> namespace SPH { /** \brief Simulation data which is required by the method Projective Fluids introduced by Weiler, Koschier * and Bender \cite Weiler:2016. */ class SimulationDataPF { public: SimulationDataPF(); virtual ~SimulationDataPF(); protected: FluidModel *m_model; /** \brief particle position from last timestep */ std::vector<Vector3r> m_old_position; /** \brief number of neighbors that are fluid particles */ std::vector<unsigned int> m_num_fluid_neighbors; /** \brief variables for optimization */ std::vector<Real> m_x; /** \brief positions predicted from momentum */ std::vector<Vector3r> m_s; public: /** Initialize the arrays containing the particle data. */ virtual void init(FluidModel *model); /** Release the arrays containing the particle data. */ virtual void cleanup(); /** Reset the particle data. */ virtual void reset(); /** Important: First call m_model->performNeighborhoodSearchSort() * to call the z_sort of the neighborhood search. */ void performNeighborhoodSearchSort(); FORCE_INLINE const Vector3r getOldPosition(const unsigned int i) const { return m_old_position[i]; } FORCE_INLINE Vector3r& getOldPosition(const unsigned int i) { return m_old_position[i]; } FORCE_INLINE void setOldPosition(const unsigned int i, const Vector3r p) { m_old_position[i] = p; } FORCE_INLINE const unsigned int getNumFluidNeighbors(const unsigned int i) const { return m_num_fluid_neighbors[i]; } FORCE_INLINE unsigned int& getNumFluidNeighbors(const unsigned int i) { return m_num_fluid_neighbors[i]; } FORCE_INLINE void setNumFluidNeighbors(const unsigned int i, const unsigned int n) { m_num_fluid_neighbors[i] = n; } FORCE_INLINE const std::vector<Real>& getX() const { return m_x; } FORCE_INLINE std::vector<Real>& getX() { return m_x; } FORCE_INLINE const Vector3r& getS(const unsigned int i) const { return m_s[i]; } FORCE_INLINE Vector3r& getS(const unsigned int i) { return m_s[i]; } FORCE_INLINE void setS(const unsigned int i, const Vector3r & s) { m_s[i] = s; } }; } #endif
21.054054
108
0.710312
[ "vector", "model" ]
b143a5d7589aa83bc8e0dd2fc258e0e25fc139c0
7,031
h
C
src/Utils/FileUtils.h
den-rain/xptools
4c39da8d44a4a92e9efb2538844d433496b38f07
[ "X11", "MIT" ]
null
null
null
src/Utils/FileUtils.h
den-rain/xptools
4c39da8d44a4a92e9efb2538844d433496b38f07
[ "X11", "MIT" ]
null
null
null
src/Utils/FileUtils.h
den-rain/xptools
4c39da8d44a4a92e9efb2538844d433496b38f07
[ "X11", "MIT" ]
null
null
null
/* * Copyright (c) 2007, Laminar Research. * * 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. * */ #ifndef FILEUTILS_H #define FILEUTILS_H #include <sys/stat.h> class FILE_case_correct_path { public: FILE_case_correct_path(const char * in_path); ~FILE_case_correct_path(); operator const char * (void) const; private: char * path; FILE_case_correct_path(const FILE_case_correct_path& rhs); FILE_case_correct_path(); FILE_case_correct_path& operator=(const FILE_case_correct_path& rhs); }; /* Tests and corrects path as needed for file/folder case correctness on LIN it returns 1 if file exists using case-sensitive filename matching returns 1 if file exists, but path is not case-correct, aka file-insensitive match. In this case the path is corrected to case-match the actual file name. returns 0 is file can not be found at all with case-insensitive match On APL or IBM its does nothing and always returns 1, as these file systems are always case insensitive. */ int FILE_case_correct(char * buf); /* FILE API Overview Method Name | Purpose | Trailing Seperator? | Returns (Sucess, fail) exists | Does file exist? | N/A | True/false get_file_extension | Gets the chars from the last dot to the end | N/A | non-empty (".txt",".jpeg". No case change), empty string get_file_meta_data | Get file info like creation time and date | No | 0, -1 get_dir_name | Get directory part of filename | N/A | non-empty, empty string get_file_name | Get file name w/o directory, can use / or \ | N/A | non-empty, empty string get_file_name_wo_extensions | Get file name w/o directory or any extensions | N/A | non-empty, empty string delete_file | rm 1 file or folder | No | 0, last_error delete_dir_recursive | rm folder and subcontents | Yes | 0, last_error read_file_to_string | read a (non-binary) file to a string | N/A | 0, last_error rename_file | rename 1 file | N/A | 0, last_error compress_dir | zip compress folder, save zip to disk | No | 0, not zero (see zlib) get_directory | get dir's content's paths* | No | num files found?**, -1 or last_error get_directory_recursive | get dir and sub dir's files and folders | No | num files found?**, -1 or last_error make_dir | make directory, assumes parent folders exist | No | 0, last_error make_dir_exist | make directory, parent folders created on fly | No | 0, last_error date_cmpr | compares which of two files is newer | N/A | (1,0,-1), -2 *get_directory can do 1 to 4 things at the same time. It can implicitly tell you if the directory exists, how many files are contained in it, and, optionally, the relative paths of file or folders non-rescursively get_directory's return value is possibly bugged or is not being interpreted correctly. Use out_files->size() for a better count. -2016/05/16 get_directory_recursive's vectors of strings contain fully qualified names, unlike get_directory. /*/ //Returns true if the file (or directory) exists, returns false if it doesn't bool FILE_exists(const char * path); // returns file extension, NOT including the dot, always as lower case string FILE_get_file_extension(const string& path); int FILE_get_file_meta_data(const string& path, struct stat& meta_data); string FILE_get_file_name(const string& path); // returns directory name, i.e. path to file w/o filename, including the final directory separator string FILE_get_dir_name(const string& path); string FILE_get_file_name_wo_extensions(const string& path); // WARNING: these do not take trailing / for directories! // Returns 0 for success, else last_error int FILE_delete_file(const char * nuke_path, bool is_dir); // Path should end in a / // Returns 0 for success, else -1 or last_error int FILE_delete_dir_recursive(const string& path); //Reads the contents of a non-binary file into a string, does not close the file handle for you int FILE_read_file_to_string(FILE* file, string& content); int FILE_read_file_to_string(const string& path, string& content); // Returns 0 for success, else last_error int FILE_rename_file(const char * old_name, const char * new_name); // Create in_dir in its parent directory // Returns 0 for success, else last_error int FILE_make_dir(const char * in_dir); // Recursively create all dirs needed for in_dir to exist - handles trailing / ok. int FILE_make_dir_exist(const char * in_dir); // Get a directory listing. Returns number of files found, or -1 on error. Both arrays are optional. int FILE_get_directory(const string& path, vector<string> * out_files, vector<string> * out_dirs); // Gets a complete listing of every file and every folder under a given directory int FILE_get_directory_recursive(const string& path, vector<string>& out_files, vector<string>& out_dirs); int FILE_compress_dir(const string& src_path, const string& dst_path, const string& prefix); enum date_cmpr_result_t { dcr_firstIsNew = -1, dcr_secondIsNew = 1, dcr_same = 0, dcr_error = -2 }; /* Pass in a file path for the first and second file * Return 1: The second file is more updated that the first * Return 0: Both files have the same timestamp * Return -1: The first file is more current than the second or the second does not exist * Return -2: There's been an error */ date_cmpr_result_t FILE_date_cmpr(const char * first, const char * second); #endif
49.865248
157
0.684398
[ "vector" ]
b143bdedadf1830d874f16242563110d9bd0a4bf
176,206
h
C
mxflib/essence.h
Jamaika1/mxflib
7eefe6da1f76f7de4f2de48322311533369f8ba5
[ "Zlib" ]
1
2015-04-30T16:21:31.000Z
2015-04-30T16:21:31.000Z
mxflib/essence.h
Jamaika1/mxflib
7eefe6da1f76f7de4f2de48322311533369f8ba5
[ "Zlib" ]
null
null
null
mxflib/essence.h
Jamaika1/mxflib
7eefe6da1f76f7de4f2de48322311533369f8ba5
[ "Zlib" ]
1
2020-04-24T07:25:47.000Z
2020-04-24T07:25:47.000Z
/*! \file essence.h * \brief Definition of classes that handle essence reading and writing * * \version $Id$ * */ /* * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from * the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must * not claim that you wrote the original software. If you use this * software in a product, you must include an acknowledgment of the * authorship in the product documentation. * * 2. Altered source versions must be plainly marked as such, and must * not be misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source * distribution. */ #ifndef MXFLIB__ESSENCE_H #define MXFLIB__ESSENCE_H #include <map> #include <list> #include <vector> // Forward refs namespace mxflib { //! Smart pointer to a GCWriter class GCWriter; typedef SmartPtr<GCWriter> GCWriterPtr; class GCReader; typedef SmartPtr<GCReader> GCReaderPtr; // Type used to identify stream typedef int GCStreamID; // Forward declare class BodyStream; //! Smart pointer to a BodyStream typedef SmartPtr<BodyStream> BodyStreamPtr; //! Parent pointer to a BodyStream typedef ParentPtr<BodyStream> BodyStreamParent; //! List of smart pointers to BodyStreams typedef std::list<BodyStreamPtr> BodyStreamList; // Forward declare class EssenceSubParser; //! Smart pointer to an EssenceSubParser typedef SmartPtr<EssenceSubParser> EssenceSubParserPtr; //! PArent pointer to an EssenceSubParser typedef ParentPtr<EssenceSubParser> EssenceSubParserParent; } /* Global definitions */ namespace mxflib { //! Flag that allows faster clip wrapping using random access /*! Clip wrapped essence may contain huge essence KLVs and it is often not * practical (or even possible) to load the whole value into memory before * writing the K and L. This means that unless it is possible to use some * shortcut to calculate the size of the value before building it, the value * will need to be 'built' twice - once without storing the data to enable * its length to be calculated, then again to actually write it. * "FastClipWrap" mode gets around this by writing the length as (2^56)-1, * the largest 8-byte BER length, writing the value, then returning to update * the length field with the correct size. This huge length ensures that any * reader that is attempting to read the file while it is being written will * have a lower chance of barfing than if any "guestimate" value is written. * The reader will see the whole of the rest of the file as the essence. * This method requires random access to the medium holding the MXF file * being written, therefore is disable by default. */ extern bool AllowFastClipWrap; //! Enable or disable "FastClipWrap" mode inline void SetFastClipWrap(bool Flag) { AllowFastClipWrap = Flag; } //! Read the status of the "FastClipWrap" mode flag inline bool GetFastClipWrap(void) { return AllowFastClipWrap; } } namespace mxflib { //! Wrapping options for an EssenceSubParser or an EssenceSubStream class WrappingOption : public RefCount<WrappingOption> { public: //! Wrapping type /*! \note "None" is only for use as a default condition */ enum WrapType { None, Frame, Clip, Line, Other } ; EssenceSubParserParent Handler; //!< Pointer to the object that can parse this wrapping option - parent pointer because the parser holds a copy of this! std::string Name; //!< A short name, unique for this sub-parser, for this wrapping option (or "" if not supported by this handler) std::string Description; //!< Human readable description of this wrapping option (to allow user selection) ULPtr WrappingID; //!< A UL (or endian swapped UUID) that uniquely identifies this sub-parser/wrapping option combination (or NULL if not suppoered by this handler) /*!< This allows an application to specify a desired wrapping, or list of wrappings, for automated selection */ ULPtr WrappingUL; //!< UL for this wrapping ULList RequiredPartners; //!< List of other items that *MUST* accompany this item to use this wrapping UInt8 GCEssenceType; //!< The Generic Container essence type, or 0 if not a GC wrapping UInt8 GCElementType; //!< The Generic Container element value, or 0 if not a GC wrapping WrapType ThisWrapType; //!< The type of this wrapping (frame, clip etc.) bool CanSlave; //!< True if this wrapping can be a "slave" which allows it to be used at a different edit rate than its own bool CanIndex; //!< True if this wrapping can be VBR indexed by the handler (CBR essence may need VBR indexing when interleaved) bool CBRIndex; //!< True if this wrapping may use a CBR index table (and therefore have a non-zero return value from GetBytesPerEditUnit() ) UInt8 BERSize; //!< The BER length size to use for this wrapping (or 0 for any) UInt32 BytesPerEditUnit; //!< set non zero for ConstSamples }; typedef SmartPtr<WrappingOption> WrappingOptionPtr; typedef std::list<WrappingOptionPtr> WrappingOptionList; //! Abstract super-class for objects that supply large quantities of essence data /*! This is used when clip-wrapping to prevent large quantities of data being loaded into memory *! \note Classes derived from this class <b>must not</b> include their own RefCount<> derivation */ class EssenceSource : public RefCount<EssenceSource> { protected: //! Holds the stream ID for this essence stream when added to a GCWriter /*! This value is persisted here between calls to a GCWriter via BodyWriter or similar. * Set to -1 if no stream ID yet set. */ GCStreamID StreamID; //! Index manager to use if we can index the essence IndexManagerPtr IndexMan; //! Sub-stream ID to use for our index data if we can index the essence int IndexStreamID; //! If the default essence key has been overridden for this source it is stored here DataChunkPtr SpecifiedKey; //! True if the default essence key has been overridden with a key that does not use GC track number mechanism bool NonGC; //! Number of frames that should be sent, used to match lengths of streams where appropriate, or -1 for undefined Length LenToSend; //! The essence descriptor describing this essence (if known) else NULL /*! The essence descriptor will be set by the wrapping application once the source has been selected and configured. * This means that the essence source has access to the full metadata that will be written into the file in case iit is required. * /note This descriptor may be the same one supplied by EssenceSubParser::IdentifyEssence() or a modified copy of it, or a completely new object */ MDObjectPtr EssenceDescriptor; //! If we are held in a BodyStream, a parent pointer to it is held here BodyStreamParent BodyParent; public: //! Base constructor EssenceSource() : StreamID(-1), LenToSend(-1) { }; //! Virtual destructor to allow polymorphism virtual ~EssenceSource() { }; //! Get the size of the next "installment" of essence data in bytes /*! \note There is intentionally no support for an "unknown" response */ virtual size_t GetEssenceDataSize(void) = 0; //! Get the next "installment" of essence data /*! This will attempt to return an entire wrapping unit (e.g. a full frame for frame-wrapping) but will return it in * smaller chunks if this would break the MaxSize limit. If a Size is specified then the chunk returned will end at * the first wrapping unit end encountered before Size. On no account will portions of two or more different wrapping * units be returned together. The mechanism for selecting a type of wrapping (e.g. frame, line or clip) is not * (currently) part of the common EssenceSource interface. * \return Pointer to a data chunk holding the next data or a NULL pointer when no more remains * \note If there is more data to come but it is not currently available the return value will be a pointer to an empty data chunk * \note If Size = 0 the object will decide the size of the chunk to return * \note On no account will the returned chunk be larger than MaxSize (if MaxSize > 0) */ virtual DataChunkPtr GetEssenceData(size_t Size = 0, size_t MaxSize = 0) = 0; //! Did the last call to GetEssenceData() return the end of a wrapping item /*! \return true if the last call to GetEssenceData() returned an entire wrapping unit. * \return true if the last call to GetEssenceData() returned the last chunk of a wrapping unit. * \return true if the last call to GetEssenceData() returned the end of a clip-wrapped clip. * \return false if there is more data pending for the current wrapping unit. * \return false if the source is to be clip-wrapped and there is more data pending for the clip */ virtual bool EndOfItem(void) = 0; //! Is all data exhasted? /*! \return false if a call to GetEssenceData() will return some valid essence data */ virtual bool EndOfData(void) = 0; //! Get data to write as padding after all real essence data has been processed /*! If more than one stream is being wrapped, they may not all end at the same wrapping-unit. * When this happens each source that has ended will produce NULL is response to GetEssenceData(). * The default action of the caller would be to write zero-length KLVs in each wrapping unit for each source that has ended. * If a source supplies an overload for this method, the supplied padding data will be written in wrapping units following the end of essence instead of a zero-length KLV * DRAGONS: Note that as the returned value is a non-smart pointer, ownership of the buffer stays with the EssenceSource object. * The recommended method of operation is to have a member DataChunk (or DataChunkPtr) allocated the first time padding is required, and return the address each call. * The destructor must then free the DataChunk, or allow the smart DataChunkPtr to do it automatically */ virtual DataChunk *GetPadding(void) { return NULL; } //! Get the GCEssenceType to use when wrapping this essence in a Generic Container virtual UInt8 GetGCEssenceType(void) = 0; //! Get the GCEssenceType to use when wrapping this essence in a Generic Container virtual UInt8 GetGCElementType(void) = 0; //! Set the stream ID for this stream or sub-stream void SetStreamID(GCStreamID NewID) { StreamID = NewID; } //! Get the stream ID for this stream or sub-stream GCStreamID GetStreamID(void) { return StreamID; } //! Is the last data read the start of an edit point? virtual bool IsEditPoint(void) { return true; } //! Get the edit rate of this wrapping of the essence /*! \note This may not be the same as the original "native" edit rate of the * essence if this EssenceSource is wrapping to a different edit rate */ virtual Rational GetEditRate(void) = 0; //! Get the current position in GetEditRate() sized edit units /*! This is relative to the start of the stream, so the first edit unit is always 0. * This is the same as the number of edit units read so far, so when the essence is * exhausted the value returned shall be the size of the essence */ virtual Position GetCurrentPosition(void) = 0; //! Get the preferred BER length size for essence KLVs written from this source, 0 for auto virtual int GetBERSize(void) { return 0; } //! Set a wrapping option for future Read and Write calls /*! \return true if this wrapping option is suitable for use, else false */ virtual bool Use(WrappingOptionPtr &UseWrapping) { return true; } //! Set a non-native edit rate /*! \return true if this rate is acceptable */ virtual bool SetEditRate(Rational EditRate) { // Default action is to not allow the edit rate to be changed return (EditRate == GetEditRate()); } //! Set a source type or parser specific option /*! \return true if the option was successfully set */ virtual bool SetOption(std::string Option, Int64 Param = 0) { return false; } ; //! Get BytesPerEditUnit if Constant, else 0 /*! \note This value may be useful even if CanIndex() returns false */ virtual UInt32 GetBytesPerEditUnit(UInt32 KAGSize = 1) { return 0; } //! Can this stream provide indexing /*! If true then SetIndex Manager can be used to set the index manager that will receive indexing data */ virtual bool CanIndex() { return false; } //! Set the index manager to use for building index tables for this essence /*! \note The values are stored even if this stream does not support indexing as a derived stream may do */ virtual void SetIndexManager(IndexManagerPtr &Manager, int StreamID) { IndexMan = Manager; IndexStreamID = StreamID; } //! Get the index manager virtual IndexManagerPtr &GetIndexManager(void) { return IndexMan; } //! Get the index manager sub-stream ID virtual int GetIndexStreamID(void) { return IndexStreamID; } //! Override the default essence key virtual void SetKey(DataChunkPtr &Key, bool NonGC = false) { mxflib_assert(Key->Size == 16); SpecifiedKey = Key; this->NonGC = NonGC; } //! Get the current overridden essence key /*! DRAGONS: If the key has not been overridden NULL will be returned - not the default key * \note Defined EssenceSource sub-classes may always use a non-standard key, in which case * they will always return a non-NULL value from this function */ virtual DataChunkPtr &GetKey(void) { return SpecifiedKey; } //! Get true if the default essence key has been overriden with a key that does not use GC track number mechanism /* \note Defined EssenceSource sub-classes may always use a non-GC-type key, in which case * they will always return true from this function */ virtual bool GetNonGC(void) { return NonGC; } /* Essence type identification */ /* These functions can be overwridden, or use the base versions to parse GetGCEssenceType() */ //! Is this source a system item rather than an essence source? virtual bool IsSystemItem(void) { return false; } //! Is this source a generic stream item rather than an normal essence source? virtual bool IsGStreamItem(void) { return false; } //! Is this picture essence? virtual bool IsPictureEssence(void) { UInt8 Type = GetGCEssenceType(); if((Type == 0x05) || (Type == 0x15)) return true; return false; } //! Is this sound essence? virtual bool IsSoundEssence(void) { UInt8 Type = GetGCEssenceType(); if((Type == 0x06) || (Type == 0x16)) return true; return false; } //! Is this data essence? virtual bool IsDataEssence(void) { UInt8 Type = GetGCEssenceType(); if((Type == 0x07) || (Type == 0x17)) return true; return false; } //! Is this compound essence? virtual bool IsCompoundEssence(void) { return (GetGCEssenceType() == 0x18); } //! An indication of the relative write order to use for this stream /*! Normally streams in a GC are ordered as follows: * - All the CP system items (in Scheme ID then Element ID order) * - All the GC system items (in Scheme ID then Element ID order) * - All the CP picture items (in Element ID then Element Number order) * - All the GC picture items (in Element ID then Element Number order) * - All the CP sound items (in Element ID then Element Number order) * - All the GC sound items (in Element ID then Element Number order) * - All the CP data items (in Element ID then Element Number order) * - All the GC data items (in Element ID then Element Number order) * - All the GC compound items (in Element ID then Element Number order) (no GC compound) * * However, sometimes this order needs to be overridden - such as for VBI data preceding picture items. * * The normal case for ordering of an essence stream is for RelativeWriteOrder to return 0, * indicating that the default ordering is to be used. Any other value indicates that relative * ordering is required, and this is used as the Position value for a SetRelativeWriteOrder() * call. The value of Type for that call is acquired from RelativeWriteOrderType() * * For example: to force a source to be written between the last GC sound item and the first CP data * item, RelativeWriteOrder() can return any -ve number, with RelativeWriteOrderType() * returning 0x07 (meaning before CP data). Alternatively RelativeWriteOrder() could * return a +ve number and RelativeWriteOrderType() return 0x16 (meaning after GC sound) */ virtual Int32 RelativeWriteOrder(void) { return 0; } //! The type for relative write-order positioning if RelativeWriteOrder() != 0 /*! This method indicates the essence type to order this data before or after if reletive write-ordering is used */ virtual int RelativeWriteOrderType(void) { return 0; } //! Get the origin value to use for this essence specifically to take account of pre-charge /*! \return Zero if not applicable for this source */ virtual Length GetPrechargeSize(void) { return 0; } //! Get the range start position /*! \return Zero if not applicable for this source */ virtual Position GetRangeStart(void) { return 0; } //! Get the range end position7 /*! \return -1 if not applicable for this source */ virtual Position GetRangeEnd(void) { return 0; } //! Get the range duration /*! \return -1 if not applicable for this source */ virtual Length GetRangeDuration(void) { return 0; } //! Get the name of this essence source (used for error messeges) virtual std::string Name(void) { return "Unnamed EssenceSource object"; } //! Enable VBR indexing, even in clip-wrap mode, by allowing each edit unit to be returned individually /*! As the byte offset part of a VBR index table is constructed at write-time each indexed chunk must be written separately. * When clip-wrapping, this is not normally the case as larger chunks may be returned for efficiency. Setting this mode * forces each indexable edit unit to be returned by a fresh GetEssenceData call as if it were being frame-wrapped. * \return true if this mode is supported by the source, and the mode was set, else false */ virtual bool EnableVBRIndexMode(void) { return false; } //! Set a length-to-send value void SetLenToSend( Length newVal ) { LenToSend=newVal; } //! Read the current length-to-send Length GetLenToSend( void ) const { return LenToSend; } //! Attach a related System Item source to the owning BodyStream if required /*! DRAGONS: This is currently a non-ideal fudge - do not assume this method will last long!!! */ virtual void AttachSystem(BodyStream *Stream) { return; } /* Methods that apply to system item sources */ //! Initialize this system item virtual void InitSystem(BodyStream *Stream) { return; } //! Get the number of KLVs in this system item virtual int GetSystemItemCount(void) { return 0; } //! Get the stream ID for the given system item KLV for this content package /*! \return The stream ID allocated to the item specified, or -1 if invalid * \param Item The 0-based item number */ virtual GCStreamID GetSystemItemID(int Item) { return -1; } //! Get the value for the given system item KLV for this content package /*! \return The value of the item specified, or NULL if invalid * \param Item The 0-based item number */ virtual DataChunkPtr GetSystemItemValue(int Item) { return NULL; } //! Set the essence descriptor virtual void SetDescriptor(MDObjectPtr Descriptor) { EssenceDescriptor = Descriptor; } //! Get a pointer to the essence descriptor for this source (if known) otherwise NULL virtual MDObjectPtr GetDescriptor(void) { return EssenceDescriptor; } //! Set the containing BodyStream void SetBodyStream(BodyStream *pBodyStream); }; // Smart pointer to an EssenceSource object typedef SmartPtr<EssenceSource> EssenceSourcePtr; // Parent pointer to an EssenceSource object typedef ParentPtr<EssenceSource> EssenceSourceParent; // List of smart pointer to EssenceSource objects typedef std::list<EssenceSourcePtr> EssenceSourceList; } #include <cmath> namespace mxflib { //! Class for essence source that supplies system items class SystemSource : public EssenceSource { protected: EssenceSourceParent Master; //!< The master stream for this essence GCStreamID SMPackID; //!< Stream ID of the system metadata pack GCStreamID PMPackID; //!< Stream ID of the package metadata pack UInt16 ContinuityCount; //!< Continuity count as per SMPTE 385M int FPS; //!< Integer frame rate value (25 or 30) bool Rate1001; //!< True if FSP is a (n*1000) / 1001 rate UInt8 EssenceLabel[16]; //!< The essence container label bool DropFrame; //!< True if timecode is using drop-frame counting UInt8 EssenceBitmap; //!< Bitmap flags for essence items, bit 1 = 1 if data, bit 2 = 1 if sound, bit 3 = 1 if picture BodyStream *Stream; //!< Our parent stream DataChunk CreationDate; //!< A pre-formatted 17-byte chunk holding the creation date/time, or an empty chunk if not set DataChunk TimecodeData; //!< A pre-formatted 17-byte chunk holding the timecode, or an empty chunk if not set DataChunk UMIDData; //!< A pre-formatted chunk holding the UMID data for the Package Item, or an empty chunk if not set DataChunk KLVData; //!< A pre-formatted chunk holding the KLV metadata for the Package Item, or an empty chunk if not set public: SystemSource(EssenceSource *MasterSource, const UL &WrappingUL) : EssenceSource() { Master = MasterSource; SMPackID = -1; PMPackID = -1; ContinuityCount = 0; EssenceBitmap = 0; Stream = NULL; // Record the frame rate and essence container label if(Master->GetEditRate().Denominator == 1) { FPS = Master->GetEditRate().Numerator; } else { double FloatFPS = static_cast<double>(Master->GetEditRate().Numerator) / static_cast<double>(Master->GetEditRate().Denominator); FPS = static_cast<int>(floor(FloatFPS + 0.5)); } // Only set flag for exact (n*1000) / 1001 rate Rate1001 = (Master->GetEditRate().Denominator == 1001); // TODO: We don't yet set drop-frame for anything! DropFrame = false; memcpy(EssenceLabel, WrappingUL.GetValue(), 16); } //! Did the last call to GetEssenceData() return the end of a wrapping item /*! \return true if the last call to GetEssenceData() returned an entire wrapping unit. * \return true if the last call to GetEssenceData() returned the last chunk of a wrapping unit. * \return true if the last call to GetEssenceData() returned the end of a clip-wrapped clip. * \return false if there is more data pending for the current wrapping unit. * \return false if the source is to be clip-wrapped and there is more data pending for the clip */ virtual bool EndOfItem(void) { return true; } //! Is all data exhasted? /*! \return false if a call to GetEssenceData() will return some valid essence data */ virtual bool EndOfData(void) { if(Master) return Master->EndOfData(); else return true; } //! Get the GCEssenceType to use when wrapping this essence in a Generic Container virtual UInt8 GetGCEssenceType(void) { return 0x04; }; //! Get the GCEssenceType to use when wrapping this essence in a Generic Container virtual UInt8 GetGCElementType(void) { return 0x00; } //! Get the edit rate of this wrapping of the essence /*! \note This may not be the same as the original "native" edit rate of the * essence if this EssenceSource is wrapping to a different edit rate */ virtual Rational GetEditRate(void) { if(Master) return Master->GetEditRate(); else return Rational(1,1); } //! Get the current position in GetEditRate() sized edit units /*! This is relative to the start of the stream, so the first edit unit is always 0. * This is the same as the number of edit units read so far, so when the essence is * exhausted the value returned shall be the size of the essence */ virtual Position GetCurrentPosition(void) { if(Master) return Master->GetCurrentPosition(); else return 0; } //! Get the preferred BER length size for essence KLVs written from this source, 0 for auto virtual int GetBERSize(void) { return 4; } //! Get BytesPerEditUnit, if Constant virtual UInt32 GetBytesPerEditUnit(UInt32 KAGSize = 1) { // Key, Len, standard value of 57 butes UInt32 Ret = 16 + GetBERSize() + 57; Ret += CalcFillerSize(Ret, KAGSize); return Ret; } //! Is this source a system item rather than an essence source? virtual bool IsSystemItem(void) { return true; } //! Is this picture essence? virtual bool IsPictureEssence(void) { return false; } //! Is this sound essence? virtual bool IsSoundEssence(void) { return false; } //! Is this data essence? virtual bool IsDataEssence(void) { return false; } //! Is this compound essence? virtual bool IsCompoundEssence(void) { return false; } //! Get the size of the essence data in bytes /*! \note There is intentionally no support for an "unknown" response */ virtual size_t GetEssenceDataSize(void) { return 0; } //! Get the next "installment" of essence data /*! \return Pointer to a data chunk holding the next data or a NULL pointer when no more remains * \note If there is more data to come but it is not currently available the return value will be a pointer to an empty data chunk * \note If Size = 0 the object will decide the size of the chunk to return * \note On no account will the returned chunk be larger than MaxSize (if MaxSize > 0) */ virtual DataChunkPtr GetEssenceData(size_t Size = 0, size_t MaxSize = 0) { return NULL; } /* Methods that apply to system item sources */ //! Initialize this system item virtual void InitSystem(BodyStream *Stream); //! Get the number of KLVs in this system item virtual int GetSystemItemCount(void) { // Return 0 when all done (so we don't keep adding empty system items) if((!Master) || Master->EndOfData()) return 0; return 2; } //! Get the stream ID for the given system item KLV for this content package /*! \return The strema ID allocated to the item specified, or -1 if invalid * \param Item The 0-based item number */ virtual GCStreamID GetSystemItemID(int Item) { if(Item == 0) return SMPackID; else if(Item == 1) return PMPackID; return -1; } //! Get the value for the given system item KLV for this content package /*! \return The value of the item specified, or NULL if invalid * \param Item The 0-based item number */ virtual DataChunkPtr GetSystemItemValue(int Item); /* SystemSource Special functions */ //! Set the creation date/time void SetCreationDateTime(std::string DateTime); //! Set the timecode from a string void SetTimecode(std::string TCString); //! Set the UMID to write in the Package Item (NULL will clear the UMID) void SetUMID(UMIDPtr Value = NULL); //! Set the KLV Metadata to write in the Package Item (NULL will clear the KLV Metadata) void SetKLVMetadata(MDObjectPtr Object = NULL); protected: //! Calculate the size of KLVFill required to align to the KAG from a given position UInt32 CalcFillerSize(Position FillPos, UInt32 KAGSize, bool ForceBER4 = false) { if(KAGSize == 0) KAGSize = 1; // Work out how far into a KAG we are UInt32 Offset = (UInt32)(FillPos % KAGSize); // Don't insert anything if we are already aligned if(Offset == 0) return 0; // Work out the required filler size UInt32 Fill = KAGSize - Offset; // Adjust so that the filler can fit // Note that for very small KAGs the filler may be several KAGs long if(ForceBER4) { while(Fill < 20) Fill += KAGSize; } else { while(Fill < 17) Fill += KAGSize; } if(Fill > 0x00ffffff) { error("Maximum supported filler is 0x00ffffff bytes long, " "but attempt to fill from 0x%s to KAG of 0x%08x " "requires a filler of size 0x%08x\n", Int64toHexString(FillPos, 8).c_str(), KAGSize, Fill); Fill = 0x00ffffff; } return Fill; } //! Increment the internal timecode void IncrementTimecode(void); }; } namespace mxflib { //! Abstract super-class for objects that receive large quantities of essence data /*! \note Classes derived from this class <b>must not</b> include their own RefCount<> derivation */ class EssenceSink : public RefCount<EssenceSink> { protected: public: // Base constructor EssenceSink() {}; //! Virtual destructor to allow polymorphism virtual ~EssenceSink() {}; //! Receive the next "installment" of essence data /*! This will recieve a buffer containing thhe next bytes of essence data * \param Buffer The data buffer * \param BufferSize The number of bytes in the data buffer * \param EndOfItem This buffer is the last in this wrapping item * \return True if all is OK, else false * \note The first call may well fail if the sink has not been fully configured. * \note If false is returned the caller should make no more calls to this function, but the function should be implemented such that it is safe to do so */ virtual bool PutEssenceData(UInt8 const *Buffer, size_t BufferSize, bool EndOfItem = true) = 0; //! Receive the next "installment" of essence data from a smart pointer to a DataChunk bool PutEssenceData(DataChunkPtr &Buffer, bool EndOfItem = true) { return PutEssenceData(Buffer->Data, Buffer->Size, EndOfItem); } //! Receive the next "installment" of essence data from a DataChunk bool PutEssenceData(DataChunk &Buffer, bool EndOfItem = true) { return PutEssenceData(Buffer.Data, Buffer.Size, EndOfItem); } //! Called once all data exhasted /*! \return true if all is OK, else false * \note This function must also be called from the derived class' destructor in case it is never explicitly called */ virtual bool EndOfData(void) = 0; //! Get the name of this essence sink (used for error messeges) virtual std::string Name(void) { return "Unnamed EssenceSink object"; } //! Query the sink for an Int32 value virtual Int32 GetInt(std::string Query) { return 0; } //! Query the sink for a string value virtual std::string GetString(std::string Query) { return ""; } //! Set an Int32 value for this sink /*! /return true if the value was accepted, else false */ virtual bool SetInt(std::string Text, Int32 Value) { return false; } //! Set a string value for this sink /*! /return true if the value was accepted, else false */ virtual bool SetString(std::string Text, std::string Value) { return false; } }; // Smart pointer to an EssenceSink object typedef SmartPtr<EssenceSink> EssenceSinkPtr; // Parent pointer to an EssenceSink object typedef ParentPtr<EssenceSink> EssenceSinkParent; // List of smart pointer to EssenceSink objects typedef std::list<EssenceSinkPtr> EssenceSinkList; } namespace mxflib { //! Default "Multiple Essence Types in the Generic Container" Label const UInt8 GCMulti_Data[16] = { 0x06, 0x0E, 0x2B, 0x34, 0x04, 0x01, 0x01, 0x03, 0x0d, 0x01, 0x03, 0x01, 0x02, 0x7F, 0x01, 0x00 }; } namespace mxflib { //! Structure to hold information about each stream in a GC struct GCStreamData { DataChunkPtr SpecifiedKey; //!< Non standard key to use, or NULL to use a standard key bool NonGC; //!< True if the track number bytes are <b>not</b> to be set automatically UInt8 Type; //!< Item type UInt8 SchemeOrCount; //!< Scheme if system or element count if essence UInt8 Element; //!< Element identifier or type UInt8 SubOrNumber; //!< Sub ID if system or element number if essence UInt8 RegDes; //!< The registry designator if this is a system item UInt8 RegVer; //!< The registry version number for the item key int LenSize; //!< The KLV length size to use for this stream (0 for auto) IndexManagerPtr IndexMan; //!< If indexing this stream a pointer to the index manager, else NULL int IndexSubStream; //!< If indexing this stream the sub stream number, else undefined bool IndexFiller; //!< If indexing this stream true if filler <b>preceeding</b> this stream is to be indexed, else undefined bool IndexClip; //!< True if indexing clip-wrapped essence bool CountFixed; //!< True once the essence element count has been fixed /*!< The count is fixed the first time either a key is written * or a track number is reported */ UInt32 WriteOrder; //!< The (default) write order for this stream /*!< Elements with a lower WriteOrder are written first when the * content package is written */ }; //! Class that manages writing of generic container essence class GCWriter : public RefCount<GCWriter> { protected: MXFFilePtr LinkedFile; //!< File that will be written to UInt32 TheBodySID; //!< Body SID for this Essence Container int StreamTableSize; //!< Size of StreamTable int StreamCount; //!< Number of entries in use in StreamTable int StreamBase; //!< Base of all stream numbers in keys GCStreamData *StreamTable; //!< Table of data for streams for this GC UInt32 KAGSize; //!< KAGSize for this Essence Container bool ForceFillerBER4; //!< True if filler items must have BER lengths forced to 4-byte BER Int32 NextWriteOrder; //!< The "WriteOrder" to use for the next auto "SetWriteOrder()" Position IndexEditUnit; //!< Edit unit of the current CP for use if indexing /*!< This property starts at zero and is incremented with each CP written, however the value * can be changed by calling SetIndexEditUnit() before calling StartNewCP() */ Length PreCharge; //!< The number of edit units of pre-charge at the start of the essence (required for indexing) UInt64 StreamOffset; //!< Current stream offset within this essence container //! Map of all used write orders to stream ID - used to ensure no duplicates std::map<UInt32, GCStreamID> WriteOrderMap; public: //! Constructor GCWriter(MXFFilePtr File, UInt32 BodySID = 0, int Base = 1); //! Destructor ~GCWriter(); //! Set the KAG for this Essence Container void SetKAG(UInt32 KAG, bool ForceBER4 = false) { KAGSize = KAG; ForceFillerBER4 = ForceBER4; }; //! Get the current KAGSize UInt32 GetKAG(void) { return KAGSize; } //! Define a new non-CP system element for this container GCStreamID AddSystemElement(unsigned int RegistryDesignator, unsigned int SchemeID, unsigned int ElementID, unsigned int SubID = 0) { return AddSystemElement(false, RegistryDesignator, SchemeID, ElementID, SubID); } //! Define a new CP-compatible system element for this container GCStreamID AddCPSystemElement(unsigned int RegistryDesignator, unsigned int SchemeID, unsigned int ElementID, unsigned int SubID = 0) { return AddSystemElement(true, RegistryDesignator, SchemeID, ElementID, SubID); } //! Define a new system element for this container GCStreamID AddSystemElement(bool CPCompatible, unsigned int RegistryDesignator, unsigned int SchemeID, unsigned int ElementID, unsigned int SubID = 0); //! Define a new non-CP picture element for this container GCStreamID AddPictureElement(unsigned int ElementType) { return AddPictureElement(false, ElementType); } //! Define a new CP-compatible picture element for this container GCStreamID AddCPPictureElement(unsigned int ElementType) { return AddPictureElement(true, ElementType); } //! Define a new picture element for this container GCStreamID AddPictureElement(bool CPCompatible, unsigned int ElementType) { return AddEssenceElement( CPCompatible ? 0x05 : 0x15, ElementType); } //! Define a new non-CP sound element for this container GCStreamID AddSoundElement(unsigned int ElementType) { return AddPictureElement(false, ElementType); } //! Define a new CP-compatible sound element for this container GCStreamID AddCPSoundElement(unsigned int ElementType) { return AddPictureElement(true, ElementType); } //! Define a new sound element for this container GCStreamID AddSoundElement(bool CPCompatible, unsigned int ElementType) { return AddEssenceElement( CPCompatible ? 0x06 : 0x16, ElementType); } //! Define a new non-CP data element for this container GCStreamID AddDataElement(unsigned int ElementType) { return AddDataElement(false, ElementType); } //! Define a new CP-compatible data element for this container GCStreamID AddCPDataElement(unsigned int ElementType) { return AddDataElement(true, ElementType); } //! Define a new data element for this container GCStreamID AddDataElement(bool CPCompatible, unsigned int ElementType) { return AddEssenceElement( CPCompatible ? 0x07 : 0x17, ElementType); } //! Define a new compound element for this container GCStreamID AddCompoundElement(unsigned int ElementType) { return AddEssenceElement( 0x18, ElementType); } //! Define a new essence element for this container GCStreamID AddEssenceElement(unsigned int EssenceType, unsigned int ElementType, int LenSize = 0); //! Define a new essence element for this container, with a specified key GCStreamID AddEssenceElement(DataChunkPtr &Key, int LenSize = 0, bool NonGC = false); //! Define a new essence element for this container, with a specified key GCStreamID AddEssenceElement(int KeySize, UInt8 *KeyData, int LenSize = 0, bool NonGC = false) { DataChunkPtr Key = new DataChunk(KeySize, KeyData); return AddEssenceElement(Key, LenSize, NonGC); } //! Allow this data stream to be indexed and set the index manager void AddStreamIndex(GCStreamID ID, IndexManagerPtr &IndexMan, int IndexSubStream, bool IndexFiller = false, bool IndexClip = false); //! Get the track number associated with the specified stream UInt32 GetTrackNumber(GCStreamID ID); //! Assign an essence container (mapping) UL to the specified stream void AssignEssenceUL(GCStreamID ID, ULPtr EssenceUL); //! Start a new content package (and write out the prevous one if required) void StartNewCP(void); //! Calculate how much data will be written if "Flush" is called now UInt64 CalcWriteSize(void); //! Flush any remaining data void Flush(void); //! Get the current stream offset Int64 GetStreamOffset(void) { return StreamOffset; } //! Set the index position for the current CP void SetIndexEditUnit(Position EditUnit) { IndexEditUnit = EditUnit; } //! Set the pre-charge size to allow the index table to be built correctly void SetPreCharge(Length PreChargeSize) { // Record for any new streams PreCharge = PreChargeSize; // Set any existing streams for(int i=0; i<StreamCount; i++) if(StreamTable[i].IndexMan) StreamTable[i].IndexMan->SetPreCharge(PreChargeSize); } //! Get the index position of the current CP Position GetIndexEditUnit(void) { return IndexEditUnit; } //! Add system item data to the current CP void AddSystemData(GCStreamID ID, UInt64 Size, const UInt8 *Data); //! Add system item data to the current CP void AddSystemData(GCStreamID ID, DataChunkPtr Chunk) { AddSystemData(ID, Chunk->Size, Chunk->Data); } //! Add encrypted system item data to the current CP void AddSystemData(GCStreamID ID, UInt64 Size, const UInt8 *Data, UUIDPtr ContextID, Length PlaintextOffset = 0); //! Add encrypted system item data to the current CP void AddSystemData(GCStreamID ID, DataChunkPtr Chunk, UUIDPtr ContextID, Length PlaintextOffset = 0) { AddSystemData(ID, Chunk->Size, Chunk->Data, ContextID, PlaintextOffset); } //! Add essence data to the current CP void AddEssenceData(GCStreamID ID, UInt64 Size, const UInt8 *Data, BodyStreamPtr BStream = NULL); //! Add essence data to the current CP void AddEssenceData(GCStreamID ID, DataChunkPtr Chunk, BodyStreamPtr BStream = NULL) { AddEssenceData(ID, Chunk->Size, Chunk->Data, BStream); } //! Add essence data to the current CP void AddEssenceData(GCStreamID ID, EssenceSourcePtr Source, bool FastClipWrap = false, BodyStreamPtr BStream = NULL); /* //! Add encrypted essence data to the current CP void AddEssenceData(GCStreamID ID, UInt64 Size, const UInt8 *Data, UUIDPtr ContextID, Length PlaintextOffset = 0); //! Add encrypted essence data to the current CP void AddEssenceData(GCStreamID ID, DataChunkPtr Chunk, UUIDPtr ContextID, Length PlaintextOffset = 0) { AddEssenceData(ID, Chunk->Size, Chunk->Data, ContextID, PlaintextOffset); } //! Add encrypted essence data to the current CP void AddEssenceData(GCStreamID ID, EssenceSource* Source, UUIDPtr ContextID, Length PlaintextOffset = 0, bool FastClipWrap = false); */ //! Add an essence item to the current CP with the essence to be read from a KLVObject void AddEssenceData(GCStreamID ID, KLVObjectPtr Source, bool FastClipWrap = false, BodyStreamPtr BStream = NULL); //! Calculate how many bytes would be written if the specified object were written with WriteRaw() Length CalcRawSize(KLVObjectPtr Object); //! Write a raw KLVObject to the file - this is written immediately and not buffered in the WriteQueue void WriteRaw(KLVObjectPtr Object); //! Structure for items to be written struct WriteBlock { UInt64 Size; //!< Number of bytes of data to write UInt8 *Buffer; //!< Pointer to bytes to write EssenceSourcePtr Source; //!< Smart pointer to an EssenceSource object or NULL KLVObjectPtr KLVSource; //!< Pointer to a KLVObject as source - or NULL int LenSize; //!< The KLV length size to use for this item (0 for auto) IndexManagerPtr IndexMan; //!< Index manager that wants to know about this data BodyStreamPtr Stream; //!< The calling BodyStream object - or NULL int IndexSubStream; //!< Sub-stream ID of data for indexing bool IndexFiller; //!< If true filler will also be indexed with SubStream -1 bool IndexClip; //!< True if indexing clip-wrapped essence bool WriteEncrypted; //!< True if the data is to be written as encrypted data (via a KLVEObject) bool FastClipWrap; //!< True if this KLV is to be "FastClipWrapped" }; //! Type for holding the write queue in write order typedef std::map<UInt32,WriteBlock> WriteQueueMap; //! Queue of items for the current content package in write order WriteQueueMap WriteQueue; //! Set the WriteOrder for the specified stream void SetWriteOrder(GCStreamID ID, Int32 WriteOrder = -1, int Type =-1); //! Set a write-order relative to all items of a specified type void SetRelativeWriteOrder(GCStreamID ID, int Type, Int32 Position); //! Get the WriteOrder for the specified stream Int32 GetWriteOrder(GCStreamID ID); //! Read the count of streams int GetStreamCount(void) { return StreamCount; }; }; } namespace mxflib { //! Class for holding a description of an essence stream class EssenceStreamDescriptor; //! A smart pointer to a EssenceStreamDescriptor object typedef SmartPtr<EssenceStreamDescriptor> EssenceStreamDescriptorPtr; //! A list of smart pointers to EssenceStreamDescriptor objects typedef std::list<EssenceStreamDescriptorPtr> EssenceStreamDescriptorList; /*! \page SubStreamNotes Notes on Sub-Streams * \section SubStreams1 Sub-Streams Introduction * Certain essence streams may have intimate data related to the essence that is linked as a substream. * \section SubParserSubStreams Sub-Streams in EssenceSubParsers * An EssenceSubParser may produce a main EssenceSource with sub-streams which are EssenceSources whose * data is extracted during the parsing that produces the main source's data. These SubStreams are indicated * by members of the EssenceStreamDescriptor::SubStreams properties of members of the EssenceStreamDescriptorList * returned by a call to EssenceSubParserBase::IdentifyEssence(). This in turn gets propogated to the * EssenceParser::WrapingConfig::SubStreams properties of members of the EssenceParser::WrapingConfigList * returned by a call to EssenceParser::ListWrappingOptions(). * * The value of EssenceStreamDescriptor::ID, and hence EssenceParser::WrapingConfig::Stream, will differ * between the main stream and its sub-streams. These stream IDs are passed to EssenceSubParserBase::GetEssenceSource * to produce the desired EssenceSource objects. The master stream needs to be requested first, otherwise the * EssenceSubParserBase::GetEssenceSource is unlikely to produce a valid sub-stream EssenceSource. * * It is worth noting that as the sub-stream data is extracted from the master stream, the master stream is responsible * for managing the file handle and other items such as the edit rate. * * \attention Any EssenceSubParser providing sub-streams <b>must</b> support EssenceSubParserBase::ReValidate(), * even if only to reject all attempts to continue into the next file (as this may not be a valid thing to do). * * \attention It is the responsibility of the EssenceSubParser to ensure that data for all streams is extracted from * the initial file before the master stream returns NULL from its GetEssenceData() method. * This is because the file will be closed soon after that call is made. * * DRAGONS: There may be a requirement at some point to allow an EssenceSubParser to keep the file open if a huge amount of data is still unread */ /*! Class for holding a description of an essence stream * (used to differentiate multiple streams in an essence file) * and a human-readable description */ class EssenceStreamDescriptor : public RefCount<EssenceStreamDescriptor> { public: //! Construct with any optional items cleared EssenceStreamDescriptor() : StartTimecode(0) {} public: UInt32 ID; //!< ID for this essence stream std::string Description; //!< Description of this essence stream UUID SourceFormat; //!< A UUID (or byte-swapped UL) identifying the source format MDObjectPtr Descriptor; //!< Pointer to an actual essence descriptor for this stream EssenceStreamDescriptorList SubStreams; //!< A list of sub-streams that can be derived from this stream. See \ref SubStreamNotes Position StartTimecode; //!< The starting timecode of this essence, if known, or zero }; //! Base class for any EssenceSubParserFactory classes class EssenceSubParserFactory : public RefCount<EssenceSubParserFactory> { public: //! Build a new sub-parser of the appropriate type virtual EssenceSubParserPtr NewParser(void) const = 0; }; //! Smart pointer to an EssenceSubParserFactory typedef SmartPtr<EssenceSubParserFactory> EssenceSubParserFactoryPtr; //! Abstract base class for all essence parsers /*! \note It is important that no derived class has its own derivation of RefCount<> */ class EssenceSubParser : public RefCount<EssenceSubParser> { protected: //! The wrapping options selected WrappingOptionPtr SelectedWrapping; //! The index manager in use IndexManagerPtr Manager; //! This essence stream's stream ID in the index manager int ManagedStreamID; //! The essence descriptor describing this essence (if known) else NULL MDObjectPtr EssenceDescriptor; public: //! Base class for essence parser EssenceSource objects /*! Still abstract as there is no generic way to determine the data size */ class ESP_EssenceSource : public EssenceSource { protected: EssenceSubParserPtr Caller; FileHandle File; UInt32 Stream; UInt64 RequestedCount; IndexTablePtr Index; DataChunkPtr RemainingData; bool AtEndOfData; bool Started; public: //! Construct and initialise for essence parsing/sourcing ESP_EssenceSource(EssenceSubParserPtr TheCaller, FileHandle InFile, UInt32 UseStream, UInt64 Count = 1) { Caller = TheCaller; File = InFile; Stream = UseStream; RequestedCount = Count; AtEndOfData = false; Started = false; }; //! Get the next "installment" of essence data /*! This will attempt to return an entire wrapping unit (e.g. a full frame for frame-wrapping) but will return it in * smaller chunks if this would break the MaxSize limit. If a Size is specified then the chunk returned will end at * the first wrapping unit end encountered before Size. On no account will portions of two or more different wrapping * units be returned together. The mechanism for selecting a type of wrapping (e.g. frame, line or clip) is not * (currently) part of the common EssenceSource interface. * \return Pointer to a data chunk holding the next data or a NULL pointer when no more remains * \note If there is more data to come but it is not currently available the return value will be a pointer to an empty data chunk * \note If Size = 0 the object will decide the size of the chunk to return * \note On no account will the returned chunk be larger than MaxSize (if MaxSize > 0) */ virtual DataChunkPtr GetEssenceData(size_t Size = 0, size_t MaxSize = 0) { return BaseGetEssenceData(Size, MaxSize); }; //! Non-virtual basic version of GetEssenceData() that can be called by derived classes /*! DRAGONS: This implementation always reads whole wrapping units, so it NOT SAFE if these could be too large to fit in memory */ DataChunkPtr BaseGetEssenceData(size_t Size = 0, size_t MaxSize = 0) { // Allow us to differentiate the first call if(!Started) Started = true; DataChunkPtr Data; if(RemainingData) { Data = RemainingData; RemainingData = NULL; } else { Data = Caller->Read(File, Stream, 1); } if(Data) { if(Data->Size == 0) Data = NULL; else { if((MaxSize) && (Data->Size > MaxSize)) { RemainingData = new DataChunk(Data->Size - MaxSize, &Data->Data[MaxSize]); Data->Resize((UInt32)MaxSize); } } } // Record when we hit the end of all data if(!Data) AtEndOfData = true; return Data; } //! Did the last call to GetEssenceData() return the end of a wrapping item /*! \return true if the last call to GetEssenceData() returned an entire wrapping unit. * \return true if the last call to GetEssenceData() returned the last chunk of a wrapping unit. * \return true if the last call to GetEssenceData() returned the end of a clip-wrapped clip. * \return false if there is more data pending for the current wrapping unit. * \return false if the source is to be clip-wrapped and there is more data pending for the clip */ virtual bool EndOfItem(void) { // If we are clip wrapping then we only end when no more data if(Caller->GetWrapType() == WrappingOption::Clip) return AtEndOfData; // Otherwise items end when there is no data remaining from the last read return !RemainingData; } //! Is all data exhasted? /*! \return true if a call to GetEssenceData() will return some valid essence data */ virtual bool EndOfData(void) { return AtEndOfData; } //! Get data to write as padding after all real essence data has been processed /*! If more than one stream is being wrapped, they may not all end at the same wrapping-unit. * When this happens each source that has ended will produce NULL is response to GetEssenceData(). * The default action of the caller would be to write zero-length KLVs in each wrapping unit for each source that has ended. * If a source supplies an overload for this method, the supplied padding data will be written in wrapping units following the end of essence instead of a zero-length KLV * DRAGONS: Note that as the returned value is a non-smart pointer, ownership of the buffer stays with the EssenceSource object. * The recommended method of operation is to have a member DataChunk (or DataChunkPtr) allocated the first time padding is required, and return the address each call. * The destructor must then free the DataChunk, or allow the smart DataChunkPtr to do it automatically */ virtual DataChunk *GetPadding(void) { return NULL; } //! Get the GCEssenceType to use when wrapping this essence in a Generic Container virtual UInt8 GetGCEssenceType(void) { return Caller->GetGCEssenceType(); } //! Get the GCEssenceType to use when wrapping this essence in a Generic Container virtual UInt8 GetGCElementType(void) { return Caller->GetGCElementType(); } //! Is the last data read the start of an edit point? virtual bool IsEditPoint(void) { return true; } //! Get the edit rate of this wrapping of the essence /*! \note This may not be the same as the original "native" edit rate of the * essence if this EssenceSource is wrapping to a different edit rate */ virtual Rational GetEditRate(void) { return Caller->GetEditRate(); } //! Get the current position in GetEditRate() sized edit units /*! This is relative to the start of the stream, so the first edit unit is always 0. * This is the same as the number of edit units read so far, so when the essence is * exhausted the value returned shall be the size of the essence */ virtual Position GetCurrentPosition(void) { return Caller->GetCurrentPosition(); } //! Set a parser specific option /*! \return true if the option was successfully set */ virtual bool SetOption(std::string Option, Int64 Param = 0) { return Caller->SetOption(Option, Param); } ; //! Get BytesPerEditUnit if Constant, else 0 /*! \note This value may be useful even if CanIndex() returns false */ virtual UInt32 GetBytesPerEditUnit(UInt32 KAGSize = 1) { return Caller->GetBytesPerEditUnit(KAGSize); } //! Can this stream provide indexing /*! If true then SetIndex Manager can be used to set the index manager that will receive indexing data */ virtual bool CanIndex() { return Caller->SelectedWrapping->CanIndex; } //! Set the index manager to use for building index tables for this essence virtual void SetIndexManager(IndexManagerPtr &Manager, int StreamID) { // Set the manager in our containing parser Caller->SetIndexManager(Manager, StreamID); } //! Get the index manager virtual IndexManagerPtr &GetIndexManager(void) { // Set the manager in our containing parser return Caller->GetIndexManager(); } //! Get the IndexManager StreamID for this essence stream virtual int GetIndexStreamID(void) { if(Caller) { // Get from our containing parser return Caller->GetIndexStreamID(); } return IndexStreamID; } //! Get the name of this essence source (used for error messeges) virtual std::string Name(void) { if(Caller) return Caller->GetParserName() +" sub-parser"; else return " Parser"; } //! Set the essence descriptor virtual void SetDescriptor(MDObjectPtr Descriptor) { Caller->EssenceDescriptor = Descriptor; } //! Get a pointer to the essence descriptor for this source (if known) otherwise NULL virtual MDObjectPtr GetDescriptor(void) { return Caller->EssenceDescriptor; } }; // Allow embedded essence source to access our protected properties friend class ESP_EssenceSource; protected: public: //! Base destructor (to allow polymorphism) virtual ~EssenceSubParser() {}; //! Report the extensions of files this sub-parser is likely to handle virtual StringList HandledExtensions(void) { StringList Ret; return Ret; }; //! Examine the open file and return a list of essence descriptors /*! This function should fail as fast as possible if the essence if not identifyable by this object * \return A list of EssenceStreamDescriptors where each essence stream identified in the input file has * an identifier (to allow it to be referenced later) and an MXF File Descriptor */ virtual EssenceStreamDescriptorList IdentifyEssence(FileHandle InFile) { EssenceStreamDescriptorList Ret; return Ret; } //! Examine the open file and return the wrapping options known by this parser /*! \param InFile The open file to examine (if the descriptor does not contain enough info) * \param Descriptor An essence stream descriptor (as produced by function IdentifyEssence) * of the essence stream requiring wrapping * \note The options should be returned in an order of preference as the caller is likely to use the first that it can support */ virtual WrappingOptionList IdentifyWrappingOptions(FileHandle InFile, EssenceStreamDescriptor &Descriptor) { WrappingOptionList Ret; return Ret; } //! Set a wrapping option for future Read and Write calls virtual void Use(UInt32 Stream, WrappingOptionPtr &UseWrapping) { // DRAGONS: Any derived version of Use() must also set SelectedWrapping SelectedWrapping = UseWrapping; } //! Does this essence parser support ReValidate() virtual bool CanReValidate(void) { return false; } //! Quickly validate that the given (open) file can be wrapped as specified /*! Providing that the given essence descriptor and wrapping option can be used this will leave the parser * in the state it would have been in after calls to IdentifyEssence(), IdentifyWrappingOptions() and Use(). * This is used when parsing a list of files to check that the second and later files are the same format as the first * \return true if all OK */ virtual bool ReValidate(FileHandle Infile, UInt32 Stream, MDObjectPtr &Descriptor, WrappingOptionPtr &UseWrapping) { return false; } //! Get the wrapping type that has been selected by Use() WrappingOption::WrapType GetWrapType(void) { if(!SelectedWrapping) return WrappingOption::None; return SelectedWrapping->ThisWrapType; } //! Set a non-native edit rate /*! \return true if this rate is acceptable */ virtual bool SetEditRate(Rational EditRate) { // Default action is to not allow the edit rate to be changed return (EditRate == GetEditRate()); } //! Get the current edit rate virtual Rational GetEditRate(void) = 0; //! Get the preferred edit rate (if one is known) /*! \return The prefered edit rate or 0/0 if note known */ virtual Rational GetPreferredEditRate(void) { // By default we don't know the preferred rate return Rational(0,0); } //! Get BytesPerEditUnit, if Constant /*! Note that we use KAGSize to prevent compiler warnings (we cannot omit it as it has a default value) */ virtual UInt32 GetBytesPerEditUnit(UInt32 KAGSize = 1) { return KAGSize * 0; } //! Get the current position in SetEditRate() sized edit units /*! This is relative to the start of the stream, so the first edit unit is always 0. * This is the same as the number of edit units read so far, so when the essence is * exhausted the value returned shall be the size of the essence */ virtual Position GetCurrentPosition(void) = 0; //! Set the IndexManager for this essence stream (and the stream ID if we are not the main stream) virtual void SetIndexManager(IndexManagerPtr &TheManager, int StreamID = 0) { Manager = TheManager; ManagedStreamID = StreamID; } //! Get the IndexManager for this essence stream virtual IndexManagerPtr &GetIndexManager(void) { return Manager; }; //! Get the IndexManager StreamID for this essence stream virtual int GetIndexStreamID(void) { return ManagedStreamID; }; //! Set the stream offset for a specified edit unit into the current index manager virtual void SetStreamOffset(Position EditUnit, UInt64 Offset) { if(Manager) Manager->SetOffset(ManagedStreamID, EditUnit, Offset); } //! Offer the stream offset for a specified edit unit to the current index manager virtual bool OfferStreamOffset(Position EditUnit, UInt64 Offset) { if(!Manager) return false; return Manager->OfferOffset(ManagedStreamID, EditUnit, Offset); } //! Instruct index manager to accept the next edit unit virtual void IndexNext(void) { if(Manager) Manager->AcceptNext(); } //! Instruct index manager to accept and log the next edit unit virtual int IndexLogNext(void) { if(Manager) return Manager->AcceptLogNext(); return -1; } //! Instruct index manager to log the next edit unit virtual int LogNext(void) { if(Manager) return Manager->LogNext(); return -1; } //! Read an edit unit from the index manager's log virtual Position ReadLog(int LogID) { if(Manager) return Manager->ReadLog(LogID); return IndexTable::IndexLowest; } //! Instruct index manager to accept provisional entry /*! \return The edit unit of the entry accepted - or IndexLowest if none available */ virtual Position AcceptProvisional(void) { if(Manager) return Manager->AcceptProvisional(); return IndexTable::IndexLowest; } //! Read the edit unit of the last entry added via the index manager (or IndexLowest if none added) Position GetLastNewEditUnit(void) { if(Manager) return Manager->GetLastNewEditUnit(); return IndexTable::IndexLowest; } //! Get the GCEssenceType to use when wrapping this essence in a Generic Container virtual UInt8 GetGCEssenceType(void) { return SelectedWrapping->GCEssenceType; } //! Get the GCEssenceType to use when wrapping this essence in a Generic Container virtual UInt8 GetGCElementType(void) { return SelectedWrapping->GCElementType; } //! Read a number of wrapping items from the specified stream and return them in a data chunk /*! If frame or line mapping is used the parameter Count is used to * determine how many items are read. In frame wrapping it is in * units of EditRate, as specified in the call to Use(), which may * not be the frame rate of this essence * \note This is going to take a lot of memory in clip wrapping! */ virtual DataChunkPtr Read(FileHandle InFile, UInt32 Stream, UInt64 Count = 1) = 0; //! Build an EssenceSource to read a number of wrapping items from the specified stream virtual EssenceSourcePtr GetEssenceSource(FileHandle InFile, UInt32 Stream, UInt64 Count = 1) = 0; //! Write a number of wrapping items from the specified stream to an MXF file /*! If frame or line mapping is used the parameter Count is used to * determine how many items are read. In frame wrapping it is in * units of EditRate, as specified in the call to Use(), which may * not be the frame rate of this essence stream * \note This used to be the only safe option for clip wrapping * \return Count of bytes transferred * DRAGONS: ** DEPRECATED ** */ virtual Length Write(FileHandle InFile, UInt32 Stream, MXFFilePtr OutFile, UInt64 Count = 1) = 0; //! Set a parser specific option /*! \return true if the option was successfully set */ virtual bool SetOption(std::string Option, Int64 Param = 0) { return false; } ; //! Get a unique name for this sub-parser /*! The name must be all lower case, and must be unique. * The recommended name is the part of the filename of the parser header after "esp_" and before the ".h". * If the parser has no name return "" (however this will prevent named wrapping option selection for this sub-parser) */ virtual std::string GetParserName(void) const { return ""; } //! Build a new sub-parser of the appropriate type /*! \note You must redefine this function in a sub-parser even if it is not going to be its own factory (EssenceSubParserFactory used). * In this case it is best to call the factory's NewParser() method. */ virtual EssenceSubParserPtr NewParser(void) const = 0; //! Set the essence descriptor virtual void SetDescriptor(MDObjectPtr Descriptor) { EssenceDescriptor = Descriptor; } //! Get a pointer to the essence descriptor for this source (if known) otherwise NULL virtual MDObjectPtr GetDescriptor(void) { return EssenceDescriptor; } }; //! Rename of EssenceSubParser for legacy compatibility typedef EssenceSubParser EssenceSubParserBase; //! A wrapper class that allows an EssenceSubParser to be its own factory /*! This less memory-efficient method supports older EssenceSubParsers */ class EssenceSubParserSelfFactory : public EssenceSubParserFactory { protected: //! The parser that we are wrapping EssenceSubParserPtr Parser; public: //! Construct a factory that wraps a specified self-factory parser EssenceSubParserSelfFactory(EssenceSubParserPtr Parser) : Parser(Parser) {}; //! Build a new sub-parser of the appropriate type virtual EssenceSubParserPtr NewParser(void) const { return Parser->NewParser(); } }; } namespace mxflib { //! Pair containing a pointer to an essence parser and its associated essence descriptors typedef std::pair<EssenceSubParserPtr, EssenceStreamDescriptorList> ParserDescriptorPair; //! List of pointers to essence parsers typedef std::list<EssenceSubParserPtr> EssenceParserList; //! List of pairs of essence parser pointers with associated file descriptors class ParserDescriptorList : public RefCount<ParserDescriptorList>, public std::list<ParserDescriptorPair> {}; typedef SmartPtr<ParserDescriptorList> ParserDescriptorListPtr; //! Master-class for parsing essence via EssenceSubParser objects class EssenceParser { public: //! A list of parser factory functions typedef std::list<EssenceSubParserFactoryPtr> EssenceSubParserFactoryList; protected: //! List of pointers to known parsers /*! Used only for building parsers to parse essence - the parses * in this list must not themselves be used for essence parsing */ static EssenceSubParserFactoryList EPList; //! Initialization flag for EPList static bool Inited; private: //! Prevent instantiation of essence parser - all methods are now static EssenceParser(); public: //! Add a new EssenceSubParser type /*! This adds a factory to build instances of a new sub parser type if required * to parse an essence stream */ static void AddNewSubParserType(EssenceSubParserFactoryPtr Factory) { EPList.push_back(Factory); } //! Add a new EssenceSubParser type /*! This adds a factory to build instances of a new sub parser type if required * to parse an essence stream. * \note This is the lecacy version to cope with EssenceSubParsers which are thier own factories */ static void AddNewSubParserType(EssenceSubParserPtr SubParser) { EssenceSubParserFactoryPtr Factory = new EssenceSubParserSelfFactory(SubParser); EPList.push_back(Factory); } //! Build a list of parsers with their descriptors for a given essence file static ParserDescriptorListPtr IdentifyEssence(FileHandle InFile); //! Configuration data for an essence parser with a specific wrapping option class WrappingConfig; //! Smart pointer to a WrappingConfig object typedef SmartPtr<WrappingConfig> WrappingConfigPtr; //! Parent pointer to a WrappingConfig object typedef ParentPtr<WrappingConfig> WrappingConfigParent; //! List of smart pointers to WrappingConfig objects typedef std::list<WrappingConfigPtr> WrappingConfigList; //! Configuration data for an essence parser with a specific wrapping option /*! \note No parser may contain one of these that includes a pointer to that parser otherwise it will never be deleted (circular reference) */ class WrappingConfig : public RefCount<WrappingConfig> { public: //! Construct with any optional items cleared WrappingConfig() : StartTimecode(0), IsExternal(false), KAGSize(1), File(FileInvalid) {} public: EssenceSubParserPtr Parser; //!< The parser that parses this essence - true smart pointer not a parent pointer to keep parser alive WrappingOptionPtr WrapOpt; //!< The wrapping options MDObjectPtr EssenceDescriptor; //!< The essence descriptior for the essence as parsed UInt32 Stream; //!< The stream ID of this stream from the parser Rational EditRate; //!< The selected edit rate for this wrapping WrappingConfigList SubStreams; //!< A list of wrapping options available for sub-streams extracted from the same essence source. See \ref SubStreamNotes Position StartTimecode; //!< The starting timecode of this essence, if known, or zero bool IsExternal; //!< True if this is actually going to become an external raw-essence stream UInt32 KAGSize; //!< The selected KAGSize for this wrapping protected: FileHandle File; //!< The handle of the file used as the source of this essence EssenceSourcePtr Source; //!< The source to use for wrapping this essence public: //! Get the essence source for this wrapping - building it if required EssenceSourcePtr GetSource(void) { if(!Source) { if(!FileValid(File)) error("WrappingConfig::GetSource() called without a call to WrappingConfig::SetFile()\n"); else Source = Parser->GetEssenceSource(File, Stream); } return Source; } //! Set the source file void SetFile(FileHandle InFile) { File = InFile; } //! Set the essence source /*! DRAGONS: When called, this wrapping config will take (shared) ownership of the source */ void SetSource(EssenceSourcePtr &Value) { Source = Value; } //! Set the essence source /*! DRAGONS: When called, this wrapping config will take (shared) ownership of the source */ void SetSource(EssenceSource *Value) { Source = Value; } }; //! Produce a list of available wrapping options static WrappingConfigList ListWrappingOptions(bool AllowMultiples, FileHandle InFile, ParserDescriptorListPtr PDList, Rational ForceEditRate, WrappingOption::WrapType ForceWrap = WrappingOption::None); //! Produce a list of available wrapping options static WrappingConfigList ListWrappingOptions(FileHandle InFile, ParserDescriptorListPtr PDList, Rational ForceEditRate, WrappingOption::WrapType ForceWrap = WrappingOption::None) { return ListWrappingOptions(false, InFile, PDList, ForceEditRate, ForceWrap); } //! Produce a list of available wrapping options static WrappingConfigList ListWrappingOptions(bool AllowMultiples, FileHandle InFile, Rational ForceEditRate, WrappingOption::WrapType ForceWrap = WrappingOption::None); //! Produce a list of available wrapping options static WrappingConfigList ListWrappingOptions(FileHandle InFile, Rational ForceEditRate, WrappingOption::WrapType ForceWrap = WrappingOption::None) { return ListWrappingOptions(false, InFile, ForceEditRate, ForceWrap); } //! Produce a list of available wrapping options static WrappingConfigList ListWrappingOptions(bool AllowMultiples, FileHandle InFile, WrappingOption::WrapType ForceWrap = WrappingOption::None) { Rational ForceEditRate(0,0); return ListWrappingOptions(AllowMultiples, InFile, ForceEditRate, ForceWrap); } //! Produce a list of available wrapping options static WrappingConfigList ListWrappingOptions(FileHandle InFile, WrappingOption::WrapType ForceWrap = WrappingOption::None) { Rational ForceEditRate(0,0); return ListWrappingOptions(false, InFile, ForceEditRate, ForceWrap); } //! Select the best wrapping option static WrappingConfigPtr SelectWrappingOption(FileHandle InFile, ParserDescriptorListPtr PDList, Rational ForceEditRate, WrappingOption::WrapType ForceWrap = WrappingOption::None) { return SelectWrappingOption(false, InFile, PDList, ForceEditRate, ForceWrap); } //! Select the best wrapping option static WrappingConfigPtr SelectWrappingOption(FileHandle InFile, ParserDescriptorListPtr PDList, WrappingOption::WrapType ForceWrap = WrappingOption::None) { Rational ForceEditRate(0,0); return SelectWrappingOption(false, InFile, PDList, ForceEditRate, ForceWrap); } //! Select the best wrapping option static WrappingConfigPtr SelectWrappingOption(bool AllowMultiples, FileHandle InFile, ParserDescriptorListPtr PDList, Rational ForceEditRate, WrappingOption::WrapType ForceWrap = WrappingOption::None); //! Select the best wrapping option static WrappingConfigPtr SelectWrappingOption(bool AllowMultiples, FileHandle InFile, ParserDescriptorListPtr PDList, WrappingOption::WrapType ForceWrap = WrappingOption::None) { Rational ForceEditRate(0,0); return SelectWrappingOption(AllowMultiples, InFile, PDList, ForceEditRate, ForceWrap); } //! Select the best wrapping option static WrappingConfigPtr SelectWrappingOption(FileHandle InFile, Rational ForceEditRate, WrappingOption::WrapType ForceWrap = WrappingOption::None) { return SelectWrappingOption(false, InFile, ForceEditRate, ForceWrap); } //! Select the best wrapping option static WrappingConfigPtr SelectWrappingOption(FileHandle InFile, WrappingOption::WrapType ForceWrap = WrappingOption::None) { Rational ForceEditRate(0,0); return SelectWrappingOption(false, InFile, ForceEditRate, ForceWrap); } //! Select the best wrapping option static WrappingConfigPtr SelectWrappingOption(bool AllowMultiples, FileHandle InFile, Rational ForceEditRate, WrappingOption::WrapType ForceWrap = WrappingOption::None); //! Select the best wrapping option static WrappingConfigPtr SelectWrappingOption(bool AllowMultiples, FileHandle InFile, WrappingOption::WrapType ForceWrap = WrappingOption::None) { Rational ForceEditRate(0,0); return SelectWrappingOption(AllowMultiples, InFile, ForceEditRate, ForceWrap); } //! Select the specified wrapping options static void SelectWrappingOption(EssenceParser::WrappingConfigPtr Config); //! Auto select a wrapping option (using the default edit rate) static WrappingConfigPtr SelectWrappingOption(FileHandle InFile) { Rational ForceEditRate(0,0); return SelectWrappingOption(InFile, ForceEditRate); } //! Select a named wrapping option (with a specified edit rate) static WrappingConfigPtr SelectWrappingOption(FileHandle InFile, std::string WrappingName, Rational ForceEditRate); //! Select a named wrapping option (using the default edit rate) static WrappingConfigPtr SelectWrappingOption(FileHandle InFile, std::string WrappingName) { Rational ForceEditRate(0,0); return SelectWrappingOption(InFile, WrappingName, ForceEditRate); } //! Select from a list of named wrapping options (with a specified edit rate) static WrappingConfigPtr SelectWrappingOption(FileHandle InFile, std::list<std::string> WrappingNameList, Rational ForceEditRate); //! Select a named wrapping option (using the default edit rate) static WrappingConfigPtr SelectWrappingOption(FileHandle InFile, std::list<std::string> WrappingNameList) { Rational ForceEditRate(0,0); return SelectWrappingOption(InFile, WrappingNameList, ForceEditRate); } //! Select a UL identified wrapping option (with a specified edit rate) static WrappingConfigPtr SelectWrappingOption(FileHandle InFile, ULPtr &WrappingID, Rational ForceEditRate); //! Select a UL identified wrapping option (using the default edit rate) static WrappingConfigPtr SelectWrappingOption(FileHandle InFile, ULPtr &WrappingID) { Rational ForceEditRate(0,0); return SelectWrappingOption(InFile, WrappingID, ForceEditRate); } //! Select a UL identified wrapping option (with a specified edit rate) static WrappingConfigPtr SelectWrappingOption(FileHandle InFile, ULList &WrappingIDList, Rational ForceEditRate); //! Select a UL identified wrapping option (using the default edit rate) static WrappingConfigPtr SelectWrappingOption(FileHandle InFile, ULList &WrappingIDList) { Rational ForceEditRate(0,0); return SelectWrappingOption(InFile, WrappingIDList, ForceEditRate); } protected: //! Take a list of wrapping options and validate them agains a specified edit rate and wrapping type /*! All valid options are built into a WrappingConfig object and added to a specified WrappingConfigList, * which may already contain other items. */ static void ExtractValidWrappingOptions(WrappingConfigList &Ret, FileHandle InFile, EssenceStreamDescriptorPtr &ESDescriptor, WrappingOptionList &WO, Rational &ForceEditRate, WrappingOption::WrapType ForceWrap); protected: //! Initialise the sub-parser list static void Init(void); }; /* Make top-level versions of EssenceParser::WrappingConfig typedefs */ //! WrappingConfig object at the top level of mxflib typedef EssenceParser::WrappingConfig WrappingConfig; //! Smart pointer to a WrappingConfig object typedef EssenceParser::WrappingConfigPtr WrappingConfigPtr; //! Parent to a WrappingConfig object typedef EssenceParser::WrappingConfigParent WrappingConfigParent; //! List of smart pointers to WrappingConfig objects typedef EssenceParser::WrappingConfigList WrappingConfigList; //! An essence source for sub-streams that slave from a master stream class EssenceSubSource : public EssenceSource { protected: EssenceSourceParent MasterSource; //!< The EssenceSource for the master source WrappingOptionPtr SelectedWrapping; //!< The selected wrapping options public: //! Base constructor EssenceSubSource(EssenceSource *Master = NULL) : MasterSource(Master) {}; //! Virtual destructor to allow polymorphism virtual ~EssenceSubSource() {}; //! Set a new master after construction (useful if the master source is not known at construction time) void SetMaster(EssenceSource *Master) { MasterSource = Master; } //! Get a pointer to the current master source, this may be NULL if it is not yet defined EssenceSource *GetMaster(void) { return MasterSource; } //! Is all data exhasted? /*! \return true if a call to GetEssenceData() will return some valid essence data */ virtual bool EndOfData(void) { if(!MasterSource) return true; return MasterSource->EndOfData(); } //! Get data to write as padding after all real essence data has been processed /*! If more than one stream is being wrapped, they may not all end at the same wrapping-unit. * When this happens each source that has ended will produce NULL is response to GetEssenceData(). * The default action of the caller would be to write zero-length KLVs in each wrapping unit for each source that has ended. * If a source supplies an overload for this method, the supplied padding data will be written in wrapping units following the end of essence instead of a zero-length KLV * DRAGONS: Note that as the returned value is a non-smart pointer, ownership of the buffer stays with the EssenceSource object. * The recommended method of operation is to have a member DataChunk (or DataChunkPtr) allocated the first time padding is required, and return the address each call. * The destructor must then free the DataChunk, or allow the smart DataChunkPtr to do it automatically */ virtual DataChunk *GetPadding(void) { return NULL; } //! Get the edit rate of this wrapping of the essence /*! \note This may not be the same as the original "native" edit rate of the * essence if this EssenceSource is wrapping to a different edit rate */ virtual Rational GetEditRate(void) { if(!MasterSource) return Rational(1,1); return MasterSource->GetEditRate(); } //! Determine if this sub-source can slave from a source with the given wrapping configuration, if so build the sub-config /*! \return A smart pointer to the new WrappingConfig for this source as a sub-stream of the specified master, or NULL if not a valid combination */ virtual EssenceParser::WrappingConfigPtr MakeWrappingConfig(WrappingConfigPtr MasterCfg) = 0; //! Configure this sub-source to use the specified wrapping options virtual void Use(WrappingOptionPtr WrapOpt) { SelectedWrapping = WrapOpt; } }; } namespace mxflib { //! Base class for handlers to receive notification of the next file about to be opened class NewFileHandler : public RefCount<NewFileHandler> { public: virtual ~NewFileHandler() {}; //! Receive notification of a new file about to be opened /*! \param FileName - reference to a std::string containing the name of the file about to be opened - <b>may be changed by this function if required</b> */ virtual void NewFile(std::string &FileName) = 0; }; //! Smart pointer to a NewFileHandler typedef SmartPtr<NewFileHandler> NewFileHandlerPtr; // Forware declare the file parser class FileParser; //! Smart pointer to a FileParser typedef SmartPtr<FileParser> FileParserPtr; //! List-of-files base class for handling a sequential set of files class ListOfFiles { protected: NewFileHandlerPtr Handler; //!< Handler to be informed of new filenames std::string RawFileName; //!< The raw filename given to start the list (excluding any prepended ! or anything from the first & onwards) std::string BaseFileName; //!< Base filename as a printf string std::list<std::string> FollowingNames; //!< Names to be processed next bool FileList; //!< True if this is a multi-file set rather than a single file (or if a range is in use) int ListOrigin; //!< Start number for filename building int ListIncrement; //!< Number to add to ListOrigin for each new file int ListNumber; //!< The number of files in the list or -1 for "end when no more files" int ListEnd; //!< The last file number in the list or -1 for "end when no more files" int FileNumber; //!< The file number to use for the <b>next</b> source file to open int FilesRemaining; //!< The number of files remaining in the list or -1 for "end when no more files" bool AtEOF; //!< True once the last file has hit it's end of file std::string CurrentFileName; //!< The name of the current file (if open) bool ExternalEssence; //!< True if this essence has been flagged to remain external (filename prepended with "!") std::string Options; //!< A list of options to send to the parser Position RangeStart; //!< The requested first edit unit, or -1 if none specified Position RangeEnd; //!< The requested last edit unit, or -1 if using RequestedDuration Length RangeDuration; //!< The requested duration, or -1 if using RequestedEnd public: //! Construct a ListOfFiles and optionally set a single source filename pattern ListOfFiles(std::string FileName = "") : ExternalEssence(false), RangeStart(-1), RangeEnd(-1), RangeDuration(-1) { AtEOF = false; // Set the filename pattern if required if(FileName.size()) { ParseFileName(FileName); } else { BaseFileName = ""; FileList = false; } } //! Virtual destructor to allow polymorphism virtual ~ListOfFiles() {} //! Set a single source filename pattern void SetFileName(std::string &FileName) { FollowingNames.clear(); ParseFileName(FileName); } //! Get the raw filename as used by SetFileName (excluding any prepended ! or anything from the first & onwards) /*! DRAGONS: This is not a full description of all files in the list */ std::string GetRawFileName(void) const { return RawFileName; } //! Get a copy of the parser options string std::string GetOptions(void) const { return Options; } //! Add a source filename pattern void AddFileName(std::string &FileName) { if(BaseFileName.empty()) { ParseFileName(FileName); } else { FollowingNames.push_back(FileName); } } //! Set a handler to receive notification of all file open actions void SetNewFileHandler(NewFileHandlerPtr &NewHandler) { Handler = NewHandler; } //! Set a handler to receive notification of all file open actions void SetNewFileHandler(NewFileHandler *NewHandler) { Handler = NewHandler; } //! Get the start of any range specified, or -1 if none Position GetRangeStart(void) const { return RangeStart; } //! Get the end of any range specified, or -1 if none Position GetRangeEnd(void) const { return RangeEnd; } //! Get the duration of any range specified, or -1 if none Position GetRangeDuration(void) const { return RangeDuration; } //! Get the current filename std::string FileName(void) { return CurrentFileName; } //! Open the current file (any new-file handler will already have been called) /*! This function must be supplied by the derived class * \return true if file open succeeded */ virtual bool OpenFile(void) = 0; //! Close the current file /*! This function must be supplied by the derived class */ virtual void CloseFile(void) = 0; //! Is the current file open? /*! This function must be supplied by the derived class */ virtual bool IsFileOpen(void) = 0; //! Is the current filename pattern a list rather than a single file? bool IsFileList(void) { return FileList; } //! Open the next file in the set of source files /*! \return true if all OK, false if no file or error */ bool GetNextFile(void); //! Has this essence been flagged to remain external (filename prepended with "!") bool IsExternal(void) { return ExternalEssence; } protected: //! Parse a given multi-file name void ParseFileName(std::string FileName); //! Process an ampersand separated list of sub-file names virtual void ProcessSubNames(std::string SubNames) {}; }; //! Filter-style source that extracts a range from another EssenceSource /*! DRAGONS: This source owns its source, so will keep it alive while we exist * \note This filter will only work if the original source is configured to produce an edit unit at a time */ class RangedEssenceSource : public EssenceSource { protected: EssenceSourcePtr Base; //!< The source being filtered Position CurrentPosition; //!< The current position, stream relative not range relative Position RequestedStart; //!< The requested first edit unit Position RequestedEnd; //!< The requested last edit unit, or -1 if using RequestedDuration Length RequestedDuration; //!< The requested duration, or -1 if using RequestedEnd bool Started; //!< Set true once we have skipped the edit units before any pre-charge bool Ending; //!< Set true once beyond the end of the range, but not necessarily done with the overrun bool Ended; //!< Set true once the overrun is done Position PreChargeStart; //!< The first edit unit in any pre-charge DataChunkList PreCharge; //!< Buffers of pre-charge essence DataChunkPtr FirstData; //!< The first edit unit following any pre-charge (as we will need to read it to check the pre-charge size) private: //! Prevent a default constructor RangedEssenceSource(); //! Prevent copy construction RangedEssenceSource(const RangedEssenceSource &); public: // Base constructor RangedEssenceSource(EssenceSourcePtr Base, Position Start, Position End, Length Duration) : EssenceSource(), Base(Base), CurrentPosition(0), RequestedStart(Start), RequestedEnd(End), RequestedDuration(Duration), Started(false), Ending(false), Ended(false), PreChargeStart(-1) {}; //! Virtual destructor to allow polymorphism virtual ~RangedEssenceSource() { }; //! Get the size of the essence data in bytes /*! \note There is intentionally no support for an "unknown" response */ virtual size_t GetEssenceDataSize(void); //! Get the next "installment" of essence data /*! This will attempt to return an entire wrapping unit (e.g. a full frame for frame-wrapping) but will return it in * smaller chunks if this would break the MaxSize limit. If a Size is specified then the chunk returned will end at * the first wrapping unit end encountered before Size. On no account will portions of two or more different wrapping * units be returned together. The mechanism for selecting a type of wrapping (e.g. frame, line or clip) is not * (currently) part of the common EssenceSource interface. * \return Pointer to a data chunk holding the next data or a NULL pointer when no more remains * \note If there is more data to come but it is not currently available the return value will be a pointer to an empty data chunk * \note If Size = 0 the object will decide the size of the chunk to return * \note On no account will the returned chunk be larger than MaxSize (if MaxSize > 0) */ virtual DataChunkPtr GetEssenceData(size_t Size = 0, size_t MaxSize = 0); //! Did the last call to GetEssenceData() return the end of a wrapping item /*! \return true if the last call to GetEssenceData() returned an entire wrapping unit. * \return true if the last call to GetEssenceData() returned the last chunk of a wrapping unit. * \return true if the last call to GetEssenceData() returned the end of a clip-wrapped clip. * \return false if there is more data pending for the current wrapping unit. * \return false if the source is to be clip-wrapped and there is more data pending for the clip */ virtual bool EndOfItem(void) { return Base->EndOfItem(); } //! Is all data exhasted? /*! \return true if a call to GetEssenceData() will return some valid essence data */ virtual bool EndOfData(void) { if(Ended) return true; return Base->EndOfData(); } //! Get data to write as padding after all real essence data has been processed /*! If more than one stream is being wrapped, they may not all end at the same wrapping-unit. * When this happens each source that has ended will produce NULL is response to GetEssenceData(). * The default action of the caller would be to write zero-length KLVs in each wrapping unit for each source that has ended. * If a source supplies an overload for this method, the supplied padding data will be written in wrapping units following the end of essence instead of a zero-length KLV * DRAGONS: Note that as the returned value is a non-smart pointer, ownership of the buffer stays with the EssenceSource object. * The recommended method of operation is to have a member DataChunk (or DataChunkPtr) allocated the first time padding is required, and return the address each call. * The destructor must then free the DataChunk, or allow the smart DataChunkPtr to do it automatically */ virtual DataChunk *GetPadding(void) { return Base->GetPadding(); } //! Get the GCEssenceType to use when wrapping this essence in a Generic Container virtual UInt8 GetGCEssenceType(void) { return Base->GetGCEssenceType(); } //! Get the GCEssenceType to use when wrapping this essence in a Generic Container virtual UInt8 GetGCElementType(void) { return Base->GetGCElementType(); } //! Is the last data read the start of an edit point? virtual bool IsEditPoint(void) { return Base->IsEditPoint(); } //! Get the edit rate of this wrapping of the essence /*! \note This may not be the same as the original "native" edit rate of the * essence if this EssenceSource is wrapping to a different edit rate */ virtual Rational GetEditRate(void) { return Base->GetEditRate(); } //! Get the current position in GetEditRate() sized edit units /*! This is relative to the start of the stream, so the first edit unit is always 0. * This is the same as the number of edit units read so far, so when the essence is * exhausted the value returned shall be the size of the essence */ virtual Position GetCurrentPosition(void) { return CurrentPosition - RequestedStart; } //! Get the preferred BER length size for essence KLVs written from this source, 0 for auto virtual int GetBERSize(void) { return Base->GetBERSize(); } //! Set a source type or parser specific option /*! \return true if the option was successfully set */ virtual bool SetOption(std::string Option, Int64 Param = 0) { return Base->SetOption(Option, Param); } ; //! Get BytesPerEditUnit if Constant, else 0 /*! \note This value may be useful even if CanIndex() returns false */ virtual UInt32 GetBytesPerEditUnit(UInt32 KAGSize = 1) { return Base->GetBytesPerEditUnit(KAGSize); } //! Can this stream provide indexing /*! If true then SetIndex Manager can be used to set the index manager that will receive indexing data */ virtual bool CanIndex() { return Base->CanIndex(); } //! Set the index manager to use for building index tables for this essence virtual void SetIndexManager(IndexManagerPtr &Manager, int StreamID) { Base->SetIndexManager(Manager, StreamID); } //! Get the index manager virtual IndexManagerPtr &GetIndexManager(void) { return Base->GetIndexManager(); } //! Get the index manager sub-stream ID virtual int GetIndexStreamID(void) { return Base->GetIndexStreamID(); } //! Override the default essence key virtual void SetKey(DataChunkPtr &Key, bool NonGC = false) { Base->SetKey(Key, NonGC); } //! Get the current overridden essence key /*! DRAGONS: If the key has not been overridden NULL will be returned - not the default key * \note Defined EssenceSource sub-classes may always use a non-standard key, in which case * they will always return a non-NULL value from this function */ virtual DataChunkPtr &GetKey(void) { return Base->GetKey(); } //! Get true if the default essence key has been overriden with a key that does not use GC track number mechanism /* \note Defined EssenceSource sub-classes may always use a non-GC-type key, in which case * they will always return true from this function */ virtual bool GetNonGC(void) { return Base->GetNonGC(); } /* Essence type identification */ /* These functions can be overwridden, or use the base versions to parse GetGCEssenceType() */ //! Is this picture essence? virtual bool IsPictureEssence(void) { return Base->IsPictureEssence(); } //! Is this sound essence? virtual bool IsSoundEssence(void) { return Base->IsSoundEssence(); } //! Is this data essence? virtual bool IsDataEssence(void) { return Base->IsDataEssence(); } //! Is this compound essence? virtual bool IsCompoundEssence(void) { return Base->IsCompoundEssence(); } //! An indication of the relative write order to use for this stream /*! Normally streams in a GC are ordered as follows: * - All the CP system items (in Scheme ID then Element ID order) * - All the GC system items (in Scheme ID then Element ID order) * - All the CP picture items (in Element ID then Element Number order) * - All the GC picture items (in Element ID then Element Number order) * - All the CP sound items (in Element ID then Element Number order) * - All the GC sound items (in Element ID then Element Number order) * - All the CP data items (in Element ID then Element Number order) * - All the GC data items (in Element ID then Element Number order) * - All the GC compound items (in Element ID then Element Number order) (no GC compound) * * However, sometimes this order needs to be overridden - such as for VBI data preceding picture items. * * The normal case for ordering of an essence stream is for RelativeWriteOrder to return 0, * indicating that the default ordering is to be used. Any other value indicates that relative * ordering is required, and this is used as the Position value for a SetRelativeWriteOrder() * call. The value of Type for that call is acquired from RelativeWriteOrderType() * * For example: to force a source to be written between the last GC sound item and the first CP data * item, RelativeWriteOrder() can return any -ve number, with RelativeWriteOrderType() * returning 0x07 (meaning before CP data). Alternatively RelativeWriteOrder() could * return a +ve number and RelativeWriteOrderType() return 0x16 (meaning after GC sound) */ virtual Int32 RelativeWriteOrder(void) { return Base->RelativeWriteOrder(); } //! The type for relative write-order positioning if RelativeWriteOrder() != 0 /*! This method indicates the essence type to order this data before or after if reletive write-ordering is used */ virtual int RelativeWriteOrderType(void) { return Base->RelativeWriteOrderType(); } //! Get the origin value to use for this essence specifically to take account of pre-charge /*! \return Zero if not applicable for this source */ virtual Length GetPrechargeSize(void) { if(!Started) LocateStart(); return static_cast<Length>(RequestedStart - PreChargeStart); } //! Get the range start position virtual Position GetRangeStart(void) { return RequestedStart; } //! Get the range end position virtual Position GetRangeEnd(void) { return RequestedEnd; } //! Get the range duration virtual Length GetRangeDuration(void) { return RequestedDuration; } //! Get the name of this essence source (used for error messeges) virtual std::string Name(void) { return "RangedEssenceSource based on " + Base->Name(); } //! Enable VBR indexing, even in clip-wrap mode, by allowing each edit unit to be returned individually /*! As the byte offset part of a VBR index table is constructed at write-time each indexed chunk must be written separately. * When clip-wrapping, this is not normally the case as larger chunks may be returned for efficiency. Setting this mode * forces each indexable edit unit to be returned by a fresh GetEssenceData call as if it were being frame-wrapped. * \return true if this mode is supported by the source, and the mode was set, else false */ virtual bool EnableVBRIndexMode(void) { return Base->EnableVBRIndexMode(); } protected: //! Locate the first usable edit unit, and if required set the end edit unit virtual void LocateStart(void); // Allow our very close relation to get even closer friend class RangedEssenceSubSource; }; //! Filter-style source that slaves to a RangedEssenceSource to stop parsing when the range is done /*! DRAGONS: This source owns its source, so will keep it alive while we exist * \note This filter will only work if the original source is configured to produce an edit unit at a time */ class RangedEssenceSubSource : public EssenceSubSource { protected: EssenceSourcePtr Base; //!< The source being filtered Position RequestedStart; //!< The requested first edit unit Position RequestedEnd; //!< The requested last edit unit, or -1 if using RequestedDuration Length RequestedDuration; //!< The requested duration, or -1 if using RequestedEnd bool Started; //!< Set true once we are ready to start reading bool Ended; //!< Set true once the range is done private: //! Prevent a default constructor RangedEssenceSubSource(); //! Prevent copy construction RangedEssenceSubSource(const RangedEssenceSource &); public: // Base constructor RangedEssenceSubSource(EssenceSourcePtr Base, Position Start, Position End, Length Duration) : Base(Base), RequestedStart(Start), RequestedEnd(End), RequestedDuration(Duration), Started(false), Ended(false) {}; //! Virtual destructor to allow polymorphism virtual ~RangedEssenceSubSource() { }; //! Get the size of the essence data in bytes /*! \note There is intentionally no support for an "unknown" response */ virtual size_t GetEssenceDataSize(void); //! Get the next "installment" of essence data /*! This will attempt to return an entire wrapping unit (e.g. a full frame for frame-wrapping) but will return it in * smaller chunks if this would break the MaxSize limit. If a Size is specified then the chunk returned will end at * the first wrapping unit end encountered before Size. On no account will portions of two or more different wrapping * units be returned together. The mechanism for selecting a type of wrapping (e.g. frame, line or clip) is not * (currently) part of the common EssenceSource interface. * \return Pointer to a data chunk holding the next data or a NULL pointer when no more remains * \note If there is more data to come but it is not currently available the return value will be a pointer to an empty data chunk * \note If Size = 0 the object will decide the size of the chunk to return * \note On no account will the returned chunk be larger than MaxSize (if MaxSize > 0) */ virtual DataChunkPtr GetEssenceData(size_t Size = 0, size_t MaxSize = 0); //! Did the last call to GetEssenceData() return the end of a wrapping item /*! \return true if the last call to GetEssenceData() returned an entire wrapping unit. * \return true if the last call to GetEssenceData() returned the last chunk of a wrapping unit. * \return true if the last call to GetEssenceData() returned the end of a clip-wrapped clip. * \return false if there is more data pending for the current wrapping unit. * \return false if the source is to be clip-wrapped and there is more data pending for the clip */ virtual bool EndOfItem(void) { return Base->EndOfItem(); } //! Is all data exhasted? /*! \return true if a call to GetEssenceData() will return some valid essence data */ virtual bool EndOfData(void) { if(Ended) return true; return Base->EndOfData(); } //! Get data to write as padding after all real essence data has been processed /*! If more than one stream is being wrapped, they may not all end at the same wrapping-unit. * When this happens each source that has ended will produce NULL is response to GetEssenceData(). * The default action of the caller would be to write zero-length KLVs in each wrapping unit for each source that has ended. * If a source supplies an overload for this method, the supplied padding data will be written in wrapping units following the end of essence instead of a zero-length KLV * DRAGONS: Note that as the returned value is a non-smart pointer, ownership of the buffer stays with the EssenceSource object. * The recommended method of operation is to have a member DataChunk (or DataChunkPtr) allocated the first time padding is required, and return the address each call. * The destructor must then free the DataChunk, or allow the smart DataChunkPtr to do it automatically */ virtual DataChunk *GetPadding(void) { return Base->GetPadding(); } //! Get the GCEssenceType to use when wrapping this essence in a Generic Container virtual UInt8 GetGCEssenceType(void) { return Base->GetGCEssenceType(); } //! Get the GCEssenceType to use when wrapping this essence in a Generic Container virtual UInt8 GetGCElementType(void) { return Base->GetGCElementType(); } //! Is the last data read the start of an edit point? virtual bool IsEditPoint(void) { return Base->IsEditPoint(); } //! Get the edit rate of this wrapping of the essence /*! \note This may not be the same as the original "native" edit rate of the * essence if this EssenceSource is wrapping to a different edit rate */ virtual Rational GetEditRate(void) { return Base->GetEditRate(); } //! Get the current position in GetEditRate() sized edit units /*! This is relative to the start of the stream, so the first edit unit is always 0. * This is the same as the number of edit units read so far, so when the essence is * exhausted the value returned shall be the size of the essence */ virtual Position GetCurrentPosition(void) { return Base->GetCurrentPosition() - RequestedStart; } //! Get the preferred BER length size for essence KLVs written from this source, 0 for auto virtual int GetBERSize(void) { return Base->GetBERSize(); } //! Set a source type or parser specific option /*! \return true if the option was successfully set */ virtual bool SetOption(std::string Option, Int64 Param = 0) { return Base->SetOption(Option, Param); } ; //! Get BytesPerEditUnit if Constant, else 0 /*! \note This value may be useful even if CanIndex() returns false */ virtual UInt32 GetBytesPerEditUnit(UInt32 KAGSize = 1) { return Base->GetBytesPerEditUnit(KAGSize); } //! Can this stream provide indexing /*! If true then SetIndex Manager can be used to set the index manager that will receive indexing data */ virtual bool CanIndex() { return Base->CanIndex(); } //! Set the index manager to use for building index tables for this essence virtual void SetIndexManager(IndexManagerPtr &Manager, int StreamID) { Base->SetIndexManager(Manager, StreamID); } //! Get the index manager virtual IndexManagerPtr &GetIndexManager(void) { return Base->GetIndexManager(); } //! Get the index manager sub-stream ID virtual int GetIndexStreamID(void) { return Base->GetIndexStreamID(); } //! Override the default essence key virtual void SetKey(DataChunkPtr &Key, bool NonGC = false) { Base->SetKey(Key, NonGC); } //! Get the current overridden essence key /*! DRAGONS: If the key has not been overridden NULL will be returned - not the default key * \note Defined EssenceSource sub-classes may always use a non-standard key, in which case * they will always return a non-NULL value from this function */ virtual DataChunkPtr &GetKey(void) { return Base->GetKey(); } //! Get true if the default essence key has been overriden with a key that does not use GC track number mechanism /* \note Defined EssenceSource sub-classes may always use a non-GC-type key, in which case * they will always return true from this function */ virtual bool GetNonGC(void) { return Base->GetNonGC(); } /* Essence type identification */ /* These functions can be overwridden, or use the base versions to parse GetGCEssenceType() */ //! Is this picture essence? virtual bool IsPictureEssence(void) { return Base->IsPictureEssence(); } //! Is this sound essence? virtual bool IsSoundEssence(void) { return Base->IsSoundEssence(); } //! Is this data essence? virtual bool IsDataEssence(void) { return Base->IsDataEssence(); } //! Is this compound essence? virtual bool IsCompoundEssence(void) { return Base->IsCompoundEssence(); } //! An indication of the relative write order to use for this stream /*! Normally streams in a GC are ordered as follows: * - All the CP system items (in Scheme ID then Element ID order) * - All the GC system items (in Scheme ID then Element ID order) * - All the CP picture items (in Element ID then Element Number order) * - All the GC picture items (in Element ID then Element Number order) * - All the CP sound items (in Element ID then Element Number order) * - All the GC sound items (in Element ID then Element Number order) * - All the CP data items (in Element ID then Element Number order) * - All the GC data items (in Element ID then Element Number order) * - All the GC compound items (in Element ID then Element Number order) (no GC compound) * * However, sometimes this order needs to be overridden - such as for VBI data preceding picture items. * * The normal case for ordering of an essence stream is for RelativeWriteOrder to return 0, * indicating that the default ordering is to be used. Any other value indicates that relative * ordering is required, and this is used as the Position value for a SetRelativeWriteOrder() * call. The value of Type for that call is acquired from RelativeWriteOrderType() * * For example: to force a source to be written between the last GC sound item and the first CP data * item, RelativeWriteOrder() can return any -ve number, with RelativeWriteOrderType() * returning 0x07 (meaning before CP data). Alternatively RelativeWriteOrder() could * return a +ve number and RelativeWriteOrderType() return 0x16 (meaning after GC sound) */ virtual Int32 RelativeWriteOrder(void) { return Base->RelativeWriteOrder(); } //! The type for relative write-order positioning if RelativeWriteOrder() != 0 /*! This method indicates the essence type to order this data before or after if reletive write-ordering is used */ virtual int RelativeWriteOrderType(void) { return Base->RelativeWriteOrderType(); } //! Get the origin value to use for this essence specifically to take account of pre-charge /*! \return Zero if not applicable for this source */ virtual Length GetPrechargeSize(void) { return 0; } //! Get the range start position virtual Position GetRangeStart(void) { return RequestedStart; } //! Get the range end position virtual Position GetRangeEnd(void) { return RequestedEnd; } //! Get the range duration virtual Length GetRangeDuration(void) { return RequestedDuration; } //! Get the name of this essence source (used for error messeges) virtual std::string Name(void) { return "RangedEssenceSubSource based on " + Base->Name(); } //! Enable VBR indexing, even in clip-wrap mode, by allowing each edit unit to be returned individually /*! As the byte offset part of a VBR index table is constructed at write-time each indexed chunk must be written separately. * When clip-wrapping, this is not normally the case as larger chunks may be returned for efficiency. Setting this mode * forces each indexable edit unit to be returned by a fresh GetEssenceData call as if it were being frame-wrapped. * \return true if this mode is supported by the source, and the mode was set, else false */ virtual bool EnableVBRIndexMode(void) { return Base->EnableVBRIndexMode(); } //! Determine if this sub-source can slave from a source with the given wrapping configuration, if so build the sub-config /*! \return A smart pointer to the new WrappingConfig for this source as a sub-stream of the specified master, or NULL if not a valid combination */ virtual EssenceParser::WrappingConfigPtr MakeWrappingConfig(WrappingConfigPtr MasterCfg) { EssenceSubSource *SubSource = SmartPtr_Cast(Base, EssenceSubSource); if(SubSource) return SubSource->MakeWrappingConfig(MasterCfg); return NULL; } protected: //! Locate the first usable edit unit, and if required set the end edit unit virtual void LocateStart(void); }; //! File parser - parse essence from a sequential set of files class FileParser : public ListOfFiles, public RefCount<FileParser> { protected: bool CurrentFileOpen; //!< True if we have a file open for processing FileHandle CurrentFile; //!< The current file being processed EssenceSubParserPtr SubParser; //!< The sub-parser selected for parsing this sourceessence UInt32 CurrentStream; //!< The currently selected stream in the source essence MDObjectPtr CurrentDescriptor; //!< Pointer to the essence descriptor for the currently selected stream WrappingOptionPtr CurrentWrapping; //!< The currently selected wrapping options EssenceSourceParent SeqSource; //!< This parser's sequential source - which perversely owns the parser! //! The essence descriptor describing this essence (if known) else NULL MDObjectPtr EssenceDescriptor; DataChunkPtr PendingData; //!< Any pending data from the main stream held over from a previous file if a sub-stream read caused a change of file //! Information about a substream struct SubStreamInfo { UInt32 StreamID; //!< The ID of this sub-stream bool Attached; //!< True for independant sub-streams attached via AddSubStream(), false for sub-streams extracted by the underlying essence parser EssenceSourcePtr Source; //!< The source for the sub-stream data }; //! A list of sub-stream sources, with associated properties typedef std::list<SubStreamInfo> SubStreamList; SubStreamList SubStreams; //!< A list of sub-stream sources public: //! Construct a FileParser and optionally set a single source filename pattern FileParser(std::string FileName = "") : ListOfFiles() { // Let our sequential source know who we are SeqSource = new SequentialEssenceSource(this); CurrentFileOpen = false; // DRAGONS: We have to get our base class to parse the filename here as doing this in the // initializer list prevents polymorphism so the wrong ProcessSubName() is called // DRAGONS: Note also that we must do this after SeqSource is added as it is required to add sub-sources ParseFileName(FileName); } //! Clean up when we are destroyed ~FileParser() { if(CurrentFileOpen && FileValid(CurrentFile)) FileClose(CurrentFile); } //! Identify the essence type in the first file in the set of possible files ParserDescriptorListPtr IdentifyEssence(void); //! Produce a list of available wrapping options EssenceParser::WrappingConfigList ListWrappingOptions(bool AllowMultiples, ParserDescriptorListPtr PDList, WrappingOption::WrapType ForceWrap = WrappingOption::None) { Rational Zero(0,0); return ListWrappingOptions(AllowMultiples, PDList, Zero, ForceWrap); } //! Produce a list of available wrapping options EssenceParser::WrappingConfigList ListWrappingOptions(ParserDescriptorListPtr PDList, WrappingOption::WrapType ForceWrap = WrappingOption::None) { Rational Zero(0,0); return ListWrappingOptions(false, PDList, Zero, ForceWrap); } //! Produce a list of available wrapping options EssenceParser::WrappingConfigList ListWrappingOptions(bool AllowMultiples, ParserDescriptorListPtr PDList, Rational ForceEditRate, WrappingOption::WrapType ForceWrap = WrappingOption::None); //! Produce a list of available wrapping options EssenceParser::WrappingConfigList ListWrappingOptions(ParserDescriptorListPtr PDList, Rational ForceEditRate, WrappingOption::WrapType ForceWrap = WrappingOption::None) { return ListWrappingOptions(false, PDList, ForceEditRate, ForceWrap); } //! Select the best wrapping option without a forced edit rate EssenceParser::WrappingConfigPtr SelectWrappingOption(ParserDescriptorListPtr PDList, UInt32 KAGSize, WrappingOption::WrapType ForceWrap = WrappingOption::None) { Rational Zero(0,0); return SelectWrappingOption(false, PDList, Zero, KAGSize, ForceWrap); } //! Select the best wrapping option with a forced edit rate EssenceParser::WrappingConfigPtr SelectWrappingOption(ParserDescriptorListPtr PDList, Rational ForceEditRate, UInt32 KAGSize = 1, WrappingOption::WrapType ForceWrap = WrappingOption::None) { return SelectWrappingOption(false, PDList, ForceEditRate, KAGSize, ForceWrap); } //! Select the best wrapping option without a forced edit rate EssenceParser::WrappingConfigPtr SelectWrappingOption(bool AllowMultiples, ParserDescriptorListPtr PDList, UInt32 KAGSize, WrappingOption::WrapType ForceWrap = WrappingOption::None) { Rational Zero(0,0); return SelectWrappingOption(AllowMultiples, PDList, Zero, KAGSize, ForceWrap); } //! Select the best wrapping option with a forced edit rate EssenceParser::WrappingConfigPtr SelectWrappingOption(bool AllowMultiples, ParserDescriptorListPtr PDList, Rational ForceEditRate, WrappingOption::WrapType ForceWrap = WrappingOption::None) { return SelectWrappingOption(AllowMultiples, PDList, ForceEditRate, 1, ForceWrap); } //! Select the best wrapping option with a forced edit rate EssenceParser::WrappingConfigPtr SelectWrappingOption(bool AllowMultiples, ParserDescriptorListPtr PDList, Rational ForceEditRate, UInt32 KAGSize, WrappingOption::WrapType ForceWrap = WrappingOption::None); //! Select the specified wrapping options void SelectWrappingOption(EssenceParser::WrappingConfigPtr Config); //! Set a wrapping option for this essence /*! IdentifyEssence() and IdentifyWrappingOptions() must have been called first */ void Use(UInt32 Stream, WrappingOptionPtr &UseWrapping); //! Set a non-native edit rate /*! \return true if this rate is acceptable */ virtual bool SetEditRate(Rational EditRate); //! Return the sequential EssenceSource for the main stream (already aquired internally, so no need to use the stream ID) EssenceSourcePtr GetEssenceSource(UInt32 Stream); //! Build an EssenceSource to read from the specified sub-stream EssenceSourcePtr GetSubSource(UInt32 Stream); //! Open the current file (any new-file handler will already have been called) /*! Required for ListOfFiles * \return true if file open succeeded */ bool OpenFile(void) { CurrentFile = FileOpenRead(CurrentFileName.c_str()); CurrentFileOpen = FileValid(CurrentFile); return CurrentFileOpen; } //! Close the current file /*! Required for ListOfFiles */ void CloseFile(void) { if(CurrentFileOpen) FileClose(CurrentFile); CurrentFileOpen = false; } //! Is the current file open? /*! Required for ListOfFiles */ bool IsFileOpen(void) { return CurrentFileOpen; } //! Add a sub-source that will be processed as if it contains data extracted from the primary source UInt32 AddSubSource(EssenceSubSource *SubSource); //! Set the essence descriptor virtual void SetDescriptor(MDObjectPtr Descriptor) { EssenceDescriptor = Descriptor; if(SeqSource) SeqSource->SetDescriptor(Descriptor); } //! Get a pointer to the essence descriptor for this source (if known) otherwise NULL virtual MDObjectPtr GetDescriptor(void) { return EssenceDescriptor; } protected: //! Set the sequential source to use the EssenceSource from the currently open and identified source file /*! \return true if all OK, false if no EssenceSource available */ bool GetFirstSource(void); //! Set the sequential source to use an EssenceSource from the next available source file /*! \return true if all OK, false if no EssenceSource available */ bool GetNextSource(void); //! Essence Source that manages a sequence of essence sources from a list of file patterns class SequentialEssenceSource : public EssenceSource { protected: EssenceSourcePtr CurrentSource; //!< An EssenceSource for the current source file FileParserPtr Outer; //!< The outer file parser which is owned by us to prevent it being released until be are done Length PreviousLength; //!< The total size of all previously read essence sources for this set bool VBRIndexMode; //!< Are we needing to use VBRIndexMode for this essence? //! Option pair for OptionList typedef std::pair<std::string, Int64> OptionPair; //! List of all options set for this source std::list<OptionPair> OptionList; //! Prevent default construction SequentialEssenceSource(); public: //! Construct a SequentialEssenceSource SequentialEssenceSource(FileParser *Outer) : Outer(Outer), PreviousLength(0), VBRIndexMode(false) {} //! Set the new source to use void SetSource(EssenceSourcePtr NewSource) { if(Outer->GetRangeStart() == -1) { CurrentSource = NewSource; } else { /* Process ranged source */ CurrentSource = new RangedEssenceSource(NewSource, Outer->GetRangeStart(), Outer->GetRangeEnd(), Outer->GetRangeDuration()); } // Set all options std::list<OptionPair>::iterator it = OptionList.begin(); while(it != OptionList.end()) { NewSource->SetOption((*it).first, (*it).second); it++; } // Set the index manager if(IndexMan) NewSource->SetIndexManager(IndexMan, IndexStreamID); } //! Get the size of the essence data in bytes virtual size_t GetEssenceDataSize(void) { if(!ValidSource()) return 0; // If we have emptied all files then exit now if(Outer->AtEOF) return 0; size_t Ret = CurrentSource->GetEssenceDataSize(); // If no more data move to the next source file if(!Ret) { // Work out how much was read from this file Length CurrentSize = (Length)CurrentSource->GetCurrentPosition(); if(Outer->GetNextSource()) { // Add this length to the previous lengths PreviousLength += CurrentSize; return GetEssenceDataSize(); } } // Return the source size return Ret; } //! Get the next "installment" of essence data virtual DataChunkPtr GetEssenceData(size_t Size = 0, size_t MaxSize = 0); //! Did the last call to GetEssenceData() return the end of a wrapping item virtual bool EndOfItem(void) { if(ValidSource()) return CurrentSource->EndOfItem(); else return true; } //! Is all data exhasted? virtual bool EndOfData(void) { if(ValidSource()) return CurrentSource->EndOfData(); else return true; } //! Get data to write as padding after all real essence data has been processed /*! If more than one stream is being wrapped, they may not all end at the same wrapping-unit. * When this happens each source that has ended will produce NULL is response to GetEssenceData(). * The default action of the caller would be to write zero-length KLVs in each wrapping unit for each source that has ended. * If a source supplies an overload for this method, the supplied padding data will be written in wrapping units following the end of essence instead of a zero-length KLV * DRAGONS: Note that as the returned value is a non-smart pointer, ownership of the buffer stays with the EssenceSource object. * The recommended method of operation is to have a member DataChunk (or DataChunkPtr) allocated the first time padding is required, and return the address each call. * The destructor must then free the DataChunk, or allow the smart DataChunkPtr to do it automatically */ virtual DataChunk *GetPadding(void) { if(ValidSource()) return CurrentSource->GetPadding(); else return NULL; } //! Get the GCEssenceType to use when wrapping this essence in a Generic Container virtual UInt8 GetGCEssenceType(void) { if(ValidSource()) return CurrentSource->GetGCEssenceType(); else return 0; } //! Get the GCEssenceType to use when wrapping this essence in a Generic Container virtual UInt8 GetGCElementType(void) { if(ValidSource()) return CurrentSource->GetGCElementType(); else return 0; } //! Is the last data read the start of an edit point? virtual bool IsEditPoint(void) { if(ValidSource()) return CurrentSource->IsEditPoint(); else return true; } //! Get the edit rate of this wrapping of the essence virtual Rational GetEditRate(void) { if(ValidSource()) return CurrentSource->GetEditRate(); else return Rational(0,0); } //! Get the current position in GetEditRate() sized edit units virtual Position GetCurrentPosition(void) { if(!ValidSource()) return 0; return CurrentSource->GetCurrentPosition() + (Position)PreviousLength; } //! Get the preferred BER length size for essence KLVs written from this source, 0 for auto virtual int GetBERSize(void) { if(!ValidSource()) return 0; return CurrentSource->GetBERSize(); } //! Set a source type or parser specific option virtual bool SetOption(std::string Option, Int64 Param = 0) { if(!ValidSource()) return false; // Record this option to allow us to reconfigure sources if we switch source OptionList.push_back(OptionPair(Option, Param)); return CurrentSource->SetOption(Option, Param); } //! Get BytesPerEditUnit if Constant, else 0 virtual UInt32 GetBytesPerEditUnit(UInt32 KAGSize = 1) { if(ValidSource()) return CurrentSource->GetBytesPerEditUnit(KAGSize); else return 0; } //! Can this stream provide indexing virtual bool CanIndex() { if(ValidSource()) return CurrentSource->CanIndex(); else return false; } //! Set the index manager to use for building index tables for this essence virtual void SetIndexManager(IndexManagerPtr &Manager, int StreamID) { IndexMan = Manager; IndexStreamID = StreamID; if(ValidSource()) CurrentSource->SetIndexManager(Manager, StreamID); } //! Get the index manager virtual IndexManagerPtr &GetIndexManager(void) { return IndexMan; } //! Get the index manager sub-stream ID virtual int GetIndexStreamID(void) { return IndexStreamID; } //! Get the origin value to use for this essence specifically to take account of pre-charge /*! \return Zero if not applicable for this source */ virtual Length GetPrechargeSize(void) { if(!ValidSource()) return 0; return CurrentSource->GetPrechargeSize(); } //! Get the range start position virtual Position GetRangeStart(void) { return Outer->GetRangeStart(); } //! Get the range end position virtual Position GetRangeEnd(void) { return Outer->GetRangeEnd(); } //! Get the range duration virtual Length GetRangeDuration(void) { return Outer->GetRangeDuration(); } //! Get the name of this essence source (used for error messeges) virtual std::string Name(void) { if(ValidSource()) return "SequentialEssenceSource based on " + CurrentSource->Name(); else return "SequentialEssenceSource"; } //! Enable VBR indexing, even in clip-wrap mode, by allowing each edit unit to be returned individually /*! As the byte offset part of a VBR index table is constructed at write-time each indexed chunk must be written separately. * When clip-wrapping, this is not normally the case as larger chunks may be returned for efficiency. Setting this mode * forces each indexable edit unit to be returned by a fresh GetEssenceData call as if it were being frame-wrapped. * \return true if this mode is supported by the source, and the mode was set, else false */ virtual bool EnableVBRIndexMode(void) { // Set the mode and record a flag to redo this each new file (if it succeeded) if(ValidSource()) return VBRIndexMode = CurrentSource->EnableVBRIndexMode(); else return false; } //! Is this source a system item rather than an essence source? virtual bool IsSystemItem(void) { if(ValidSource()) return CurrentSource->IsSystemItem(); else return false; } //! Is this source a generic stream item rather than an normal essence source? virtual bool IsGStreamItem(void) { if(ValidSource()) return CurrentSource->IsGStreamItem(); else return false; } //! Attach a related System Item source to the owning BodyStream if required /*! DRAGONS: This is currently a non-ideal fudge - do not assume this method will last long!!! */ virtual void AttachSystem(BodyStream *Stream) { if(ValidSource()) CurrentSource->AttachSystem(Stream); } protected: //! Ensure that CurrentSource is valid and ready for reading - if not select the next source file /*! \return true if all OK, false if no EssenceSource available */ bool ValidSource(void); // Allow the parser to access our internals friend class FileParser; }; // Allow our protected member to access our internals friend class SequentialEssenceSource; //! Send options to a sub-parser based on a formatted string /*! Each option is a string with an optional equals and Int64 number. Options are semi-colon separated. * The option string may be within quotes, if not it will be left and right trimmed to remove spaces */ void SendParserOptions(EssenceSubParserPtr &SubParser, const std::string Options); //! Process an ampersand separated list of sub-file names virtual void ProcessSubNames(std::string SubNames); }; } // GCReader and associated structures namespace mxflib { //! Content Units to be counted to evaluate when to stop ReadFromFile typedef enum _ReaderUnit { Unit_KLV, Unit_GC, Unit_Part, Unit_Cont } ReaderUnit; //! Base class for GCReader handlers /*! \note Classes derived from this class <b>must not</b> include their own RefCount<> derivation */ class GCReadHandler_Base : public RefCount<GCReadHandler_Base> { public: //! Base destructor virtual ~GCReadHandler_Base() {}; //! Handle a "chunk" of data that has been read from the file /*! \return true if all OK, false on error */ virtual bool HandleData(GCReaderPtr Caller, KLVObjectPtr Object) = 0; }; // Smart pointer for the base GCReader read handler typedef SmartPtr<GCReadHandler_Base> GCReadHandlerPtr; //! Class that reads data from an MXF file class GCReader : public RefCount<GCReader> { protected: MXFFilePtr File; //!< File from which to read Position FileOffset; //!< The offset of the start of the current (or next) KLV within the file. Current KLV during HandleData() and next at other times. Position StreamOffset; //!< The offset of the start of the current KLV within the data stream bool StopNow; //!< True if no more KLVs should be read - set by StopReading() and ReadFromFile() when Focus,Unit,Count is satisfied bool StopCalled; //!< True if StopReading() called while processing the current KLV bool PushBackRequested; //!< True if StopReading() called with PushBackKLV = true GCReadHandlerPtr DefaultHandler; //!< The default handler to receive all KLVs without a specific handler GCReadHandlerPtr FillerHandler; //!< The hanlder to receive all filler KLVs GCReadHandlerPtr EncryptionHandler; //!< The hanlder to receive all encrypted KLVs std::map<UInt32, GCReadHandlerPtr> Handlers; //!< Map of read handlers indexed by track number public: //! Create a new GCReader, optionally with a given default item handler and filler handler /*! \note The default handler receives all KLVs without a specific handler (except fillers) * The filler handler receives all filler KLVs */ GCReader( MXFFilePtr File, GCReadHandlerPtr DefaultHandler = NULL, GCReadHandlerPtr FillerHandler = NULL ); //! Set the default read handler /*! This handler receives all KLVs without a specific data handler assigned * including KLVs that do not appear to be standard GC KLVs. If not default handler * is set KLVs with no specific handler will be discarded. */ void SetDefaultHandler(GCReadHandlerPtr DefaultHandler = NULL) { this->DefaultHandler = DefaultHandler; } //! Set the filler handler /*! If no filler handler is set all filler KLVs are discarded * \note Filler KLVs are <b>never</b> sent to the default handler * unless it is also set as the filler handler */ void SetFillerHandler(GCReadHandlerPtr FillerHandler = NULL) { this->FillerHandler = FillerHandler; } //! Set encryption handler /*! This handler will receive all encrypted KLVs and after decrypting them will * resubmit the decrypted version for handling using function HandleData() */ void SetEncryptionHandler(GCReadHandlerPtr EncryptionHandler = NULL) { this->EncryptionHandler = EncryptionHandler; } //! Set data handler for a given track number void SetDataHandler(UInt32 TrackNumber, GCReadHandlerPtr DataHandler = NULL) { if(DataHandler) { Handlers[TrackNumber] = DataHandler; } else { Handlers.erase(TrackNumber); } } //! Read from file - and specify a start location /*! All KLVs are dispatched to handlers * Stops reading when Focus,Unit,Count is satisfied (default=false,Unit_KLV,1) * \param FilePos Location within the file to start this read * \param StreamPos Stream offset of the first KLV to be read * \param Focus (default false) if reading will Stop after the Unit and Count params are satisfied * \param Unit enum (default Unit_KLV) of what Unit of content {Unit_KLV,Unit_GC,Unit_Part,Unit_Cont} is to be Counted * \param Count count (default 1) of how many Units are be read prior to stop (0==forever) * \return true if all went well, false end-of-file, an error occured or StopReading() was called */ bool ReadFromFile(Position FilePos, Position StreamPos, bool Focus = false, ReaderUnit Unit = Unit_KLV, int Count = 1 ) { FileOffset = FilePos; // Record the file location StreamOffset = StreamPos; // Record the stream location return ReadFromFile(Focus,Unit,Count); // Then do a "continue" read } //! Read from file - continuing from a previous read /*! All KLVs are dispatched to handlers * Stops reading when Focus,Unit,Count is satisfied (default=false,Unit_KLV,1) * \return true if all went well, false end-of-file, an error occured or StopReading() was called */ bool ReadFromFile(bool Focus = false, ReaderUnit Unit = Unit_KLV, int Count = 1 ); //! Set the offset of the start of the next KLV in the file /*! Generally this will only be called as a result of parsing a partition pack * \note The offset will increment automatically as data is read. * If a seek is performed the offset will need to be adjusted. */ void SetFileOffset(Position NewOffset) { FileOffset = NewOffset; }; //! Set the offset of the start of the next KLV within this GC stream /*! Generally this will only be called as a result of parsing a partition pack * \note The offset will start at zero and increment automatically as data is read. * If a seek is performed the offset will need to be adjusted. */ void SetStreamOffset(Position NewOffset) { StreamOffset = NewOffset; }; //! Get the file offset of the next read (or the current KLV if inside ReadFromFile) /*! \note This is not the correct way to access the raw KLV in the file - that should be done via the KLVObject. * This function allows the caller to determine where the file pointer ended up after a read. */ Position GetFileOffset(void) { return FileOffset; } /*** Functions for use by read handlers ***/ //! Force a KLVObject to be handled /*! \note This is not the normal way that the GCReader is used, but allows the encryption handler * to push the decrypted data back to the GCReader to pass to the appropriate handler * \return true if all OK, false on error */ bool HandleData(KLVObjectPtr Object); //! Stop reading even though there appears to be valid data remaining /*! This function can be called from a handler if it detects that the current KLV is either the last * KLV in partition, or does not belong in this partition at all. If the KLV belongs to another * partition, or handling should be deferred for some reason, PushBackKLV can be set to true */ void StopReading(bool PushBackKLV = false); //! Get the offset of the start of the current KLV within this GC stream Position GetStreamOffset(void) { return StreamOffset; }; }; } // BodyReader and associated structures namespace mxflib { //! BodyReader class - reads from an MXF file (reads data is "pulled" from the file) class BodyReader : public RefCount<BodyReader> { protected: MXFFilePtr File; //!< File from which to read Position CurrentPos; //!< Current position within file bool NewPos; //!< The value of CurrentPos has been updated by a seek - therefore reading must be reinitialized! bool SeekInited; //!< True once the per SID seek system has been initialized bool AtPartition; //!< Are we (to our knowledge) at the start of a partition pack? bool AtEOF; //!< Are we (to our knowledge) at the end of the file? UInt32 CurrentBodySID; //!< The currentBodySID being processed GCReadHandlerPtr GCRDefaultHandler; //!< Default handler to use for new GCReaders GCReadHandlerPtr GCRFillerHandler; //!< Filler handler to use for new GCReaders GCReadHandlerPtr GCREncryptionHandler; //!< Encryption handler to use for new GCReaders std::map<UInt32, GCReaderPtr> Readers; //!< Map of GCReaders indexed by BodySID public: //! Construct a body reader and associate it with an MXF file BodyReader(MXFFilePtr File); //! Seek to a specific point in the file /*! \return New location or -1 on seek error */ Position Seek(Position Pos = 0); //! Tell the current file location Position Tell(void) { return CurrentPos; }; //! Seek to a specific byte offset in a given stream /*! \return New file offset or -1 on seek error */ Position Seek(UInt32 BodySID, Position Pos); //! Report the byte offset in a given stream /*! \return File offset or -1 if not known or stream does not exist */ Position Tell(UInt32 BodySID); //! Set the default handler for all new GCReaders /*! Each time a new GCReader is created this default handler will be used if no other is specified */ void SetDefaultHandler(GCReadHandlerPtr DefaultHandler = NULL) { GCRDefaultHandler = DefaultHandler; }; //! Set the filler handler for all new GCReaders /*! Each time a new GCReader is created this filler handler will be used if no other is specified */ void SetFillerHandler(GCReadHandlerPtr FillerHandler = NULL) { GCRFillerHandler = FillerHandler; }; //! Set the encryption handler for all new GCReaders /*! Each time a new GCReader is created this encryption handler will be used */ void SetEncryptionHandler(GCReadHandlerPtr EncryptionHandler = NULL) { GCREncryptionHandler = EncryptionHandler; }; //! Make a GCReader for the specified BodySID /*! \return true on success, false on error (such as there is already a GCReader for this BodySID) */ bool MakeGCReader(UInt32 BodySID, GCReadHandlerPtr DefaultHandler = NULL, GCReadHandlerPtr FillerHandler = NULL); //! Make a GCReader for the specified BodySID /*! \return A pointer to the new Reader, or the NULL on error (such as there is already a GCReader for this BodySID) */ GCReader *NewGCReader(UInt32 BodySID, GCReadHandlerPtr DefaultHandler = NULL, GCReadHandlerPtr FillerHandler = NULL); //! Get a pointer to the GCReader used for the specified BodySID GCReaderPtr GetGCReader(UInt32 BodySID) { // See if we have a GCReader for this BodySID std::map<UInt32, GCReaderPtr>::iterator it = Readers.find(BodySID); // If not found return NULL if(it == Readers.end()) return NULL; // Return the pointer return (*it).second; } //! Read from file /*! All KLVs are dispatched to handlers * Stops reading when Focus,Unit,Count is satisfied (default=false,Unit_KLV,1) * \return true if all went well, false end-of-file, an error occured or StopReading() * was called on the current GCReader */ bool ReadFromFile(bool Focus = false, ReaderUnit Unit = Unit_KLV, int Count= 1 ); //! Resync after possible loss or corruption of body data /*! Searches for the next partition pack and moves file pointer to that point * \return false if an error (or EOF found) */ bool ReSync(); //! Are we currently at the start of a partition pack? bool IsAtPartition(void); //! Are we currently at the end of the file? bool Eof(void); /*** Functions for use by read handlers ***/ //! Get the BodySID of the current location (0 if not known) UInt32 GetBodySID(void) { return CurrentBodySID; } protected: //! Initialize the per SID seek system /*! To allow us to seek to byte offsets within a file we need to initialize * various structures - seeking is not always possible!! * \return False if seeking could not be initialized (perhaps because the file is not seekable) */ bool InitSeek(void); }; //! Smart pointer to a BodyReader typedef SmartPtr<BodyReader> BodyReaderPtr; } //********************************************* //** ** //** General essence functions ** //** ** //********************************************* namespace mxflib { //! Structure to hold information about each stream in a GC struct GCElementKind { bool IsValid; //!< true if this is a GC Element UInt8 Item; //!< Item type - byte 13 UInt8 Count; //!< Element count - byte 14 UInt8 ElementType; //!< Element type - byte 15 UInt8 Number; //!< Element number - byte 16 bool operator==( const GCElementKind R ) const { if( !IsValid && !R.IsValid ) return true; return (Item==R.Item && Count==R.Count && ElementType==R.ElementType && Number==R.Number); } bool operator!=( const GCElementKind R ) const { return !operator==(R); } }; //! Register an essence key to be treated as a GC essence key /*! This allows private or experimental essence keys to be treated as standard GC keys when reading * /note If the size is less than 16-bytes, only that part of the key given will be compared (all the rest will be treated as wildcard bytes). * Byte 8 is never compared (the version number byte) */ void RegisterGCElementKey(DataChunkPtr &Key); //! Register a system item key to be treated as a GC system key /*! This allows private or experimental essence keys to be treated as standard GC keys when reading * /note If the size is less than 16-bytes, only that part of the key given will be compared (all the rest will be treated as wildcard bytes). * Byte 8 is never compared (the version number byte) */ void RegisterGCSystemKey(DataChunkPtr &Key); //! Get a GCElementKind structure from a key GCElementKind GetGCElementKind(const ULPtr TheUL); //! Determine if this is a system item bool IsGCSystemItem(const ULPtr TheUL); //! Determine if this is a generic stream item bool IsGStreamItem(const ULPtr TheUL); //! Get the track number of this essence key (if it is a GC Key) /*! \return 0 if not a valid GC Key */ UInt32 GetGCTrackNumber(ULPtr TheUL); //! GCLayout class maintains a vector of GC elements (both Sys and Essence) discovered while reading class GCLayout { private: std::vector<GCElementKind> _current; //!< pre-built or pre-loaded layour, used to compare against std::vector<GCElementKind> _fresh; //!< layout building now whilst comparing bool _valid; //!< validity of _current. false = don't compare bool _inconsistent; //!< true = inconsistency found in _fresh relative to _current bool _autorefresh; //!< true = automatically replace _current at start of next GC, see below //! normal behaviour is to save _fresh as _current upon starting new GC (i.e. when Offer returns 3) Position _pos; //!< count how many complete GCs public: GCLayout( const bool refresh = true ) { _valid = false; _inconsistent = false; _autorefresh = refresh; _pos = 0; _current.reserve( 16 ); // to avoid unnecessary reallocation _fresh.reserve( 16 ); }; ~GCLayout() { _current.clear(); _fresh.clear(); }; bool IsValid() { return _valid; } bool IsConsistent() { return !_inconsistent; } //! return how many since last reset Position Pos() { return _pos; } //! most recent element GCElementKind Which() { return _fresh.back(); } size_t Size() { if( _valid ) return _current.size(); else return _fresh.size(); } //! reset _current, Where() and set _autorefresh void Reset( const bool refresh = true ) { _valid = false; _inconsistent = false; _autorefresh = refresh; _pos = 0; _current.clear(); _fresh.clear(); } //! Offer an element and report status // -1 = inconsistent // 0 = added OK // 1 = added OK, presume next will be last // 2 = added OK, presumed was last // 3 = starts new GC note: may also be inconsistent int Offer( const GCElementKind me ) { if( !_valid ) { if( _fresh.empty() ) // first element { _fresh.push_back( me ); return 3; // ok } else if( _fresh.size()==1 && me==_fresh.back() // double element ||( _fresh.size()>1 && me==_fresh.front() ) ) // repeat cycle { if( _autorefresh ) { _current = _fresh; _valid = true; _inconsistent = false; } _fresh.clear(); _fresh.push_back( me ); _pos++; return 3; // start new } else if( (me.Item&0xF) > 4 && (_fresh.back().Item&0xF) == 7 // Pic, Snd, Cpd allowed after Data ||( (me.Item&0xF) >= (_fresh.back().Item&0xF) ) ) // otherwise allowed in seq Sys, Pic, Snd, Data, Cpd { _fresh.push_back( me ); return 0; // ok } else { if( _autorefresh ) { _current = _fresh; _valid = true; _inconsistent = false; } _fresh.clear(); _fresh.push_back( me ); _pos++; return 3; // start new } } else { if( _current.size() >= 1 && me == _current.front() ) { _fresh.clear(); _fresh.push_back( me ); _pos++; return 3; // start new } _fresh.push_back( me ); if( _fresh.size() > _current.size() ) { _inconsistent = true; return -1; } // just became inconsistently bigger if( _fresh.size() == _current.size() ) { if( me != _current.back() ) { _inconsistent = true; return -1; } else return 2; // was last } else if( _fresh.size() == (_current.size()-1) ) { if( me != _current.back() ) { _inconsistent = true; return -1; } else return 1; // was penultimate } if( me != _current.back() ) { _inconsistent = true; return -1; } else return 0; // OK } }; //! report where in _current // -1 = no _curr // 0 = in middle // 1 = next will be last // 2 = at end // 3 = just started int Where() { if( !_valid || _current.empty() ) return -1; // no curr if( _fresh.size() == _current.size() ) return 2; // at end else if( _fresh.size() == (_current.size()-1) ) return 1; // penultimate else if( _fresh.size() == 1 ) return 3; // first return 0; // somewhere }; //! force immediate end of _fresh layout // -1 = was not at end // 2 = OK int ForceEnd() { _current = _fresh; _inconsistent = false; _fresh.clear(); if( Where()!=2 ) return -1; // wasn't at end else { _valid = true; return 2; } // ok }; }; } /* BodyWriter and related classes */ namespace mxflib { //! Class holding data relating to a stream to be written by BodyWriter /*! Sub-streams can be added as pointers to their essence sources as this class is derived from EssenceSourceList. * Sub-streams will be written in the same generic container as this stream. * This stream's essence source will appear as the first "child" when the EssenceSourceList is scanned */ class BodyStream : public RefCount<BodyStream>, public EssenceSourceList { public: //! Define the action required next for this stream enum StateType { BodyStreamStart = 0, //!< This stream has not yet done anything - state unknown BodyStreamHeadIndex, //!< Next action: Write a "header" index table - if required in an isolated partition following the header BodyStreamPreBodyIndex, //!< Next action: Write an isolated index table before the next body partition BodyStreamBodyWithIndex, //!< Next action: Write a body partition with an index table BodyStreamBodyNoIndex, //!< Next action: Write a body partition without index table BodyStreamPostBodyIndex, //!< Next action: Write an isolated index table after a body partition BodyStreamFootIndex, //!< Next action: Write a "footer" index table - if required in an isolated partition before the footer BodyStreamDone //!< All done - no more actions required }; //! The index table type or types of this stream enum IndexType { StreamIndexNone = 0, //!< No index table will be written StreamIndexFullFooter = 1, //!< A full index table will be written in the footer if possible (or an isolated partition just before the footer if another index is going to use the footer) StreamIndexSparseFooter = 2, //!< A sparse index table will be written in the footer if possible (or an isolated partition just before the footer if another index is going to use the footer) StreamIndexSprinkled = 4, //!< A full index table will be sprinkled through the file, one chunk in each of this essence's body partitions, and one in or just before the footer StreamIndexSprinkledIsolated = 8, //!< A full index table will be sprinkled through the file, one chunk in an isolated partition following each of this essence's body partitions StreamIndexCBRHeader = 16, //!< A CBR index table will be written in the header (or an isolated partition following the header if another index table exists in the header) StreamIndexCBRHeaderIsolated = 32, //!< A CBR index table will be written in an isolated partition following the header StreamIndexCBRFooter = 64, //!< A CBR index table will be written in the footer if possible (or an isolated partition just before the footer if another index is going to use the footer) StreamIndexCBRBody = 128, //!< A CBR index table will be written in each body partition for this stream StreamIndexCBRIsolated = 256, //!< A CBR index table will be written in an isolated body partition following each partition of this stream StreamIndexCBRPreIsolated = 512 //!< A CBR index table will be written in an isolated body partition before each partition of this stream }; //! Wrapping types for streams enum WrapType { StreamWrapOther = 0, //!< Other non-standard wrapping types - the essence source will supply one KLVs worth at a time (??) StreamWrapFrame, //!< Frame wrapping StreamWrapClip //!< Clip wrapping }; protected: EssenceSourcePtr Source; //!< The essence source for this stream EssenceSourceList SubStreams; //!< Sources for each sub-stream EssenceSourceList::iterator SubStream_it; //!< Current sub-stream bool SubStreamRestart; //!< Flag true when the sub-stream iterator needs moving to the top of the list next time StateType State; //!< The state of this stream IndexType StreamIndex; //!< The index type(s) of this stream IndexType FooterIndexFlags; //!< Set of flags for tracking footer index tables UInt32 BodySID; //!< BodySID to use for this stream UInt32 IndexSID; //!< IndexSID to use for indexing this stream WrapType StreamWrap; //!< The wrapping type of this stream GCWriter* StreamWriter; //!< The writer for this stream bool EssencePendingData; //!< Is there any essence data pending in the writer? bool EndOfStream; //!< No more essence available for this stream IndexManagerPtr IndexMan; //!< The index manager for this stream Position NextSprinkled; //!< The location of the first edit-unit to use for the next sprinkled index segment size_t PrevSprinkleSize; //!< The size of the most recent sprinkled index table bool FreeSpaceIndex; //!< True if the free space at the end of the essenc eis to be indexed /*!< When an essence stream may be extended during file creation it may be useful to know * where the essence currently ends (to allow new essence to be added). * /note DRAGONS: This is non-standard and will produce invalid index tables (even if they are later "fixed") */ bool ValueRelativeIndexing; //!< Flag to allow value-relative indexing /*!< \note This is NOT implemented in the IndexManager, but must be handled by the caller */ Length PrechargeSize; //!< The number of edit units of pre-charge remaining to be written /*!< DRAGONS: This is set when the state moves from "start" because it is * important to wait for all sub-streams to be set up first */ //! The fixed position for this stream, or (0 - 0x7fffffff) if not fixed /*! This allows the position to be fixed at the start of processing an edit unit, then unfixed at the end */ Position FixedPosition; Length OverallEssenceSize; //!< The number of raw essence bytes written from this stream so far /*!< DRAGONS: This is only the raw bytes, not including keys, lengths or any filler */ //! KLV Alignment Grid to use for this stream (of zero if default for this body is to be used) UInt32 KAG; //! Flag set if BER lengths for this stream should be forced to 4-byte (where possible) bool ForceBER4; //! Flag set if partitioning is to be done only on edit boundaries /*! \note Only the master stream is (currently) edit aligned, not all sub-streams */ bool EditAlign; //! Prevent NULL construction BodyStream(); //! Prevent copy construction BodyStream(BodyStream &); /* Public properties */ public: std::list<Position> SparseList; //!< List of edit units to include in sparse index tables public: //! Construct a body stream object with a given essence source BodyStream(UInt32 SID, EssenceSourcePtr &EssSource, DataChunkPtr Key = NULL, bool NonGC = false) { BodySID = SID; IndexSID = 0; Source = EssSource; State = BodyStreamStart; StreamIndex = StreamIndexNone; FooterIndexFlags = StreamIndexNone; StreamWrap = StreamWrapOther; StreamWriter = NULL; SubStreamRestart = true; NextSprinkled = 0; PrevSprinkleSize = 0; EssencePendingData = false; EndOfStream = false; FreeSpaceIndex = false; ValueRelativeIndexing = false; PrechargeSize = 0; OverallEssenceSize = 0; // Clear the fixed position SetFixedPosition(); KAG = 0; ForceBER4 = false; EditAlign = false; // Set the non-standard key if requested if(Key) EssSource->SetKey(Key, NonGC); // Set the master stream as one of the essence streams push_back(Source); // Inform the master stream that we are holding them EssSource->SetBodyStream(this); // Allow the master stream to attach a system item if required EssSource->AttachSystem(this); } //! Get the essence source for this stream EssenceSourcePtr &GetSource(void) { return Source; } //! Get the number of sub-streams (includes the master stream) size_type SubStreamCount(void) { return size(); } //! Add a new sub-stream void AddSubStream(EssenceSourcePtr &SubSource, DataChunkPtr Key = NULL, bool NonGC = false); //! Get this stream's BodySID UInt32 GetBodySID(void) { return BodySID; } //! Set this stream's IndexSID void SetIndexSID(UInt32 SID) { IndexSID = SID; } //! Get this stream's IndexSID UInt32 GetIndexSID(void) { return IndexSID; } //! Set the stream's state void SetState(StateType NewState) { State = NewState; } //! Get the current state StateType GetState(void) { if(State == BodyStreamStart) GetNextState(); return State; } //! Get the next state /*! Sets State to the next state * \return The next state (now the current state) */ StateType GetNextState(void); //! Add the specified index type(s) void AddIndexType(IndexType NewIndexType) { StreamIndex = (IndexType) (StreamIndex | NewIndexType); } //! Set the index type(s) to the desired value /*! \note This sets the complete value, it doesn't just add an option - to add "X" use AddIndexType() */ void SetIndexType(IndexType NewIndexType) { StreamIndex = NewIndexType; } //! Get the index type(s) IndexType GetIndexType(void) { return StreamIndex; } //! Set the footer index flags to the desired value /*! \note This sets the complete value, it doesn't just add an option - to add "X" use SetFooterIndex(GetFooterIndex() | "X"); */ void SetFooterIndex(IndexType NewIndexType) { FooterIndexFlags = NewIndexType; } //! Get the footer index flags IndexType GetFooterIndex(void) { return FooterIndexFlags; } //! Set the wrapping type for this stream void SetWrapType(WrapType NewWrapType) { StreamWrap = NewWrapType; } //! Set the wrapping type for this stream void SetWrapType(WrappingOption::WrapType NewWrapType) { if(NewWrapType == WrappingOption::Frame) StreamWrap = StreamWrapFrame; else if(NewWrapType == WrappingOption::Clip) StreamWrap = StreamWrapClip; else StreamWrap = StreamWrapOther; } //! Get the wrapping type of this stream WrapType GetWrapType(void) { return StreamWrap; } //! Set the current GCWriter void SetWriter(GCWriter* Writer); //! Get the current index manager IndexManagerPtr &GetIndexManager(void) { if(!IndexMan) InitIndexManager(); return IndexMan; } //! Get a pointer to the current GCWriter GCWriter* GetWriter(void) { return StreamWriter; } //! Get the track number associated with this stream UInt32 GetTrackNumber(void) { if(!Source) return 0; return StreamWriter->GetTrackNumber(Source->GetStreamID()); } //! Get the track number associated with a specified stream or sub-stream Uint32 GetTrackNumber(GCStreamID ID) { if(!Source) return 0; return StreamWriter->GetTrackNumber(ID); } //! Set the pending essence data flag void SetPendingData(bool Value = true) { EssencePendingData = Value; } //! Find out if there is any essence data stored in the GCWriter pending a write bool HasPendingData(void) { return EssencePendingData; } //! Set the EndOfStream flag void SetEndOfStream(bool Value = true) { EndOfStream = Value; } //! Find out if there is any essence data remaining for this stream bool GetEndOfStream(void) { return EndOfStream; } //! Set the first edit unit for the next sprinkled index segment void SetNextSprinkled(Position Sprinkled) { NextSprinkled = Sprinkled; } //! Get the first edit unit for the next sprinkled index segment Position GetNextSprinkled(void) { return NextSprinkled; } //! Set the size of the previous sprinkled index segment void SetPrevSprinkleSize( size_t Curr ) { PrevSprinkleSize = Curr; } //! Get the size of the previous sprinkled index segment size_t GetPrevSprinkleSize(void) { return PrevSprinkleSize; } //! Set the KLV Alignment Grid // FIXME: This will break CBR indexing if changed during writing! void SetKAG(UInt32 NewKAG) { KAG = NewKAG; } //! Get the KLV Alignment Grid UInt32 GetKAG(void) { return KAG; } //! Set flag if BER lengths should be forced to 4-byte (where possible) void SetForceBER4(bool Force) { ForceBER4 = Force; } //! Get flag stating whether BER lengths should be forced to 4-byte (where possible) bool GetForceBER4(void) { return ForceBER4; } //! Set edit align forced partitioning flag void SetEditAlign(bool Align) { EditAlign = Align; } //! Get edit align forced partitioning flag bool GetEditAlign(void) { return EditAlign; } //! Set the "FreeSpaceIndex" flag /*! \note DRAGONS: Setting this flag will cause index tables that are not SMPTE 377M complient to be created */ void SetFreeSpaceIndex(bool Flag) { FreeSpaceIndex = Flag; } //! Read the "FreeSpaceIndex" flag bool GetFreeSpaceIndex(void) { return FreeSpaceIndex; } //! Set value-relative indexing flag /*! Value-relative indexing will produce index tables that count from the first byte of the KLV * of clip-wrapped essence rather than the key. These tables can be used internally but must not * be written to a file as they are not 377M complient */ void SetValueRelativeIndexing(bool Val) { ValueRelativeIndexing = Val; if(IndexMan) IndexMan->SetValueRelativeIndexing(Val); } //! Get value-relative indexing flag /*! Value-relative indexing will produce index tables that count from the first byte of the KLV * of clip-wrapped essence rather than the key. These tables can be used internally but must not * be written to a file as they are not 377M complient */ bool GetValueRelativeIndexing(void) { return ValueRelativeIndexing; } //! Read the number of edit units of pre-charge remaining Length GetPrechargeSize(void) const { return PrechargeSize; } //! Reduce the precharge count by one void DecrementPrecharge(void) { if(PrechargeSize) PrechargeSize--; } //! Initialize an index manager if required void InitIndexManager(void); //! Increment the count of essence bytes written so far from this stream /*! DRAGONS: This is intended only for internal library use */ void IncrementOverallEssenceSize(Length Delta) { OverallEssenceSize += Delta; }; //! Get the count of essence bytes written so far from this stream /*! DRAGONS: This is only the raw bytes, not including keys, lengths or any filler */ Length GetOverallEssenceSize(void) { return OverallEssenceSize; }; //! Get the position of the stream in edit units since the start of the stream Position GetPosition(void); //! Set or clear the fixed position for this stream /*! This allows the position to be fixed at the start of processing an edit unit, then unfixed at the end */ void SetFixedPosition(Position Pos = (0 - 0x7fffffff)) { FixedPosition = Pos; } }; // Forward declare BodyWriterPtr to allow it to be used in BodyWriterHandler class BodyWriter; typedef SmartPtr<BodyWriter> BodyWriterPtr; //! Base class for partition candler callbacks class BodyWriterHandler : public RefCount<BodyWriterHandler> { public: //! Virtual destructor to allow polymorphism virtual ~BodyWriterHandler(); //! Handler called before writing a partition pack /*! \param Caller - A pointer to the calling BodyWriter * \param BodySID - The Stream ID of the essence in this partition (0 if none) * \param IndexSID - The Stream ID of the index data in this partition (0 if none) * \note If metadata is to be written the partition type must be set accordingly by the handler - otherwise closed and complete will be used * \note If metadata is requested but the partition will contain index or essence data that is not permitted to share a partition * with metadata an extra partition pack will be written with no metadata after writing the metadata * \return true if metadata should be written with this partition pack */ virtual bool HandlePartition(BodyWriterPtr Caller, UInt32 BodySID, UInt32 IndexSID) = 0; }; //! Smart pointer to a BodyWriterHandler typedef SmartPtr<BodyWriterHandler> BodyWriterHandlerPtr; //! Body writer class - manages multiplexing of essence class BodyWriter : public RefCount<BodyWriter> { protected: // States for BodyWriter enum BodyState { BodyStateStart = 0, //!< The BodyWriter has not yet started writing BodyStateHeader, //!< Writing the header (and/or post header indexes) BodyStateBody, //!< Writing the body essence and indexes BodyStateFooter, //!< Writing the footer (and/or pre-footer indexes or RIP) BodyStateDone //!< All done }; //! The state for this writer BodyState State; //! Class for holding info relating to a stream /*! This class holds medium-term info about a stream in comparision to BodyStream which holds * long-term info. This is because odd interleaving may cause a stream to be added and removed * from the writer during the course of the file. Data that needs to survive through the whole * file lives in BodyStream and data relating to this phase lives in StreamInfo. * \note This class has public internals because it is basically a glorified struct! */ class StreamInfo : public RefCount<StreamInfo> { public: bool Active; //!< True if active - set false once finished BodyStreamPtr Stream; //!< The stream in question Length StopAfter; //!< Number of edit units to output (or zero for no limit). Decremented each time data is written (unless zero). public: //! Construct an "empty" StreamInfo StreamInfo() { Active = false; } //! Copy constructor StreamInfo(const StreamInfo &rhs) { Active = rhs.Active; Stream = rhs.Stream; StopAfter = rhs.StopAfter; } }; //! Smart pointer to a StreamInfo typedef SmartPtr<StreamInfo> StreamInfoPtr; //! Type for list of streams to write /*! The list is kept in the order that the BodySIDs are added */ typedef std::list<StreamInfoPtr> StreamInfoList; //! Destination file MXFFilePtr File; //! List of streams to write StreamInfoList StreamList; //! KLV Alignment Grid to use UInt32 KAG; //! Flag set if BER lengths should be forced to 4-byte (where possible) bool ForceBER4; //! Partition pack to use when one is required PartitionPtr BasePartition; BodyWriterHandlerPtr PartitionHandler; //!< The body partition handler UInt32 MinPartitionSize; //!< The minimum size of the non-essence part of the next partition UInt32 MinPartitionFiller; //!< The minimum size of filler before the essence part of the next partition bool IndexSharesWithMetadata; //!< If true index tables may exist in the same partition as metadata bool EssenceSharesWithMetadata; //!< If true essence may exist in the same partition as metadata //! The current BodySID, or 0 if not known (will move back to the start of the list) UInt32 CurrentBodySID; //! The current partition is done and must not be continued - any new data must start a new partition bool PartitionDone; //! Iterator for the current (or previous) stream data. Only valid if CurrentBodySID != 0 StreamInfoList::iterator CurrentStream; /* Details about the pending partition, set but not yet written * This is because the value of BodySID depends on whether any * essence is going to be written in this partition which won't * be known for certain until we are about to write the essence */ //! Flag set when a partition pack is ready to be written bool PartitionWritePending; //! Is the pending metadata a header? bool PendingHeader; //! Is the pending metadata a footer? bool PendingFooter; //! Is the next partition write going to have metadata? bool PendingMetadata; //! Is the pending partition pack for a generic stream? bool PendingGeneric; //! Pointer to a chunk of index table data for the pendinf partition or NULL if none is required DataChunkPtr PendingIndexData; //! BodySID of the essence or index data already written or pending for this partition /*! This is used to determine if particular essence can be added to this partition. * Set to zero if none yet written. */ UInt32 PartitionBodySID; //! Prevent NULL construction BodyWriter(); //! Prevent copy construction BodyWriter(BodyWriter &); public: //! Construct a body writer for a specified file BodyWriter(MXFFilePtr &DestFile) { State = BodyStateStart; CurrentBodySID = 0; PartitionDone = false; File = DestFile; // By default index tables may share with metadata, but not essence IndexSharesWithMetadata = true; EssenceSharesWithMetadata = false; KAG = 0; ForceBER4 = false; MinPartitionSize = 0; MinPartitionFiller = 0; PartitionWritePending = false; PendingHeader = 0; PendingFooter = 0; PendingMetadata = false; PartitionBodySID = 0; PendingGeneric = false; } //! Clear any stream details ready to call AddStream() /*! This allows previously used streams to be removed before a call to WriteBody() or WriteNext() */ void ClearStreams(void) { StreamList.clear(); CurrentBodySID = 0; } //! Add a stream to the list of those to write /*! \param Stream - The stream to write * \param StopAfter - If > 0 the writer will stop writing this stream at the earliest opportunity after (at least) this number of edit units have been written * Streams will be written in the order that they were offered and the list is kept in this order. * \return false if unable to add this stream (for example this BodySID already in use) */ bool AddStream(BodyStreamPtr &Stream, Length StopAfter = 0); //! Set the KLV Alignment Grid void SetKAG(UInt32 NewKAG) { // TODO: This is probably not the best way - but is the only way to currently ensure correct CBR indexing! if(StreamList.size()) warning("KAG size changed after adding streams - CBR indexing may be incorrect\n"); KAG = NewKAG; } //! Get the KLV Alignment Grid UInt32 GetKAG(void) { return KAG; } //! Set flag if BER lengths should be forced to 4-byte (where possible) void SetForceBER4(bool Force) { ForceBER4 = Force; } //! Get flag stating whether BER lengths should be forced to 4-byte (where possible) bool GetForceBER4(void) { return ForceBER4; } //! Set what sort of data may share with header metadata void SetMetadataSharing(bool IndexMayShare = true, bool EssenceMayShare = false) { IndexSharesWithMetadata = IndexMayShare; EssenceSharesWithMetadata = EssenceMayShare; } //! Set the template partition pack to use when partition packs are required /*! The byte counts and SIDs will be updated are required before writing. * FooterPosition will not be updated so it must either be 0 or the correct value. * Any associated metadata will be written for the header and if the handler (called just before the write) requests it. * \note The original object given will be modified - not a copy of it */ void SetPartition(PartitionPtr &ThePartition) { BasePartition = ThePartition; } //! Get a pointer to the current template partition pack PartitionPtr GetPartition(void) { return BasePartition; } //! Write the file header /*! No essence will be written, but CBR index tables will be written if required. * The partition will not be "ended" if only the header partition is written * meaning that essence will be added by the next call to WritePartition() */ void WriteHeader(bool IsClosed, bool IsComplete); //! End the current partition /*! Once "ended" no more essence will be added, even if otherwise valid. * A new partition will be started by the next call to WritePartition() * \note This function will also flush any pending partition writes */ void EndPartition(void); //! Write stream data /*! \param Duration If > 0 the stop writing at the earliest opportunity after (at least) this number of edit units have been written for each stream * \param MaxPartitionSize If > 0 the writer will attempt to keep the partition no larger than this size in bytes. There is no guarantee that it will succeed * \note Streams that have finished or hit thier own StopAfter value will be regarded as having written enough when judging whether to stop */ void WriteBody(Length Duration = 0, Length MaxPartitionSize = 0); //! Write the next partition or continue the current one (if not complete) /*! Will stop at the point where the next partition will start, or (if Duration > 0) at the earliest opportunity after (at least) Duration edit units have been written */ Length WritePartition(Length Duration = 0, Length MaxPartitionSize = 0, bool ClosePartition = true); //! Determine if all body partitions have been written /*! Will be false until after the last required WritePartition() call */ bool BodyDone(void) { return (State == BodyStateFooter) || (State == BodyStateDone); } //! Write the file footer /*! No essence will be written, but index tables will be written if required. */ void WriteFooter(bool WriteMetadata = false, bool IsComplete = true); //! Set a handler to be called before writing a partition pack within the body /*! Will be called before a body partition is written */ void SetPartitionHandler(BodyWriterHandlerPtr &NewBodyHandler) { PartitionHandler = NewBodyHandler; } //! Set the minumum size of the non-essence part of the next partition /*! This will cause a filler KLV to be added (if required) after the partition pack, any header metadata and index table segments * in order to reach the specified size. This is useful for reserving space for future metadata updates. * This value is read after calling the partition handlers so this function may safely be used in the handlers. * \note The size used will be the minimum size that satisfies the following: * - All required items are included (partition pack, metadata if required, index if required) * - The total size, excluding essence, is at least as big as the value specified by SetPartitionSize() * - The filler following the last non-essence item is at least as big as the value specified by SetPartitionFiller() * - The KAGSize value is obeyed */ void SetPartitionSize(UInt32 PartitionSize) { MinPartitionSize = PartitionSize; } //! Set the minumum size of filler between the non-essence part of the next partition and any following essence /*! If non-zero this will cause a filler KLV to be added after the partition pack, any header metadata and index table segments * of at least the size specified. This is useful for reserving space for future metadata updates. * This value is read after calling the partition handlers so this function may safely be used in the handlers. * \note The size used will be the minimum size that satisfies the following: * - All required items are included (partition pack, metadata if required, index if required) * - The total size, excluding essence, is at least as big as the value specified by SetPartitionSize() * - The filler following the last non-essence item is at least as big as the value specified by SetPartitionFiller() * - The KAGSize value is obeyed */ void SetPartitionFiller(UInt32 PartitionFiller) { MinPartitionFiller = PartitionFiller; } //! Initialize all required index managers void InitIndexManagers(void); //! Get the BodySID next in our internal list of streams, after the specified BodySID /*! If the value of BodySID passed in is zero, the first BodySID in our list is returned. * If there is no stream following the specified one, zero is returned * DRAGONS: This allows our internal streams to be iterated */ UInt32 GetNextUsedBodySID(UInt32 BodySID = 0); //! Get the BodyStream for the specified BodySID, or NULL if not one of our streams BodyStreamPtr GetStream(UInt32 BodySID); protected: //! Move to the next active stream (will also advance State as required) /*! \note Will set CurrentBodySID to 0 if no more active streams */ void SetNextStream(void); //! Write a complete partition's worth of essence /*! Will stop if: * Frame or "other" wrapping and the "StopAfter" reaches zero or "Duration" reaches zero * Clip wrapping and the entire clip is wrapped */ Length WriteEssence(StreamInfoPtr &Info, Length Duration = 0, Length MaxPartitionSize = 0, bool ClosePartition = true); //! Write a partition pack for the current partition - but do not flag it as "ended" void WritePartitionPack(void); }; //! Smart pointer to a BodyWriter typedef SmartPtr<BodyWriter> BodyWriterPtr; } /* Various functions used to determine if an Essence Container is Frame or Clip Wrapped */ namespace mxflib { //! Determine the wrapping type frame/clip from the Essence Container Label /*! \retval ClipWrap - Wrapping is Clip Wrap or similar (Wrapping size > Edit Unit) * \retval FrameWrap - Wrapping is Frame Wrap or similar (Wrapping size <= Edit Unit) * \retval UnknownWrap - Unable to determine */ WrapType GetWrapType(UInt8 const *ECLabel); //! Determine the wrapping type frame/clip from the Essence Container Label /*! \retval ClipWrap - Wrapping is Clip Wrap or similar (Wrapping size > Edit Unit) * \retval FrameWrap - Wrapping is Frame Wrap or similar (Wrapping size <= Edit Unit) * \retval UnknownWrap - Unable to determine */ inline WrapType GetWrapType(ULPtr const &ECLabel) { return GetWrapType(ECLabel->GetValue()); } //! Determine the wrapping type frame/clip from the Essence Container Label /*! \retval ClipWrap - Wrapping is Clip Wrap or similar (Wrapping size > Edit Unit) * \retval FrameWrap - Wrapping is Frame Wrap or similar (Wrapping size <= Edit Unit) * \retval UnknownWrap - Unable to determine */ inline WrapType GetWrapType(UL const &ECLabel) { return GetWrapType(ECLabel.GetValue()); } } #endif // MXFLIB__ESSENCE_H
42.94565
218
0.722586
[ "object", "vector" ]
b1486e9e0d4fc960bad0bbf70c8398273cb948a4
390
h
C
NoHoldMusic/NSApplication+NHMHelpExtension.h
mdfw/No-Hold-Music
be8ec1400be34ead55b923a412c35a42ef582c83
[ "Apache-2.0" ]
null
null
null
NoHoldMusic/NSApplication+NHMHelpExtension.h
mdfw/No-Hold-Music
be8ec1400be34ead55b923a412c35a42ef582c83
[ "Apache-2.0" ]
null
null
null
NoHoldMusic/NSApplication+NHMHelpExtension.h
mdfw/No-Hold-Music
be8ec1400be34ead55b923a412c35a42ef582c83
[ "Apache-2.0" ]
null
null
null
// // NSApplication+NHMHelpExtension.h // NoHoldMusic // // Created by Mark D. Freeman Williams on 6/4/16. // Copyright © 2016 The Fascinating Group. All rights reserved. // #import <Cocoa/Cocoa.h> @interface NSApplication (NHMHelpExtension) /** * Show the help window. * * @param sender The object requesting the window. */ - (IBAction)nhm_showHelp:(nullable id)sender; @end
18.571429
64
0.705128
[ "object" ]
7f2d3283f51c90d3059cd50c5ce7756fb199df9d
4,333
h
C
stack/framework/inc/fifo.h
Seba-P/dash-7-project
734ce7610a1b6e7458a3e38bedb4d28f2345cefe
[ "Apache-2.0" ]
null
null
null
stack/framework/inc/fifo.h
Seba-P/dash-7-project
734ce7610a1b6e7458a3e38bedb4d28f2345cefe
[ "Apache-2.0" ]
null
null
null
stack/framework/inc/fifo.h
Seba-P/dash-7-project
734ce7610a1b6e7458a3e38bedb4d28f2345cefe
[ "Apache-2.0" ]
null
null
null
/* * OSS-7 - An opensource implementation of the DASH7 Alliance Protocol for ultra * lowpower wireless sensor communication * * Copyright 2015 University of Antwerp * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file fifo.h * @addtogroup fifo * @ingroup framework * @{ * @brief A generic FIFO implementation which allows pushing and popping bytes in a circular buffer. * */ #ifndef FIFO_H #define FIFO_H #include "types.h" /** * @brief This struct contains the FIFO state variables * * A pointer to this is passed to alle functions of the fifo module **/ typedef struct { uint16_t head_idx; /**< The offset in buffer to the head of the FIFO */ uint16_t tail_idx; /**< The offset in buffer to the head of the FIFO */ uint16_t max_size; /**< The maximum size of bytes contained in the FIFO */ uint8_t* buffer; /**< The buffer where the data is stored*/ } fifo_t; /** * @brief Initializes the fifo. * @param fifo Fifo state, initialized by this function * @param buffer The buffer used for the fifo, the caller is responsible for allocating this to be big enough for max_size * @param max_size The maximum size of bytes contained in the FIFO */ void fifo_init(fifo_t* fifo, uint8_t* buffer, uint16_t max_size); /** * @brief Initializes the fifo with a pre-filled buffer * @param fifo Fifo state, initialized by this function * @param buffer The buffer used for the fifo, the caller is responsible for allocating this to be big enough for max_size * @param filled_size The length of the pre-filled buffer * @param max_size The maximum size of bytes contained in the FIFO */ void fifo_init_filled(fifo_t *fifo, uint8_t *buffer, uint16_t filled_size, uint16_t max_size); /** * @brief Put bytes in to the FIFO * @param fifo Pointer to the fifo object * @param data Pointer to the data to be put in the FIFO * @param len Number of bytes to put in the FIFO * @returns SUCCESS or ESIZE when data would overwrite head of FIFO */ error_t fifo_put(fifo_t* fifo, uint8_t* data, uint16_t len); /** * @brief Put byte in to the FIFO * @param fifo Pointer to the fifo object * @param byte Byte to be put in the FIFO * @returns SUCCESS or ESIZE when data would overwrite head of FIFO */ error_t fifo_put_byte(fifo_t* fifo, uint8_t byte); /** * @brief Peek at the FIFO contents without popping. Fills buffer with the data in the FIFO starting from head_idx + offset for len bytes * @param fifo Pointer to the fifo object * @param buffer buffer to be filled * @param offset offset starting from head * @param len length in number of bytes to read * @returns SUCCESS or ESIZE when len > max_size or len > current size */ error_t fifo_peek(fifo_t* fifo, uint8_t* buffer, uint16_t offset, uint16_t len); /** * @brief Read and pop bytes from the FIFO * @param fifo Pointer to the fifo object * @param buffer Pointer to buffer where the first len bytes of FIFO can be copied to. Caller is responsible for allocating this buffer. * @param len number of bytes to read/pop * @returns SUCCESS or ESIZE if len > current size or when FIFO empty */ error_t fifo_pop(fifo_t* fifo, uint8_t* buffer, uint16_t len); /** * @brief Clears the FIFO * @param fifo Pointer to the fifo object */ void fifo_clear(fifo_t* fifo); /** * @brief Returns the number of bytes currently in the FIFO * @param fifo Pointer to the fifo object * @return Number of bytes currently in the FIFO */ int16_t fifo_get_size(fifo_t* fifo); /** * @brief Returns if the FIFO is completely full or if there is still space left * @param fifo Pointer to the fifo object * @return Flag indicating if FIFO is full */ bool fifo_is_full(fifo_t* fifo); #endif // FIFO_H /** @}*/
35.516393
139
0.711055
[ "object" ]
7f30959427eeb35e171464d0115f823fd25aa4b6
7,728
h
C
src/include/DynamoDB/DynamoDBPutItemRequest.h
jcbertin/aws-sdk-ios
e4e62507ba48149c300c8063d67a3b99aaa07276
[ "Apache-2.0" ]
13
2015-02-16T05:54:33.000Z
2016-10-13T00:01:08.000Z
src/include/DynamoDB/DynamoDBPutItemRequest.h
jcbertin/aws-sdk-ios
e4e62507ba48149c300c8063d67a3b99aaa07276
[ "Apache-2.0" ]
15
2015-09-15T17:43:43.000Z
2017-11-09T19:41:48.000Z
src/include/DynamoDB/DynamoDBPutItemRequest.h
jcbertin/aws-sdk-ios
e4e62507ba48149c300c8063d67a3b99aaa07276
[ "Apache-2.0" ]
23
2015-02-16T19:51:12.000Z
2017-04-27T09:33:30.000Z
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #import "DynamoDBAttributeValue.h" #import "DynamoDBExpectedAttributeValue.h" #ifdef AWS_MULTI_FRAMEWORK #import <AWSRuntime/AmazonServiceRequestConfig.h> #else #import "../AmazonServiceRequestConfig.h" #endif /** * Put Item Request */ @interface DynamoDBPutItemRequest:AmazonServiceRequestConfig { NSString *tableName; NSMutableDictionary *item; NSMutableDictionary *expected; NSString *returnValues; NSString *returnConsumedCapacity; NSString *returnItemCollectionMetrics; } /** * The name of the table to contain the item. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>3 - 255<br/> * <b>Pattern: </b>[a-zA-Z0-9_.-]+<br/> */ @property (nonatomic, retain) NSString *tableName; /** * A map of attribute name/value pairs, one for each attribute. Only the * primary key attributes are required; you can optionally provide other * attribute name-value pairs for the item. <p>If you specify any * attributes that are part of an index key, then the data types for * those attributes must match those of the schema in the table's * attribute definition. <p>For more information about primary keys, see * <a * modb/latest/developerguide/DataModel.html#DataModelPrimaryKey">Primary * Key</a> in the Amazon DynamoDB Developer Guide. <p>Each element in the * <i>Item</i> map is an <i>AttributeValue</i> object. */ @property (nonatomic, retain) NSMutableDictionary *item; /** * A map of attribute/condition pairs. This is the conditional block for * the <i>PutItem</i> operation. All the conditions must be met for the * operation to succeed. <p><i>Expected</i> allows you to provide an * attribute name, and whether or not Amazon DynamoDB should check to see * if the attribute value already exists; or if the attribute value * exists and has a particular value before changing it. <p>Each item in * <i>Expected</i> represents an attribute name for Amazon DynamoDB to * check, along with the following: <ul> <li> <p><i>Value</i> - The * attribute value for Amazon DynamoDB to check. </li> <li> * <p><i>Exists</i> - Causes Amazon DynamoDB to evaluate the value before * attempting a conditional operation: <ul> <li> <p>If <i>Exists</i> is * <code>true</code>, Amazon DynamoDB will check to see if that attribute * value already exists in the table. If it is found, then the operation * succeeds. If it is not found, the operation fails with a * <i>ConditionalCheckFailedException</i>. </li> <li> <p>If <i>Exists</i> * is <code>false</code>, Amazon DynamoDB assumes that the attribute * value does <i>not</i> exist in the table. If in fact the value does * not exist, then the assumption is valid and the operation succeeds. If * the value is found, despite the assumption that it does not exist, the * operation fails with a <i>ConditionalCheckFailedException</i>. </li> * </ul> <p>The default setting for <i>Exists</i> is <code>true</code>. * If you supply a <i>Value</i> all by itself, Amazon DynamoDB assumes * the attribute exists: You don't have to set <i>Exists</i> to * <code>true</code>, because it is implied. <p>Amazon DynamoDB returns a * <i>ValidationException</i> if: <ul> <li> <p><i>Exists</i> is * <code>true</code> but there is no <i>Value</i> to check. (You expect a * value to exist, but don't specify what that value is.) </li> <li> * <p><i>Exists</i> is <code>false</code> but you also specify a * <i>Value</i>. (You cannot expect an attribute to have a value, while * also expecting it not to exist.) </li> </ul> </li> </ul> <p>If you * specify more than one condition for <i>Exists</i>, then all of the * conditions must evaluate to true. (In other words, the conditions are * ANDed together.) Otherwise, the conditional operation will fail. */ @property (nonatomic, retain) NSMutableDictionary *expected; /** * Use <i>ReturnValues</i> if you want to get the item attributes as they * appeared before they were updated with the <i>PutItem</i> request. For * <i>PutItem</i>, the valid values are: <ul> <li> <p><code>NONE</code> - * If <i>ReturnValues</i> is not specified, or if its value is * <code>NONE</code>, then nothing is returned. (This is the default for * <i>ReturnValues</i>.) </li> <li> <p><code>ALL_OLD</code> - If * <i>PutItem</i> overwrote an attribute name-value pair, then the * content of the old item is returned. </li> </ul> * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>NONE, ALL_OLD, UPDATED_OLD, ALL_NEW, UPDATED_NEW */ @property (nonatomic, retain) NSString *returnValues; /** * If set to <code>TOTAL</code>, the response includes * <i>ConsumedCapacity</i> data for tables and indexes. If set to * <code>INDEXES</code>, the repsonse includes <i>ConsumedCapacity</i> * for indexes. If set to <code>NONE</code> (the default), * <i>ConsumedCapacity</i> is not included in the response. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>INDEXES, TOTAL, NONE */ @property (nonatomic, retain) NSString *returnConsumedCapacity; /** * If set to <code>SIZE</code>, statistics about item collections, if * any, that were modified during the operation are returned in the * response. If set to <code>NONE</code> (the default), no statistics are * returned. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>SIZE, NONE */ @property (nonatomic, retain) NSString *returnItemCollectionMetrics; /** * Default constructor for a new PutItemRequest object. Callers should use the * property methods to initialize this object after creating it. */ -(id)init; /** * Constructs a new PutItemRequest object. * Callers should use properties to initialize any additional object members. * * @param theTableName The name of the table to contain the item. * @param theItem A map of attribute name/value pairs, one for each * attribute. Only the primary key attributes are required; you can * optionally provide other attribute name-value pairs for the item. * <p>If you specify any attributes that are part of an index key, then * the data types for those attributes must match those of the schema in * the table's attribute definition. <p>For more information about * primary keys, see <a * modb/latest/developerguide/DataModel.html#DataModelPrimaryKey">Primary * Key</a> in the Amazon DynamoDB Developer Guide. <p>Each element in the * <i>Item</i> map is an <i>AttributeValue</i> object. */ -(id)initWithTableName:(NSString *)theTableName andItem:(NSMutableDictionary *)theItem; /** * Set a value in the dictionary item for the specified key. * This function will alloc and init item if not already done. */ -(void)setItemValue:(DynamoDBAttributeValue *)theValue forKey:(NSString *)theKey; /** * Set a value in the dictionary expected for the specified key. * This function will alloc and init expected if not already done. */ -(void)setExpectedValue:(DynamoDBExpectedAttributeValue *)theValue forKey:(NSString *)theKey; /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. */ -(NSString *)description; @end
40.460733
93
0.715321
[ "object" ]
7f32be7a397e77a1ca2ef238a0bca4ad5a95e128
24,104
h
C
base/new/include/user/window.h
gramado/field
c45fb8a3435b2f13b8b48d96567074fb19f02e31
[ "BSD-2-Clause" ]
9
2022-02-02T18:32:31.000Z
2022-03-24T11:24:42.000Z
base/new/include/user/window.h
elenderg/field
c45fb8a3435b2f13b8b48d96567074fb19f02e31
[ "BSD-2-Clause" ]
2
2022-02-16T17:22:40.000Z
2022-03-03T17:04:05.000Z
base/new/include/user/window.h
elenderg/field
c45fb8a3435b2f13b8b48d96567074fb19f02e31
[ "BSD-2-Clause" ]
2
2022-02-08T14:25:33.000Z
2022-03-03T16:27:32.000Z
// window.h // ring0, kernel base. #ifndef __WINDOW_H #define __WINDOW_H 1 #define KGWS_ZORDER_BOTTOM 0 #define KGWS_ZORDER_TOP 1023 //top window #define KGWS_ZORDER_MAX 1024 //max // #importante: // Tipos de mensagem de comunicação nos diálogos // e procesimento de janelas: // // SIGNAL_ Sinal. Não contém argumentos. // MSG_ Message. Contém os argumentos padrão. // STREAMMSG_ Streams. O argumento é um ponteiro para uma stream. // BUFFER_MSG_ Buffer. O argumento é um ponteiro para um buffer. // CAT_MSG_ Concatenate. Os argumentos long1 e long devem ser concatenados. // Window handle status // Se uma janela está aberta ou não. #define HANDLE_STATUS_CLOSE 0 #define HANDLE_STATUS_OPEN 1 //used #define WINDOW_NOTUSED 0 #define WINDOW_USED 1 #define WINDOW_GC 216 //Sinalizada para o GC. //... //magic #define WINDOW_NOTMAGIC 0 #define WINDOW_MAGIC 1234 #define WINDOW_CLOSED 4321 //... //desktop window. (Área de trabalho) //#define MAINWINDOW_DEFAULTX ? //#define MAINWINDOW_DEFAULTY ? // Número máximo de janelas. //@todo: Aumentar esse tamanho. // # window lock support # #define WINDOW_LOCKED 1 #define WINDOW_UNLOCKED 0 /* *********************************************** * Messages. * mensagens para procedimentos de janelas e * para diálogos dentro do gws. * Obs: Isso refere-se principalmente à janelas. */ //??tipos de mensagens ?? #define MSG_NULL 0 #define SIGNAL_NULL 0 #define STREAM_MSG_NULL 0 #define BUFFER_MSG_NULL 0 #define CAT_MSG_NULL 0 //window (1-19) #define MSG_CREATE 1 #define MSG_DESTROY 2 #define MSG_MOVE 3 #define MSG_SIZE 4 #define MSG_RESIZE 5 //#define MSG_OPEN 6 #define MSG_CLOSE 7 #define MSG_PAINT 8 #define MSG_SETFOCUS 9 #define MSG_KILLFOCUS 10 #define MSG_ACTIVATE 11 #define MSG_SHOWWINDOW 12 #define MSG_SETCURSOR 13 #define MSG_HIDE 14 // ?? (MIN) //#define MSG_MINIMIZE 14 // ?? (MIN) #define MSG_MAXIMIZE 15 #define MSG_RESTORE 16 #define MSG_SHOWDEFAULT 17 //keyboard (20-29) #define MSG_KEYDOWN 20 #define MSG_KEYUP 21 #define MSG_SYSKEYDOWN 22 #define MSG_SYSKEYUP 23 // mouse (30 - 39) #define MSG_MOUSEKEYDOWN 30 #define MSG_MOUSEKEYUP 31 #define MSG_MOUSEBUTTONDOWN 30 #define MSG_MOUSEBUTTONUP 31 #define MSG_MOUSEMOVE 32 #define MSG_MOUSEOVER 33 #define MSG_MOUSEWHEEL 34 #define MSG_MOUSEPRESSED 35 #define MSG_MOUSERELEASED 36 #define MSG_MOUSECLICKED 37 #define MSG_MOUSEENTERED 38 //?? capturou ?? #define MSG_MOUSEEXITED 39 //?? descapturou ?? //#define MSG_MOUSEMOVEBYOFFSET //#define MSG_MOUSEMOVETOELEMENT //outros (40 - ...) #define MSG_COMMAND 40 #define MSG_CUT 41 #define MSG_COPY 42 #define MSG_PASTE 43 #define MSG_CLEAR 44 #define MSG_UNDO 45 #define MSG_INSERT 46 #define MSG_RUN_PROCESS 47 #define MSG_RUN_THREAD 48 //Quando um comando é enviado para o terminal. ele será atendido pelo //módulo /sm no procedimento de janela do sistema. //Todas as mensagens de terminal serão atencidas pelo procedimento de janela //nessa mensagem. //#bugbug: temos outro grupo de mensagems abordadndo esse tema logo abaixo. #define MSG_TERMINAL_COMMAND 49 #define MSG_TERMINAL_SHUTDOWN 50 #define MSG_TERMINAL_REBOOT 51 #define MSG_DEVELOPER 52 //UM TIMER SE ESGOTOU, #define MSG_TIMER 53 //... //o servidor de rede se comunica com o processo. #define MSG_AF_INET 54 #define MSG_NET_DATA_IN 55 //o driver de network está notificando um processo em ring3. #define MSG_NETWORK_NOTIFY_PROCESS 56 // // mouse support: continuação ... // #define MSG_MOUSE_DOUBLECLICKED 60 #define MSG_MOUSE_DRAG 61 #define MSG_MOUSE_DROP 62 //... // // terminal commands // #define MSG_TERMINALCOMMAND 100 #define TERMINALCOMMAND_PRINTCHAR 1000 //#define TERMINALCOMMAND_PRINT??? 1001 //... // o evento de rolagem aconteceu ... // O número do evento será entregue em long1. #define MSG_HSCROLL 2000 #define MSG_VSCROLL 2001 // // ==== Window Type ==== // #define WT_NULL 0 #define WT_SIMPLE 1 // Igual simples, mais uma bordinha preta. #define WT_EDITBOX 2 // Sobreposta (completa)(barra de titulo + borda +client area). #define WT_OVERLAPPED 3 // Um tipo especial de sobreposta, usada em dialog ou message box. // (com ou sem barra de titulo ou borda) #define WT_POPUP 4 // Caixa de seleção. Caixa de verificação. // Quadradinho. #define WT_CHECKBOX 5 // Cria uma scroll bar. // Para ser usada como janela filha. #define WT_SCROLLBAR 6 #define WT_EDITBOX_MULTIPLE_LINES 7 #define WT_BUTTON 8 #define WT_STATUSBAR 9 // Pequeno retângulo com uma imagem bmp e talvez texto. #define WT_ICON 10 #define WT_TITLEBAR 11 //... // window style #define WINDOW_STYLE_FLOATING 1000 #define WINDOW_STYLE_DOCKING 2000 //(atracada em algum canto.) //... // window status #define WINDOW_STATUS_ACTIVE 1 #define WINDOW_STATUS_INACTIVE 0 //... //window relationship status. (seu status em relação as outras janelas.) //Obs: tem uma estreita ligação com o status da thread que está trabalahndo com ela //e com a prioridade dessa thread e do processo que a possui. // *** RELAÇÃO IMPLICA PRIORIDADE *** #define WINDOW_REALATIONSHIPSTATUS_FOREGROUND 1000 #define WINDOW_REALATIONSHIPSTATUS_BACKGROUND 2000 #define WINDOW_REALATIONSHIPSTATUS_OWNED 3000 //Possuida por outra janela. #define WINDOW_REALATIONSHIPSTATUS_ZAXIS_TOP 4000 #define WINDOW_REALATIONSHIPSTATUS_ZAXIS_BOTTOM 6000 //... // Apresentação. #define VIEW_NULL 0 #define VIEW_FULL 1 #define VIEW_MAXIMIZED 2 #define VIEW_MINIMIZED 4 #define VIEW_NORMAL 8 // Normal (restaurada) // ... // // ## botoes ## // //button state #define BS_NULL 0 #define BS_DEFAULT 1 #define BS_FOCUS 2 #define BS_PRESS 3 #define BS_HOVER 4 #define BS_DISABLED 5 #define BS_PROGRESS 6 //... //button states: //0. NULL. //1. Default //2. Focus //3. Expanded/Toggled/Selected //4. Disabled //5. Hover and Active //#define BN_CLICKED 200 //#define BN_DOWN 1 //#define BN_UP 2 //#define BN_SELECTED 3 //@todo: what ??? //?? um handle para o desktop. #define HWND_DESKTOP 0 /* * Dimensões: * * Parametro principal para dimensões de janela. * todos os outros tomam esse como refêrencia. * depende do modo que estiver usando. * * vesa 112: * * 640x480x24bit - (3 bytes por pixel) * * @todo, o kernel usará dimensões 640x480 no modo gráfico. */ #define KERNEL_COL_MAX 640 #define KERNEL_LIN_MAX 480 #define BAR_STEPS 46 #define LINE KERNEL_COL_MAX //dimensões - provisorio #define COL_MAX KERNEL_COL_MAX #define LINHA_MAX KERNEL_LIN_MAX /* * Constants para a task bar. */ //#define TASKBUTTONS_BASE 40 //#define CLOCK_BASE (KERNEL_COL_MAX-40) //========================================= // **** KERNEL WINDOW **** //Definições padronizadas para janelas do kernel usadas para //fornecer informações sobre o sistema. // (Retângulo grande no topo da tela.) // #bugbug // Isso não é uma coisa boa. #define KERNEL_WINDOW_DEFAULT_LEFT 0 #define KERNEL_WINDOW_DEFAULT_TOP 0 #define KERNEL_WINDOW_DEFAULT_WIDTH 800 #define KERNEL_WINDOW_DEFAULT_HEIGHT (600/4) #define KERNEL_WINDOW_DEFAULT_CLIENTCOLOR xCOLOR_GRAY2 #define KERNEL_WINDOW_DEFAULT_BGCOLOR xCOLOR_GRAY1 //... // // ESSA VARIÁVEL BLOQUEIA O FOCO NA JANELA DO DESENVOLVEDOR // int _lockfocus; // ESSA SERÁ USADA DEPOIS QUANDO A INTERFACE GRÁFICA ESTIVER MAIS ROBUSTA; int gFocusBlocked; // #todo: deletar. //unsigned long g_mainwindow_width; //unsigned long g_mainwindow_height; //unsigned long g_navigationbar_width; //unsigned long g_navigationbar_height; /* ************************************************** * rect_d: * Estrutura para gerenciamento de retângulos. * Um retângulo pertence à uma janela. */ // #todo // Usar isso para lidar com dirty rectangles. struct rect_d { object_type_t objectType; object_class_t objectClass; int used; int magic; // // Invalidate // // Sujo de tinta. // If the rectangle is dirty, so it needs to be flushed into // the framebuffer. // When we draw a window it needs to be invalidated. int dirty; int flag; // Estilo de design int style; //dimensoes unsigned long x; unsigned long y; unsigned long cx; unsigned long cy; //margins unsigned long left; unsigned long top; unsigned long width; unsigned long height; unsigned long right; unsigned long bottom; // 32 bit unsigned int bg_color; struct rect_d *next; }; // Isso pode ser útil principalmente // para passar um retângulo de um ambiente para outro. // É muito mais didático que a figura do retângulo como objeto. struct surface_d { int used; int magic; int dirty; struct rect_d *rect; struct surface_d *next; }; // #todo // struct surface_d *backbuffer_surface; /* rgba */ struct tagRGBA { object_type_t objectType; object_class_t objectClass; char red; char green; char blue; char alpha; }; struct tagRGBA *RGBA; // // Window Class support. // // ?? rever. // Enumerando classe de janela typedef enum { WindowClassNull, WindowClassClient, // 1 cliente WindowClassKernel, // 2 kernel WindowClassServer, // 3 servidor }wc_t; //classes de janelas controladas pelos aplicativos. typedef enum { WindowClassApplicationWindow, //... }client_window_classes_t; //??bugbug: tá errado. //classes de janelas controladas exclusivamente pelo kernel. typedef enum { WindowClassKernelWindow, //janelas criadas pelo kernel ... coma a "tela azul da morte" WindowClassTerminal, //janela de terminal usada pelos aplicativos que não criam janela e gerenciada pelo kernel WindowClassButton, WindowClassComboBox, WindowClassEditBox, WindowClassListBox, WindowClassScrollBar, WindowClassMessageOnly, //essa janela não é visível, serve apenas para troca de mensagens ... WindowClassMenu, WindowClassDesktopWindow, WindowClassDialogBox, WindowClassMessageBox, WindowClassTaskSwitchWindow, WindowClassIcons, WindowClassControl, //?? WindowClassDialog, WindowClassInfo, //... }kernel_window_classes_t; //classes de janelas controladas pelos servidores. typedef enum { WindowClassServerWindow, //... }server_window_classes_t; //estrutura para window class struct window_class_d { //Que tipo de window class. // do sistema, dos processos ... //tipo de classe. wc_t windowClass; //1 client_window_classes_t clientClass; //2 kernel_window_classes_t kernelClass; //3 server_window_classes_t serverClass; //Endereço do procedimento de janela. //(eip da thread primcipal do app) unsigned long procedure; //... }; // Single message struct model. struct msg_d { // validation int used; int magic; // Standard header. struct window_d *window; int msg; unsigned long long1; unsigned long long2; // extra payload. unsigned long long3; unsigned long long4; // Extention: pid_t sender_pid; pid_t receiver_pid; int sender_tid; int receiver_tid; // ... // #todo // We need some synchronization flags. // Maybe its better putting this flag into the thread struct. // t->msg_flags; //unsigned long flags; }; // #deprecated struct window_d { int dummy_deprecated; //int used; //int magic; }; struct window_d *CurrentWindow; //Janela atual struct window_d *ActiveWindow; //Janela atual. struct window_d *WindowWithFocus; //Janela com o foco de entrada. //... // Lista encadeada de janelas. struct window_d *window_Conductor2; struct window_d *window_Conductor; struct window_d *window_rootConductor; //... // // Window list. // unsigned long windowList[WINDOW_COUNT_MAX]; // ?? unsigned long Windows[KGWS_ZORDER_MAX]; //id da janela que o mouse está em cima. int window_mouse_over; // // ## Ponteiros para ícones ## // // Ponteiros para o endereço onde os ícones // foram carregados. // queremos saber se o endereço alocado eh compartilhado ... // para o window server usar ... entao chamaremos de sharedbufferIcon. void *shared_buffer_app_icon; //1 void *shared_buffer_file_icon; void *shared_buffer_folder_icon; void *shared_buffer_terminal_icon; void *shared_buffer_cursor_icon; // ... //?? // struct window_d *FULLSCREEN_TABWINDOW; // // == z order support ========================= // //#define ZORDER_COUNT_MAX 128 //??PROVISÓRIO //esses tipo indicam algum posicionamento dentro da xorder. typedef enum { zordertypeNull, //ignorado zordertypeTop, //acima de todas zordertypeBottom, //abaixo de rodas. //... }zorder_type_t; //essas são as camadas onde os objetos gráficos ficam ... //estão associadas com formulários e containers. typedef enum { zorderlayerNull, //ignorado zorderlayerBack, //back layer. é a área onde os métodos invocarão a construção de objetos gráficos. zorderlayerMiddle, //middle layer. é onde os objetos gráficos e as etiquetas de controle são colocadas. zorderlayerFront, //front layer. são colocados os controles não gráficos como: //CommandButton, CheckBox e ListBox //... }zorder_layer_t; // //Estrutura para controlar um índice de janela //ponteiros de instãncias dessa estrutura ficarão na lista zorderList[]. // Obs: uma estrutura de janela pode ter um poteiro para essa // estrutura que controlará todas as propriedades de zorder relaticas a aquela janela. // struct zorder_d { // tipo ... top ou bottom. //encontraremos com facilidade se ela é top ou bottom. //zorder_type_t zorderType; //zorder_layer_t zorderLayer; int zIndex; //?? ... struct window_d *window; //toda janela está na lista de zorder de outra janela. struct window_d *parent; //janela mãe... struct zorder_d *next; }; /* struct zorderInfo { struct window *top_window; } */ int zorder; int zorderCounter; //contador de janelas incluidas nessa lista. int zorderTopWindow; //... /* * zorderList[] support. * Sobreposição de janelas. * ?? Precisamos reorganizar a lista ?? * ?? seria melhor uma lista encadeada ?? * ??e quando fecharem uma janela no meio da lista ?? * * >> Quando criamos uma janela ela é incluída no primeiro lugar vago da lista. * >> quando deletamos uma janela, apenas excluimos ela da lista, não precisamos reorganizar. * >> uma janelas minimizada é excluida dessa lista, é zerada z_axis_order na sua estrutura. * >> repintaremos começando do zero. */ //unsigned long zorderList[ZORDER_COUNT_MAX]; // // Backbuffer support. (espelho da memória de video) // struct backbufferinfo_d { //@todo: object support int used; int magic; unsigned long start; unsigned long end; unsigned long size; //... //@todo: // ?? O que nos podemos ter aqui ?? // terminal., window, line disciplice, cursor ... //input buffer? z-order ?? }; struct backbufferinfo_d *BackBufferInfo; // // Frontbuffer support. (memória de vídeo) // struct frontbufferinfo_d { //@todo: object support int used; int magic; unsigned long start; unsigned long end; unsigned long size; unsigned long width; unsigned long height; unsigned long bpp; // //@todo: // ?? O que nos podemos ter aqui ?? // terminal., window, line disciplice, cursor ... }; struct frontbufferinfo_d *FrontBufferInfo; /* ********************************************************** * gui: * Nível 0 * ## gui ## * * Obs: Foi incluído aqui os ponteiros para as janelas principais usadas nos * principais recursos gráficos, como control menu do desktop por exemplo. * * Histórico: * 2015 - Created. * 2016 - incluíndo novos elementos. * ... */ // #bugbug // Muita coisa nessa estrutura precis ser revista. // Tendo em vista que ela apenas contempla o kgws // como provedor de recursos gráficos. // Dessa forma essa estrutura só faz sentido no ambiente // de setup, que usa o kgws. struct gui_d { int initialised; // Procedimento da janela ativa. unsigned long procedure; // #bugbug // precisamos de estrutura de device context, // onde teremos informações sobre o hardware // responsável pelos recursos gráficos. // BUFFERS // Ponteiros para os principais buffers usados pelo sistema. // LFB: // O endereço do início da memória de vídeo do cartão de memória. // obs: Quantos desses ponteiros precisamos dentro da memória de // vídeo? E se tivermos várias placas de memória de vídeo, seria // um lfb para cada placa? // Esse valor foi configurado pelo BIOS pelo metodo VESA. unsigned long lfb; // unsigned long lfb_pa; //use this one // Backbuffer // O Backbuffer pe o buffer para colocar a imagem de pano de fundo. // Ele será o buffer dedicado da janela principal gui->main. // #importante. // Um backbuffer pode cobrir a área de vários monitores. // O conceito de backbuffer pode estar relacionado com o conceito de room, // (window station), com vários desktops e monitores. unsigned long backbuffer; //unsigned long backbuffer_pa; //use this one void *backbuffer1; void *backbuffer2; void *backbuffer3; // ... /* * Default dedicated buffers. * Esses ponteiros podem ser usados para aloca * memória para buffer dedicado antes mesmo de se criar a estrutura * da janela. * Obs: Toda janela tem que ter um buffer dedicado, onde ela será pintada. * Depois de pintada ela pertencerá a uma lista de janelas que serão * enviadas para o LFB seguindo a ordem da lista. */ //void* defaultWindowDedicatedBuffer1; //void* defaultWindowDedicatedBuffer2; //void* defaultWindowDedicatedBuffer3; //... // redraw // Flag para repintar todas as janelas. // #todo: #bugbug, Isso parece estranho. Cada janela // está pintada em seu buffer dedicado e fica por conta de // cada janela decidir se repinta ou não apenas ela. int redraw; // refresh // Flag para enviar do backbuffer para a memória de video. // Seguindo uma lista linkada, copiaremos o conteúdo do buffer // dedicado de cada janela da lista no LFB. Primeiro é Backbuffer // que é o buffer da janela principal, que funcionará como // Head da lista. int refresh; // status das janelas usadas pelo sistema. int screenStatus; int backgroundStatus; int logoStatus; int mainStatus; int navigationbarStatus; int menuStatus; int taskbarStatus; int statusbarStatus; int infoboxStatus; int messageboxStatus; int debugStatus; int gridStatus; /* * Windows * * Obs: * Ponteiros para as janelas principais usadas na interfáce * gráfica. Essas janelas não dependem dos processos e sim os * processos dependem delas. Os processos do sistema poderão recriar * essas janelas e registrar seus ponteiros aqui. Por exemplo, o control * menu pode sofrer alterações e depois registrar o ponteiro aqui. * Outro exemplo é o control menu da janela ativa, toda vez que * trocar a janela ativa, deve-se registrar o ponteiro do control menu * da janela aqui, para fácil acesso. * * Os ponteiros aqui serão organizados em grupos: * ============================================== * Screen - root window * Grupo 0: Background, Logo, Desktop, Taskbar. * Grupo 1: Main (Full Screen), Status Bar. * Grupo 2: Grid. (grid de ícones flutuantes) * Grupo 3: Control menu.(Control menu da janel atual). * Grupo 4: Info Box, ToolTip. * Grupo 5: ?? * Grupo 6: Outras. */ // // Security // struct usession_d *CurrentUserSession; struct room_d *CurrentRoom; struct desktop_d *CurrentDesktop; // // User info. // //struct user_info_d *User; //... }; // #importante // Estrutura global. // (Usada para passar estutura entre funções) struct gui_d *gui; // // == prototypes ================ // // // pixel // void putpixel0 ( unsigned int _color, unsigned long _x, unsigned long _y, unsigned long _rop_flags, unsigned long buffer_va ); void backbuffer_putpixel ( unsigned int _color, unsigned long _x, unsigned long _y, unsigned long _rop_flags ); void frontbuffer_putpixel ( unsigned int _color, unsigned long _x, unsigned long _y, unsigned long _rop_flags ); // // char // void set_char_width ( int width ); void set_char_height (int height); int get_char_width (void); int get_char_height (void); void d_draw_char ( unsigned long x, unsigned long y, unsigned long c, unsigned int fgcolor, unsigned int bgcolor ); void d_drawchar_transparent ( unsigned long x, unsigned long y, unsigned int color, unsigned long c ); // // string // void draw_string ( unsigned long x, unsigned long y, unsigned int color, char *string ); // // x_panic // void x_panic( char *string ); void xxxDrawString( char *string ); // // line // void backbuffer_draw_horizontal_line ( unsigned long x1, unsigned long y, unsigned long x2, unsigned int color, unsigned long rop_flags ); void frontbuffer_draw_horizontal_line ( unsigned long x1, unsigned long y, unsigned long x2, unsigned int color, unsigned long rop_flags ); // // Draw rectangle into the backbuffer. // void drawrectangle0( unsigned long x, unsigned long y, unsigned long width, unsigned long height, unsigned int color, unsigned long rop_flags, int back_or_front ); void backbuffer_draw_rectangle( unsigned long x, unsigned long y, unsigned long width, unsigned long height, unsigned int color, unsigned long rop_flags ); void frontbuffer_draw_rectangle( unsigned long x, unsigned long y, unsigned long width, unsigned long height, unsigned int color, unsigned long rop_flags ); void drawDataRectangle ( unsigned long x, unsigned long y, unsigned long width, unsigned long height, unsigned int color, unsigned long rop_flags ); void refresh_rectangle0 ( unsigned long x, unsigned long y, unsigned long width, unsigned long height, unsigned long buffer_dest, unsigned long buffer_src ); void refresh_rectangle ( unsigned long x, unsigned long y, unsigned long width, unsigned long height ); void scroll_screen_rect (void); void *rectStrCopyMemory32 ( unsigned long *dest, unsigned long *src, int count ); // // Background // int Background_initialize(void); void backgroundDraw (unsigned int color); // // == wm ===================== // // See: kgwm.c unsigned long wmProcedure ( struct window_d *window, int msg, unsigned long long1, unsigned long long2 ); // See: kgwm.c void wmRegisterWSCallbacks( unsigned long callback0, unsigned long callback1, unsigned long callback2 ); // Send input to the window manager // inside the window server // gwssrv.bin unsigned long wmSendInputToWindowManager( unsigned long wid, unsigned long msg, unsigned long long1, unsigned long long2); void exit_kernel_console(void); void kgwm_early_kernel_console(void); // ========== // Pega um scancode, transforma em caractere e envia na forma de mensagem // para a thread de controle associada com a janela que tem o foco de entrada. int xxxKeyEvent ( int tid, unsigned char raw_byte ); int xxxMouseEvent(int event_id,long long1, long long2); #endif
21.014821
117
0.680053
[ "object", "model" ]
7f3683d2071d74dd0ed9b24ca57e6f6ef7483d03
9,822
h
C
src/xr_3da/xrRender_R2/r2.h
acidicMercury8/xray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
2
2020-01-30T12:51:49.000Z
2020-08-31T08:36:49.000Z
src/xr_3da/xrRender_R2/r2.h
acidicMercury8/xray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
null
null
null
src/xr_3da/xrRender_R2/r2.h
acidicMercury8/xray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
null
null
null
#pragma once #include "..\xrRender\r__dsgraph_structure.h" #include "..\xrRender\r__occlusion.h" #include "..\xrRender\PSLibrary.h" #include "r2_types.h" #include "r2_rendertarget.h" #include "..\xrRender\hom.h" #include "..\xrRender\detailmanager.h" #include "..\xrRender\modelpool.h" #include "..\xrRender\wallmarksengine.h" #include "smap_allocator.h" #include "..\xrRender\light_db.h" #include "light_render_direct.h" #include "..\xrRender\LightTrack.h" #include "../irenderable.h" #include "../fmesh.h" // definition class CRender : public R_dsgraph_structure { public: enum { PHASE_NORMAL = 0, // E[0] PHASE_SMAP = 1, // E[1] }; public: struct _options { u32 bug : 1; u32 smapsize : 16; u32 depth16 : 1; u32 mrt : 1; u32 mrtmixdepth : 1; u32 fp16_filter : 1; u32 fp16_blend : 1; u32 albedo_wo : 1; // work-around albedo on less capable HW u32 HW_smap : 1; u32 HW_smap_PCF : 1; u32 HW_smap_FETCH4 : 1; u32 HW_smap_FORMAT : 32; u32 nvstencil : 1; u32 nvdbt : 1; u32 nullrt : 1; u32 distortion : 1; u32 distortion_enabled : 1; u32 mblur : 1; u32 sunfilter : 1; u32 sunstatic : 1; u32 sjitter : 1; u32 noshadows : 1; u32 Tshadows : 1; // transluent shadows u32 disasm : 1; u32 forcegloss : 1; u32 forceskinw : 1; float forcegloss_v ; } o; struct _stats { u32 l_total, l_visible; u32 l_shadowed, l_unshadowed; s32 s_used, s_merged, s_finalclip; u32 o_queries, o_culled; u32 ic_total, ic_culled; } stats; public: // Sector detection and visibility CSector* pLastSector; Fvector vLastCameraPos; u32 uLastLTRACK; xr_vector<IRender_Portal*> Portals; xr_vector<IRender_Sector*> Sectors; xrXRC Sectors_xrc; CDB::MODEL* rmPortals; CHOM HOM; R_occlusion HWOCC; // Global vertex-buffer container xr_vector<FSlideWindowItem> SWIs; xr_vector<ref_shader> Shaders; typedef svector<D3DVERTEXELEMENT9,MAXD3DDECLLENGTH+1> VertexDeclarator; xr_vector<VertexDeclarator> nDC,xDC; xr_vector<IDirect3DVertexBuffer9*> nVB,xVB; xr_vector<IDirect3DIndexBuffer9*> nIB,xIB; xr_vector<IRender_Visual*> Visuals; CPSLibrary PSLibrary; CDetailManager* Details; CModelPool* Models; CWallmarksEngine* Wallmarks; CRenderTarget* Target; // Render-target CLight_DB Lights; CLight_Compute_XFORM_and_VIS LR; xr_vector<light*> Lights_LastFrame; SMAP_Allocator LP_smap_pool; light_Package LP_normal; light_Package LP_pending; xr_vector<Fbox3,render_alloc<Fbox3> > main_coarse_structure; shared_str c_sbase ; shared_str c_lmaterial ; float o_hemi ; float o_sun ; IDirect3DQuery9* q_sync_point[2] ; u32 q_sync_count ; private: // Loading / Unloading void LoadBuffers (CStreamReader *fs, BOOL _alternative); void LoadVisuals (IReader *fs); void LoadLights (IReader *fs); void LoadPortals (IReader *fs); void LoadSectors (IReader *fs); void LoadSWIs (CStreamReader *fs); BOOL add_Dynamic (IRender_Visual *pVisual, u32 planes); // normal processing void add_Static (IRender_Visual *pVisual, u32 planes); void add_leafs_Dynamic (IRender_Visual *pVisual); // if detected node's full visibility void add_leafs_Static (IRender_Visual *pVisual); // if detected node's full visibility public: IRender_Sector* rimp_detectSector (Fvector& P, Fvector& D); void render_main (Fmatrix& mCombined, bool _fportals); void render_forward (); void render_smap_direct (Fmatrix& mCombined); void render_indirect (light* L ); void render_lights (light_Package& LP ); void render_sun (); void render_sun_near (); void render_sun_filtered (); void render_menu (); public: ShaderElement* rimp_select_sh_static (IRender_Visual *pVisual, float cdist_sq); ShaderElement* rimp_select_sh_dynamic (IRender_Visual *pVisual, float cdist_sq); D3DVERTEXELEMENT9* getVB_Format (int id, BOOL _alt=FALSE); IDirect3DVertexBuffer9* getVB (int id, BOOL _alt=FALSE); IDirect3DIndexBuffer9* getIB (int id, BOOL _alt=FALSE); FSlideWindowItem* getSWI (int id); IRender_Portal* getPortal (int id); IRender_Sector* getSectorActive (); IRender_Visual* model_CreatePE (LPCSTR name); IRender_Sector* detectSector (const Fvector& P, Fvector& D); // HW-occlusion culling IC u32 occq_begin (u32& ID ) { return HWOCC.occq_begin (ID); } IC void occq_end (u32& ID ) { HWOCC.occq_end (ID); } IC u32 occq_get (u32& ID ) { return HWOCC.occq_get (ID); } ICF void apply_object (IRenderable* O) { if (0==O) return; if (0==O->renderable_ROS()) return; CROS_impl& LT = *((CROS_impl*)O->renderable_ROS()); LT.update_smooth (O) ; o_hemi = 0.75f*LT.get_hemi () ; o_sun = 0.75f*LT.get_sun () ; } IC void apply_lmaterial () { R_constant* C = &*RCache.get_c (c_sbase); // get sampler if (0==C) return; VERIFY (RC_dest_sampler == C->destination); VERIFY (RC_sampler == C->type); CTexture* T = RCache.get_ActiveTexture (u32(C->samp.index)); VERIFY (T); float mtl = T->m_material; #ifdef DEBUG if (ps_r2_ls_flags.test(R2FLAG_GLOBALMATERIAL)) mtl=ps_r2_gmaterial; #endif RCache.set_c (c_lmaterial,o_hemi,o_sun,0,(mtl+.5f)/4.f); } public: // feature level virtual GenerationLevel get_generation () { return IRender_interface::GENERATION_R2; } // Loading / Unloading virtual void create (); virtual void destroy (); virtual void reset_begin (); virtual void reset_end (); virtual void level_Load (IReader*); virtual void level_Unload (); virtual IDirect3DBaseTexture9* texture_load (LPCSTR fname, u32& msize); virtual HRESULT shader_compile ( LPCSTR name, LPCSTR pSrcData, UINT SrcDataLen, void* pDefines, void* pInclude, LPCSTR pFunctionName, LPCSTR pTarget, DWORD Flags, void* ppShader, void* ppErrorMsgs, void* ppConstantTable); // Information virtual void Statistics (CGameFont* F); virtual LPCSTR getShaderPath () { return "r2\\"; } virtual ref_shader getShader (int id); virtual IRender_Sector* getSector (int id); virtual IRender_Visual* getVisual (int id); virtual IRender_Sector* detectSector (const Fvector& P); virtual IRender_Target* getTarget (); // Main virtual void flush (); virtual void set_Object (IRenderable* O ); virtual void add_Occluder (Fbox2& bb_screenspace ); // mask screen region as oclluded virtual void add_Visual (IRender_Visual* V ); // add visual leaf (no culling performed at all) virtual void add_Geometry (IRender_Visual* V ); // add visual(s) (all culling performed) // wallmarks virtual void add_StaticWallmark (ref_shader& S, const Fvector& P, float s, CDB::TRI* T, Fvector* V); virtual void clear_static_wallmarks (); virtual void add_SkeletonWallmark (intrusive_ptr<CSkeletonWallmark> wm); virtual void add_SkeletonWallmark (const Fmatrix* xf, CKinematics* obj, ref_shader& sh, const Fvector& start, const Fvector& dir, float size); // virtual IBlender* blender_create (CLASS_ID cls); virtual void blender_destroy (IBlender* &); // virtual IRender_ObjectSpecific* ros_create (IRenderable* parent); virtual void ros_destroy (IRender_ObjectSpecific* &); // Lighting virtual IRender_Light* light_create (); virtual IRender_Glow* glow_create (); // Models virtual IRender_Visual* model_CreateParticles (LPCSTR name); virtual IRender_DetailModel* model_CreateDM (IReader* F); virtual IRender_Visual* model_Create (LPCSTR name, IReader* data=0); virtual IRender_Visual* model_CreateChild (LPCSTR name, IReader* data); virtual IRender_Visual* model_Duplicate (IRender_Visual* V); virtual void model_Delete (IRender_Visual* & V, BOOL bDiscard); virtual void model_Delete (IRender_DetailModel* & F); virtual void model_Logging (BOOL bEnable) { Models->Logging(bEnable); } virtual void models_Prefetch (); virtual void models_Clear (BOOL b_complete); // Occlusion culling virtual BOOL occ_visible (vis_data& V); virtual BOOL occ_visible (Fbox& B); virtual BOOL occ_visible (sPoly& P); // Main virtual void Calculate (); virtual void Render (); virtual void Screenshot (ScreenshotMode mode=SM_NORMAL, LPCSTR name = 0); virtual void OnFrame (); // Render mode virtual void rmNear (); virtual void rmFar (); virtual void rmNormal (); // Constructor/destructor/loader CRender (); virtual ~CRender (); }; extern CRender RImplementation;
34.829787
149
0.613521
[ "render", "model" ]
7f36abd854f2456e987a6bd8b8b927d5f2b0ceee
3,889
c
C
ext/zim/routing/compiledroute.zep.c
henter/zim-ext
df92dff89a6225c0a1a3a9882fe8345feef9c721
[ "MIT" ]
9
2019-01-16T02:15:46.000Z
2020-01-19T09:56:33.000Z
ext/zim/routing/compiledroute.zep.c
henter/zim-ext
df92dff89a6225c0a1a3a9882fe8345feef9c721
[ "MIT" ]
null
null
null
ext/zim/routing/compiledroute.zep.c
henter/zim-ext
df92dff89a6225c0a1a3a9882fe8345feef9c721
[ "MIT" ]
null
null
null
#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/object.h" #include "kernel/operators.h" #include "kernel/memory.h" /** * CompiledRoutes are returned by the RouteCompiler class. * * @author Fabien Potencier <fabien@symfony.com> */ ZEPHIR_INIT_CLASS(Zim_Routing_CompiledRoute) { ZEPHIR_REGISTER_CLASS(Zim\\Routing, CompiledRoute, zim, routing_compiledroute, zim_routing_compiledroute_method_entry, 0); zend_declare_property_null(zim_routing_compiledroute_ce, SL("variables"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(zim_routing_compiledroute_ce, SL("tokens"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(zim_routing_compiledroute_ce, SL("staticPrefix"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(zim_routing_compiledroute_ce, SL("regex"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_declare_property_null(zim_routing_compiledroute_ce, SL("pathVariables"), ZEND_ACC_PROTECTED TSRMLS_CC); return SUCCESS; } /** * @param string $staticPrefix The static prefix of the compiled route * @param string $regex The regular expression to use to match this route * @param array $tokens An array of tokens to use to generate URL for this route * @param array $pathVariables An array of path variables * @param array $variables An array of variables (variables defined in the path and in the host patterns) */ PHP_METHOD(Zim_Routing_CompiledRoute, __construct) { zval tokens, pathVariables, variables; zval *staticPrefix_param = NULL, *regex_param = NULL, *tokens_param = NULL, *pathVariables_param = NULL, *variables_param = NULL; zval staticPrefix, regex; zval *this_ptr = getThis(); ZVAL_UNDEF(&staticPrefix); ZVAL_UNDEF(&regex); ZVAL_UNDEF(&tokens); ZVAL_UNDEF(&pathVariables); ZVAL_UNDEF(&variables); ZEPHIR_MM_GROW(); zephir_fetch_params(1, 4, 1, &staticPrefix_param, &regex_param, &tokens_param, &pathVariables_param, &variables_param); zephir_get_strval(&staticPrefix, staticPrefix_param); zephir_get_strval(&regex, regex_param); zephir_get_arrval(&tokens, tokens_param); zephir_get_arrval(&pathVariables, pathVariables_param); if (!variables_param) { ZEPHIR_INIT_VAR(&variables); array_init(&variables); } else { zephir_get_arrval(&variables, variables_param); } zephir_update_property_zval(this_ptr, SL("staticPrefix"), &staticPrefix); zephir_update_property_zval(this_ptr, SL("regex"), &regex); zephir_update_property_zval(this_ptr, SL("tokens"), &tokens); zephir_update_property_zval(this_ptr, SL("pathVariables"), &pathVariables); zephir_update_property_zval(this_ptr, SL("variables"), &variables); ZEPHIR_MM_RESTORE(); } /** * Returns the static prefix. * * @return string The static prefix */ PHP_METHOD(Zim_Routing_CompiledRoute, getStaticPrefix) { zval *this_ptr = getThis(); RETURN_MEMBER(getThis(), "staticPrefix"); } /** * Returns the regex. * * @return string The regex */ PHP_METHOD(Zim_Routing_CompiledRoute, getRegex) { zval *this_ptr = getThis(); RETURN_MEMBER(getThis(), "regex"); } /** * Returns the tokens. * * @return array The tokens */ PHP_METHOD(Zim_Routing_CompiledRoute, getTokens) { zval *this_ptr = getThis(); RETURN_MEMBER(getThis(), "tokens"); } /** * Returns the variables. * * @return array The variables */ PHP_METHOD(Zim_Routing_CompiledRoute, getVariables) { zval *this_ptr = getThis(); RETURN_MEMBER(getThis(), "variables"); } /** * Returns the path variables. * * @return array The variables */ PHP_METHOD(Zim_Routing_CompiledRoute, getPathVariables) { zval *this_ptr = getThis(); RETURN_MEMBER(getThis(), "pathVariables"); }
24.770701
130
0.749293
[ "object" ]
7f3a3b70c940f49bbc43b08de615a88b15f28c94
15,242
h
C
MicroPython_RTL8722/ports/rtl8722/amebad_vendor/sdk/component/common/bluetooth/realtek/sdk/example/bt_mesh/lib/model/light_lc.h
xidameng/micropython_amebaD
5a570f45354941cc51fcb7cc70d336d361021eb5
[ "MIT" ]
4
2020-07-31T14:29:20.000Z
2021-08-02T12:32:26.000Z
MicroPython_RTL8722/ports/rtl8722/amebad_vendor/sdk/component/common/bluetooth/realtek/sdk/example/bt_mesh/lib/model/light_lc.h
xidameng/micropython_amebaD
5a570f45354941cc51fcb7cc70d336d361021eb5
[ "MIT" ]
null
null
null
MicroPython_RTL8722/ports/rtl8722/amebad_vendor/sdk/component/common/bluetooth/realtek/sdk/example/bt_mesh/lib/model/light_lc.h
xidameng/micropython_amebaD
5a570f45354941cc51fcb7cc70d336d361021eb5
[ "MIT" ]
3
2020-08-06T13:11:52.000Z
2020-11-04T10:40:47.000Z
/** ***************************************************************************************** * Copyright(c) 2015, Realtek Semiconductor Corporation. All rights reserved. ***************************************************************************************** * @file light_lc.h * @brief Head file for light lc models. * @details Data types and external functions declaration. * @author hector_huang * @date 2019-07-17 * @version v1.0 * ************************************************************************************* */ #ifndef _LIGHT_LC_H_ #define _LIGHT_LC_H_ #include "mesh_api.h" #include "generic_on_off.h" BEGIN_DECLS /** * @addtogroup LIGHT_LC * @{ */ /** * @defgroup LIGHT_LC_ACCESS_OPCODE Access Opcode * @brief Mesh message access opcode * @{ */ #define MESH_MSG_LIGHT_LC_MODE_GET 0x8291 #define MESH_MSG_LIGHT_LC_MODE_SET 0x8292 #define MESH_MSG_LIGHT_LC_MODE_SET_UNACK 0x8293 #define MESH_MSG_LIGHT_LC_MODE_STATUS 0x8294 #define MESH_MSG_LIGHT_LC_OM_GET 0x8295 #define MESH_MSG_LIGHT_LC_OM_SET 0x8296 #define MESH_MSG_LIGHT_LC_OM_SET_UNACK 0x8297 #define MESH_MSG_LIGHT_LC_OM_STATUS 0x8298 #define MESH_MSG_LIGHT_LC_LIGHT_ON_OFF_GET 0x8299 #define MESH_MSG_LIGHT_LC_LIGHT_ON_OFF_SET 0x829A #define MESH_MSG_LIGHT_LC_LIGHT_ON_OFF_SET_UNACK 0x829B #define MESH_MSG_LIGHT_LC_LIGHT_ON_OFF_STATUS 0x829C #define MESH_MSG_LIGHT_LC_PROPERTY_GET 0x829D #define MESH_MSG_LIGHT_LC_PROPERTY_SET 0x62 #define MESH_MSG_LIGHT_LC_PROPERTY_SET_UNACK 0x63 #define MESH_MSG_LIGHT_LC_PROPERTY_STATUS 0x64 /** @} */ /** * @defgroup LIGHT_LC_MODEL_ID Model ID * @brief Mesh model id * @{ */ #define MESH_MODEL_LIGHT_LC_SERVER 0x130FFFFF #define MESH_MODEL_LIGHT_LC_SETUP_SERVER 0x1310FFFF #define MESH_MODEL_LIGHT_LC_CLIENT 0x1311FFFF /** @} */ /** * @defgroup LIGHT_LC_MESH_MSG Mesh Msg * @brief Mesh message types used by models * @{ */ typedef struct { uint32_t time_fade; uint32_t time_fade_on; uint32_t time_fade_standby_auto; uint32_t time_fade_standby_manual; uint32_t time_occupancy_delay; uint32_t time_prolong; uint32_t time_run_on; } light_lc_time_t; #define LIGHT_LC_MODE_TURNED_OFF 0 #define LIGHT_LC_MODE_TURNED_ON 1 typedef struct { uint8_t opcode[ACCESS_OPCODE_SIZE(MESH_MSG_LIGHT_LC_MODE_GET)]; } _PACKED_ light_lc_mode_get_t; typedef struct { uint8_t opcode[ACCESS_OPCODE_SIZE(MESH_MSG_LIGHT_LC_MODE_SET)]; uint8_t mode; } _PACKED_ light_lc_mode_set_t; typedef struct { uint8_t opcode[ACCESS_OPCODE_SIZE(MESH_MSG_LIGHT_LC_MODE_STATUS)]; uint8_t mode; } _PACKED_ light_lc_mode_status_t; #define LIGHT_LC_OM_OCCUPANCY_NOT_FROM_STANDBY 0 #define LIGHT_LC_OM_OCCUPANCY_FROM_STANDBY 1 typedef struct { uint8_t opcode[ACCESS_OPCODE_SIZE(MESH_MSG_LIGHT_LC_OM_GET)]; } _PACKED_ light_lc_om_get_t; typedef struct { uint8_t opcode[ACCESS_OPCODE_SIZE(MESH_MSG_LIGHT_LC_MODE_SET)]; uint8_t mode; } _PACKED_ light_lc_om_set_t; typedef struct { uint8_t opcode[ACCESS_OPCODE_SIZE(MESH_MSG_LIGHT_LC_MODE_STATUS)]; uint8_t mode; } _PACKED_ light_lc_om_status_t; typedef struct { uint8_t opcode[ACCESS_OPCODE_SIZE(MESH_MSG_LIGHT_LC_LIGHT_ON_OFF_GET)]; } _PACKED_ light_lc_light_on_off_get_t; typedef struct { uint8_t opcode[ACCESS_OPCODE_SIZE(MESH_MSG_LIGHT_LC_LIGHT_ON_OFF_SET)]; generic_on_off_t light_on_off; uint8_t tid; generic_transition_time_t trans_time; uint8_t delay; } _PACKED_ light_lc_light_on_off_set_t; typedef struct { uint8_t opcode[ACCESS_OPCODE_SIZE(MESH_MSG_LIGHT_LC_LIGHT_ON_OFF_STATUS)]; generic_on_off_t present_light_on_off; generic_on_off_t target_light_on_off; generic_transition_time_t trans_time; } _PACKED_ light_lc_light_on_off_status_t; typedef struct { uint8_t opcode[ACCESS_OPCODE_SIZE(MESH_MSG_LIGHT_LC_PROPERTY_GET)]; uint16_t property_id; } _PACKED_ light_lc_property_get_t; typedef struct { uint8_t opcode[ACCESS_OPCODE_SIZE(MESH_MSG_LIGHT_LC_PROPERTY_SET)]; uint16_t property_id; uint8_t property_value[0]; } _PACKED_ light_lc_property_set_t; typedef struct { uint8_t opcode[ACCESS_OPCODE_SIZE(MESH_MSG_LIGHT_LC_PROPERTY_STATUS)]; uint16_t property_id; uint8_t property_value[0]; } _PACKED_ light_lc_property_status_t; /** @} */ /** * @defgroup LIGHT_LC_TRANSITION_TYPE Transition Type * @brief Mesh message transition and delay execution type * @{ */ #define GENERIC_TRANSITION_TYPE_LIGHT_LC 0 #define DELAY_EXECUTION_TYPE_LIGHT_LC 0 /** @} */ /** * @defgroup LIGHT_LC_SERVER_DATA Server Data * @brief Data types and structure used by data process callback * @{ */ #define LIGHT_LC_SERVER_GET_MODE 0 //!< @ref light_lc_server_get_mode_t #define LIGHT_LC_SERVER_GET_OM 1 //!< @ref light_lc_server_get_om_t #define LIGHT_LC_SERVER_GET_LIGHT_ON_OFF 2 //!< @ref light_lc_server_get_light_on_off_t #define LIGHT_LC_SERVER_GET_PROPERTY 3 //!< @ref light_lc_server_get_property_t #define LIGHT_LC_SERVER_GET_DEFAULT_TRANSITION_TIME 4 //!< @ref light_lc_server_get_default_transition_time_t #define LIGHT_LC_SERVER_GET_SM_TRANSITION_TIME 5 //!< @ref light_lc_server_get_sm_transition_time_t #define LIGHT_LC_SERVER_SET_MODE 6 //!< @ref light_lc_server_set_mode_t #define LIGHT_LC_SERVER_SET_OM 7 //!< @ref light_lc_server_set_om_t #define LIGHT_LC_SERVER_SET_LIGHT_ON_OFF 8 //!< @ref light_lc_server_set_light_on_off_t #define LIGHT_LC_SERVER_SET_PROPERTY 9 //!< @ref light_lc_server_set_property_t typedef struct { uint8_t mode; } light_lc_server_get_mode_t; typedef struct { uint8_t mode; } light_lc_server_get_om_t; typedef struct { generic_on_off_t on_off; } light_lc_server_get_light_on_off_t; typedef struct { uint16_t property_id; uint32_t property_value; uint8_t value_len; } light_lc_server_get_property_t; typedef struct { generic_transition_time_t trans_time; } light_lc_server_get_default_transition_time_t; typedef struct { generic_on_off_t light_on_off; generic_transition_time_t sm_trans_time; } light_lc_server_get_sm_transition_time_t; typedef struct { uint8_t mode; } light_lc_server_set_mode_t; typedef struct { uint8_t mode; } light_lc_server_set_om_t; typedef struct { generic_on_off_t light_on_off; generic_transition_time_t total_time; generic_transition_time_t remaining_time; } light_lc_server_set_light_on_off_t; typedef struct { uint16_t property_id; uint32_t property_value; } light_lc_server_set_property_t; /** @} */ /** * @defgroup LIGHT_LC_CLIENT_DATA Client Data * @brief Data types and structure used by data process callback * @{ */ #define LIGHT_LC_CLIENT_MODE_STATUS 0 //!< @ref light_lc_client_model_status_t #define LIGHT_LC_CLIENT_OM_STATUS 1 //!< @ref light_lc_client_om_status_t #define LIGHT_LC_CLIENT_LIGHT_ON_OFF_STATUS 2 //!< @ref light_lc_client_light_on_off_status_t #define LIGHT_LC_CLIENT_PROPERTY_STATUS 3 //!< @ref light_lc_client_property_status_t typedef struct { uint16_t src; uint8_t mode; } light_lc_client_mode_status_t; typedef struct { uint16_t src; uint8_t mode; } light_lc_client_om_status_t; typedef struct { uint16_t src; generic_on_off_t present_on_off; bool optional; generic_on_off_t target_on_off; generic_transition_time_t remaining_time; } light_lc_client_light_on_off_status_t; typedef struct { uint16_t src; uint16_t property_id; uint32_t property_value; } light_lc_client_property_status_t; /** @} */ /** * @defgroup LIGHT_LC_SERVER_API Server API * @brief Functions declaration * @{ */ /** * @brief register light lc server model * @param[in] element_index: element index that model registered to * @param[in] pmodel_info: pointer to light lc server model context * @retval TRUE: register success * @retval FALSE: register failed */ bool light_lc_server_reg(uint8_t element_index, mesh_model_info_p pmodel_info); /** * @brief register light lc setup server model * @param[in] element_index: element index that model registered to * @param[in] pmodel_info: pointer to light lc setup server model context * @retval TRUE: register success * @retval FALSE: register failed */ bool light_lc_setup_server_reg(uint8_t element_index, mesh_model_info_p pmodel_info); /** * @brief publish light lc mode * @param[in] pmodel_info: pointer to light lc server model context * @param[in] mode: light lc modeo need to publish * @return publish status */ mesh_msg_send_cause_t light_lc_mode_publish(const mesh_model_info_p pmodel_info, uint8_t mode); /** * @brief publish light lc om * @param[in] pmodel_info: pointer to light lc server model context * @param[in] om: light lc om need to publish * @return publish status */ mesh_msg_send_cause_t light_lc_om_publish(const mesh_model_info_p pmodel_info, uint8_t om); /** * @brief publish light lc light on/off * @param[in] pmodel_info: pointer to light lc server model context * @param[in] on_off: light on/off status need to publish * @return publish status */ mesh_msg_send_cause_t light_lc_light_on_off_publish(const mesh_model_info_p pmodel_info, generic_on_off_t on_off); /** * @brief publish light lc property * @param[in] pmodel_info: pointer to light lc setup server model context * @param[in] property_id: property id need to publish * @param[in] pproperty_value: property value need to publish * @param[in] len: property value length * @return publish status */ mesh_msg_send_cause_t light_lc_property_publish(const mesh_model_info_p pmodel_info, uint16_t property_id, const uint8_t *pproperty_value, uint16_t len); /** @} */ /** * @defgroup LIGHT_LC_CLIENT_API Client API * @brief Functions declaration * @{ */ /** * @brief register light lc client model * @param[in] element_index: element index that model registered to * @param[in] pmodel_info: pointer to light lc client model context * @retval true: register success * @retval false: register failed */ bool light_lc_client_reg(uint8_t element_index, mesh_model_info_p pmodel_info); /** * @brief get light lc mode value * @param[in] pmodel_info: pointer to light lc client model context * @param[in] dst: remote address * @param[in] app_key_index: mesh message used app key index * @return send status */ mesh_msg_send_cause_t light_lc_mode_get(const mesh_model_info_p pmodel_info, uint16_t dst, uint16_t app_key_index); /** * @brief set light lc mode value * @param[in] pmodel_info: pointer to light lc client model context * @param[in] dst: remote address * @param[in] app_key_index: mesh message used app key index * @param[in] mode: lc mode value * @param[in] ack: acknowledge flag * @return send status */ mesh_msg_send_cause_t light_lc_mode_set(const mesh_model_info_p pmodel_info, uint16_t dst, uint16_t app_key_index, uint8_t mode, bool ack); /** * @brief get light lc om value * @param[in] pmodel_info: pointer to light lc client model context * @param[in] dst: remote address * @param[in] app_key_index: mesh message used app key index * @return send status */ mesh_msg_send_cause_t light_lc_om_get(const mesh_model_info_p pmodel_info, uint16_t dst, uint16_t app_key_index); /** * @brief set light lc om value * @param[in] pmodel_info: pointer to light lc client model context * @param[in] dst: remote address * @param[in] app_key_index: mesh message used app key index * @param[in] mode: lc om value * @param[in] ack: acknowledge flag * @return send status */ mesh_msg_send_cause_t light_lc_om_set(const mesh_model_info_p pmodel_info, uint16_t dst, uint16_t app_key_index, uint8_t mode, bool ack); /** * @brief get light lc light on off value * @param[in] pmodel_info: pointer to light lc client model context * @param[in] dst: remote address * @param[in] app_key_index: mesh message used app key index * @return send status */ mesh_msg_send_cause_t light_lc_light_on_off_get(const mesh_model_info_p pmodel_info, uint16_t dst, uint16_t app_key_index); /** * @brief set light lc light on off value * @param[in] pmodel_info: pointer to light lc client model context * @param[in] dst: remote address * @param[in] app_key_index: mesh message used app key index * @param[in] light_on_off: desired light on off value * @param[in] tid: transition identify value * @param[in] optional: represent whether contains transition time or not * @param[in] trans_time: new transition time * @param[in] delay: new delay time * @param[in] ack: acknowledge flag * @return send status */ mesh_msg_send_cause_t light_lc_light_on_off_set(const mesh_model_info_p pmodel_info, uint16_t dst, uint16_t app_key_index, uint8_t light_on_off, uint8_t tid, bool optional, generic_transition_time_t trans_time, uint8_t delay, bool ack); /** * @brief get light lc property value * @param[in] pmodel_info: pointer to light lc client model context * @param[in] dst: remote address * @param[in] app_key_index: mesh message used app key index * @param[in] property_id: property id * @return send status */ mesh_msg_send_cause_t light_lc_property_get(const mesh_model_info_p pmodel_info, uint16_t dst, uint16_t app_key_index, uint16_t property_id); /** * @brief set light lc property value * @param[in] pmodel_info: pointer to light lc client model context * @param[in] dst: remote address * @param[in] app_key_index: mesh message used app key index * @param[in] property_id: property id * @param[in] pvalue: property value * @param[in] value_len: property value length * @param[in] property_id: property id * @param[in] ack: acknowledge flag * @return send status */ mesh_msg_send_cause_t light_lc_property_set(const mesh_model_info_p pmodel_info, uint16_t dst, uint16_t app_key_index, uint16_t property_id, uint8_t *pvalue, uint16_t value_len, bool ack); /** @} */ /** @} */ END_DECLS #endif /* _LIGHT_LC_H_ */
33.134783
123
0.692101
[ "mesh", "model" ]
7f3ae3def0c08ca9649e768b409184e4db1c39dc
7,561
h
C
Demo/Support/RenderTarget.h
jntesteves/smaa
4f471dd5f63d0ba8325c362bf65f991444712830
[ "MIT" ]
653
2015-01-11T05:17:35.000Z
2022-03-26T12:51:28.000Z
Demo/Support/RenderTarget.h
theomission/smaa
71c806a838bdd7d517df19192a20f0c61b3ca29d
[ "MIT" ]
6
2015-02-28T12:57:33.000Z
2021-12-21T19:05:14.000Z
Demo/Support/RenderTarget.h
theomission/smaa
71c806a838bdd7d517df19192a20f0c61b3ca29d
[ "MIT" ]
107
2015-01-29T21:57:32.000Z
2022-02-23T06:28:42.000Z
/** * Copyright (C) 2013 Jorge Jimenez (jorge@iryoku.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * 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. As clarification, there * is no requirement that the copyright notice and permission be included in * binary distributions 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. */ #ifndef RENDERTARGET_H #define RENDERTARGET_H #include <vector> #include <d3d10.h> #include <d3dx10.h> #include <d3d9.h> #include <dxerr.h> #include <dxgi.h> class NoMSAA : public DXGI_SAMPLE_DESC { public: inline NoMSAA() { Count = 1; Quality = 0; } }; class RenderTarget { public: RenderTarget(ID3D10Device *device, int width, int height, DXGI_FORMAT format, const DXGI_SAMPLE_DESC &sampleDesc=NoMSAA(), bool typeless=true); /** * These two are just convenience constructors to build from existing * resources. */ RenderTarget(ID3D10Device *device, ID3D10Texture2D *texture2D, DXGI_FORMAT format); RenderTarget(ID3D10Device *device, ID3D10RenderTargetView *renderTargetView, ID3D10ShaderResourceView *shaderResourceView); ~RenderTarget(); operator ID3D10Texture2D * () const { return texture2D; } operator ID3D10RenderTargetView * () const { return renderTargetView; } operator ID3D10RenderTargetView *const * () const { return &renderTargetView; } operator ID3D10ShaderResourceView * () const { return shaderResourceView; } int getWidth() const { return width; } int getHeight() const { return height; } void setViewport(float minDepth=0.0f, float maxDepth=1.0f) const; static DXGI_FORMAT makeTypeless(DXGI_FORMAT format); private: void createViews(ID3D10Device *device, D3D10_TEXTURE2D_DESC desc, DXGI_FORMAT format); ID3D10Device *device; int width, height; ID3D10Texture2D *texture2D; ID3D10RenderTargetView *renderTargetView; ID3D10ShaderResourceView *shaderResourceView; }; class DepthStencil { public: DepthStencil(ID3D10Device *device, int width, int height, DXGI_FORMAT texture2DFormat = DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT depthStencilViewFormat = DXGI_FORMAT_D32_FLOAT, DXGI_FORMAT shaderResourceViewFormat = DXGI_FORMAT_R32_FLOAT, const DXGI_SAMPLE_DESC &sampleDesc=NoMSAA()); ~DepthStencil(); operator ID3D10Texture2D * const () { return texture2D; } operator ID3D10DepthStencilView * const () { return depthStencilView; } operator ID3D10ShaderResourceView * const () { return shaderResourceView; } int getWidth() const { return width; } int getHeight() const { return height; } void setViewport(float minDepth=0.0f, float maxDepth=1.0f) const; private: ID3D10Device *device; int width, height; ID3D10Texture2D *texture2D; ID3D10DepthStencilView *depthStencilView; ID3D10ShaderResourceView *shaderResourceView; }; class BackbufferRenderTarget { public: BackbufferRenderTarget(ID3D10Device *device, IDXGISwapChain *swapChain); ~BackbufferRenderTarget(); operator ID3D10Texture2D * () const { return texture2D; } operator ID3D10RenderTargetView * () const { return renderTargetView; } operator ID3D10RenderTargetView *const * () const { return &renderTargetView; } operator ID3D10ShaderResourceView * () const { return shaderResourceView; } int getWidth() const { return width; } int getHeight() const { return height; } private: int width, height; ID3D10Texture2D *texture2D; ID3D10RenderTargetView *renderTargetView; ID3D10ShaderResourceView *shaderResourceView; }; class Quad { public: Quad(ID3D10Device *device, const D3D10_PASS_DESC &desc); ~Quad(); void setInputLayout() { device->IASetInputLayout(vertexLayout); } void draw(); private: ID3D10Device *device; ID3D10Buffer *buffer; ID3D10InputLayout *vertexLayout; }; class FullscreenTriangle { public: FullscreenTriangle(ID3D10Device *device, const D3D10_PASS_DESC &desc); ~FullscreenTriangle(); void setInputLayout() { device->IASetInputLayout(vertexLayout); } void draw(); private: ID3D10Device *device; ID3D10Buffer *buffer; ID3D10InputLayout *vertexLayout; }; class SaveViewportsScope { public: SaveViewportsScope(ID3D10Device *device); ~SaveViewportsScope(); private: ID3D10Device *device; UINT numViewports; std::vector<D3D10_VIEWPORT> viewports; }; class SaveRenderTargetsScope { public: SaveRenderTargetsScope(ID3D10Device *device); ~SaveRenderTargetsScope(); private: ID3D10Device *device; ID3D10RenderTargetView *renderTargets[D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT]; ID3D10DepthStencilView *depthStencil; }; class SaveInputLayoutScope { public: SaveInputLayoutScope(ID3D10Device *device); ~SaveInputLayoutScope(); private: ID3D10Device *device; ID3D10InputLayout *inputLayout; }; class SaveBlendStateScope { public: SaveBlendStateScope(ID3D10Device *device); ~SaveBlendStateScope(); private: ID3D10Device *device; ID3D10BlendState *blendState; FLOAT blendFactor[4]; UINT sampleMask; }; class SaveDepthStencilScope { public: SaveDepthStencilScope(ID3D10Device *device); ~SaveDepthStencilScope(); private: ID3D10Device *device; ID3D10DepthStencilState *depthStencilState; UINT stencilRef; }; class PerfEventScope { public: PerfEventScope(const std::wstring &eventName) { D3DPERF_BeginEvent(D3DCOLOR_XRGB(0, 0, 0), eventName.c_str()); } ~PerfEventScope() { D3DPERF_EndEvent(); } }; class Utils { public: static ID3D10Texture2D *createStagingTexture(ID3D10Device *device, ID3D10Texture2D *texture); static D3D10_VIEWPORT viewportFromView(ID3D10View *view); static D3D10_VIEWPORT viewportFromTexture2D(ID3D10Texture2D *texture2D); }; #endif
31.768908
121
0.664462
[ "vector" ]
7f3d0e138777ba9b1544a9e2f8c83b2b2f8b6831
10,211
h
C
src/backend/gporca/libgpos/include/gpos/common/CDynamicPtrArray.h
Tylarb/gpdb
15e1341cfbac7f70d2086a9a1d46149a82765b5e
[ "PostgreSQL", "Apache-2.0" ]
1
2021-01-01T03:11:59.000Z
2021-01-01T03:11:59.000Z
src/backend/gporca/libgpos/include/gpos/common/CDynamicPtrArray.h
Tylarb/gpdb
15e1341cfbac7f70d2086a9a1d46149a82765b5e
[ "PostgreSQL", "Apache-2.0" ]
6
2020-06-24T18:56:06.000Z
2022-02-26T08:53:11.000Z
src/backend/gporca/libgpos/include/gpos/common/CDynamicPtrArray.h
Tylarb/gpdb
15e1341cfbac7f70d2086a9a1d46149a82765b5e
[ "PostgreSQL", "Apache-2.0" ]
null
null
null
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2008 Greenplum, Inc. // // @filename: // CDynamicPtrArray.h // // @doc: // Dynamic array of pointers frequently used in optimizer data structures //--------------------------------------------------------------------------- #ifndef GPOS_CDynamicPtrArray_H #define GPOS_CDynamicPtrArray_H #include "gpos/base.h" #include "gpos/common/CRefCount.h" #include "gpos/common/clibwrapper.h" namespace gpos { // forward declaration template <class T, void (*CleanupFn)(T*)> class CDynamicPtrArray; // comparison function signature typedef INT (*CompareFn)(const void *, const void *); // frequently used destroy functions // NOOP template<class T> inline void CleanupNULL(T*) {} // plain delete template<class T> inline void CleanupDelete(T *elem) { GPOS_DELETE(elem); } // delete of array template<class T> inline void CleanupDeleteArray(T *elem) { GPOS_DELETE_ARRAY(elem); } // release ref-count'd object template<class T> inline void CleanupRelease(T *elem) { (dynamic_cast<CRefCount*>(elem))->Release(); } // commonly used array types // arrays of unsigned integers typedef CDynamicPtrArray<ULONG, CleanupDelete> ULongPtrArray; // array of unsigned integer arrays typedef CDynamicPtrArray<ULongPtrArray, CleanupRelease> ULongPtr2dArray; // arrays of integers typedef CDynamicPtrArray<INT, CleanupDelete> IntPtrArray; // array of strings typedef CDynamicPtrArray<CWStringBase, CleanupDelete> StringPtrArray; // arrays of chars typedef CDynamicPtrArray<CHAR, CleanupDelete> CharPtrArray; //--------------------------------------------------------------------------- // @class: // CDynamicPtrArray // // @doc: // Simply dynamic array for pointer types // //--------------------------------------------------------------------------- template <class T, void (*CleanupFn)(T*)> class CDynamicPtrArray : public CRefCount { private: // memory pool CMemoryPool *m_mp; // currently allocated size ULONG m_capacity; // min size ULONG m_min_size; // current size ULONG m_size; // expansion factor ULONG m_expansion_factor; // actual array T **m_elems; // comparison function for pointers static INT PtrCmp(const void *p1, const void *p2) { ULONG_PTR ulp1 = *(ULONG_PTR*)p1; ULONG_PTR ulp2 = *(ULONG_PTR*)p2; if (ulp1 < ulp2) { return -1; } if (ulp1 > ulp2) { return 1; } return 0; } // private copy ctor CDynamicPtrArray<T, CleanupFn> (const CDynamicPtrArray<T, CleanupFn> &); // resize function void Resize(ULONG new_size) { GPOS_ASSERT(new_size > m_capacity && "Invalid call to Resize, cannot shrink array"); // get new target array T **new_elems = GPOS_NEW_ARRAY(m_mp, T*, new_size); if (m_size > 0) { GPOS_ASSERT(NULL != m_elems); clib::Memcpy(new_elems, m_elems, sizeof(T*) * m_size); GPOS_DELETE_ARRAY(m_elems); } m_elems = new_elems; m_capacity = new_size; } public: // ctor explicit CDynamicPtrArray<T, CleanupFn> (CMemoryPool *mp, ULONG min_size = 4, ULONG expansion_factor = 10) : m_mp(mp), m_capacity(0), m_min_size(std::max((ULONG)4, min_size)), m_size(0), m_expansion_factor(std::max((ULONG)2, expansion_factor)), m_elems(NULL) { GPOS_ASSERT(NULL != CleanupFn && "No valid destroy function specified"); // do not allocate in constructor; defer allocation to first insertion } // dtor ~CDynamicPtrArray<T, CleanupFn> () { Clear(); GPOS_DELETE_ARRAY(m_elems); } // clear elements void Clear() { for(ULONG i = 0; i < m_size; i++) { CleanupFn(m_elems[i]); } m_size = 0; } // append element to end of array void Append(T *elem) { if (m_size == m_capacity) { // resize at least by 4 elements or percentage as given by ulExp ULONG new_size = (ULONG) (m_capacity * (1 + (m_expansion_factor/100.0))); ULONG min_expand_size = m_capacity + 4; Resize(std::max(std::max(min_expand_size, new_size), m_min_size)); } GPOS_ASSERT(m_size < m_capacity); m_elems[m_size] = elem; ++m_size; } // append array -- flatten it void AppendArray(const CDynamicPtrArray<T, CleanupFn> *arr) { GPOS_ASSERT(NULL != arr); GPOS_ASSERT(this != arr && "Cannot append array to itself"); ULONG total_size = m_size + arr->m_size; if (total_size > m_capacity) { Resize(total_size); } GPOS_ASSERT(m_size <= m_capacity); GPOS_ASSERT_IMP(m_size == m_capacity, 0 == arr->m_size); GPOS_ASSERT(total_size <= m_capacity); // at this point old memory is no longer accessible, hence, no self-copy if (arr->m_size > 0) { GPOS_ASSERT(NULL != arr->m_elems); clib::Memcpy(m_elems + m_size, arr->m_elems, arr->m_size * sizeof(T*)); } m_size = total_size; } // number of elements currently held ULONG Size() const { return m_size; } // sort array void Sort(CompareFn compare_func = PtrCmp) { clib::Qsort(m_elems, m_size, sizeof(T*), compare_func); } // equality check BOOL Equals(const CDynamicPtrArray<T, CleanupFn> *arr) const { BOOL is_equal = (Size() == arr->Size()); for (ULONG i = 0; i < m_size && is_equal; i++) { is_equal = (m_elems[i] == arr->m_elems[i]); } return is_equal; } // lookup object T* Find(const T *elem) const { GPOS_ASSERT(NULL != elem); for (ULONG i = 0; i < m_size; i++) { if (*m_elems[i] == *elem) { return m_elems[i]; } } return NULL; } // lookup object position ULONG IndexOf(const T *elem) const { GPOS_ASSERT(NULL != elem); for (ULONG ul = 0; ul < m_size; ul++) { if (*m_elems[ul] == *elem) { return ul; } } return gpos::ulong_max; } #ifdef GPOS_DEBUG // check if array is sorted BOOL IsSorted() const { for (ULONG i = 1; i < m_size; i++) { if ((ULONG_PTR)(m_elems[i - 1]) > (ULONG_PTR)(m_elems[i])) { return false; } } return true; } #endif // GPOS_DEBUG // accessor for n-th element T *operator [] (ULONG pos) const { GPOS_ASSERT(pos < m_size && "Out of bounds access"); return (T*) m_elems[pos]; } // replace an element in the array void Replace(ULONG pos, T *new_elem) { GPOS_ASSERT(pos < m_size && "Out of bounds access"); CleanupFn(m_elems[pos]); m_elems[pos] = new_elem; } // swap two array entries void Swap(ULONG pos1, ULONG pos2) { GPOS_ASSERT(pos1 < m_size && pos2 < m_size && "Swap positions out of bounds"); T *temp = m_elems[pos1]; m_elems[pos1] = m_elems[pos2]; m_elems[pos2] = temp; } // return the last element of the array and at the same time remove it from the array T *RemoveLast() { if (0 == m_size) { return NULL; } return m_elems[--m_size]; } // return the indexes of first appearances of elements of the first array // in the second array if the first array is not included in the second, // return null // equality comparison between elements is via the "==" operator ULongPtrArray *IndexesOfSubsequence(CDynamicPtrArray<T, CleanupFn> *subsequence) { GPOS_ASSERT(NULL != subsequence); ULONG subsequence_length = subsequence->Size(); ULongPtrArray *indexes = GPOS_NEW(m_mp) ULongPtrArray(m_mp); for (ULONG ul1 = 0; ul1 < subsequence_length; ul1++) { T* elem = (*subsequence)[ul1]; ULONG index = IndexOf(elem); if (gpos::ulong_max == index) { // not found indexes->Release(); return NULL; } indexes->Append(GPOS_NEW(m_mp) ULONG(index)); } return indexes; } // Eliminate members from an array that are not contained in a given list of indexes CDynamicPtrArray<T, CleanupFn> *CreateReducedArray(ULongPtrArray *indexes_to_choose) { CDynamicPtrArray<T, CleanupFn> *result = GPOS_NEW(m_mp) CDynamicPtrArray<T, CleanupFn>(m_mp, m_min_size, m_expansion_factor); ULONG list_size = indexes_to_choose->Size(); for (ULONG i = 0; i < list_size; i++) { result->Append((*this)[*((*indexes_to_choose)[i])]); } return result; } }; // class CDynamicPtrArray } #endif // !GPOS_CDynamicPtrArray_H // EOF
26.800525
100
0.509451
[ "object" ]
7f3e22355fe33423f9e32a0aed58140588216e4e
36,116
c
C
third_party/ffmpeg/libswscale/swscale.c
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
ffmpeg/libswscale/swscale.c
junlon2006/wheels
05232e05b83dbcd44ea477df4ad0666f0e08959c
[ "Apache-2.0" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
ffmpeg/libswscale/swscale.c
junlon2006/wheels
05232e05b83dbcd44ea477df4ad0666f0e08959c
[ "Apache-2.0" ]
353
2017-05-08T01:33:31.000Z
2022-03-12T05:57:16.000Z
/* * Copyright (C) 2001-2011 Michael Niedermayer <michaelni@gmx.at> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <inttypes.h> #include <math.h> #include <stdio.h> #include <string.h> #include "libavutil/avassert.h" #include "libavutil/avutil.h" #include "libavutil/bswap.h" #include "libavutil/cpu.h" #include "libavutil/imgutils.h" #include "libavutil/intreadwrite.h" #include "libavutil/mathematics.h" #include "libavutil/pixdesc.h" #include "config.h" #include "rgb2rgb.h" #include "swscale_internal.h" #include "swscale.h" DECLARE_ALIGNED(8, const uint8_t, ff_dither_8x8_128)[9][8] = { { 36, 68, 60, 92, 34, 66, 58, 90, }, { 100, 4, 124, 28, 98, 2, 122, 26, }, { 52, 84, 44, 76, 50, 82, 42, 74, }, { 116, 20, 108, 12, 114, 18, 106, 10, }, { 32, 64, 56, 88, 38, 70, 62, 94, }, { 96, 0, 120, 24, 102, 6, 126, 30, }, { 48, 80, 40, 72, 54, 86, 46, 78, }, { 112, 16, 104, 8, 118, 22, 110, 14, }, { 36, 68, 60, 92, 34, 66, 58, 90, }, }; DECLARE_ALIGNED(8, static const uint8_t, sws_pb_64)[8] = { 64, 64, 64, 64, 64, 64, 64, 64 }; static av_always_inline void fillPlane(uint8_t *plane, int stride, int width, int height, int y, uint8_t val) { int i; uint8_t *ptr = plane + stride * y; for (i = 0; i < height; i++) { memset(ptr, val, width); ptr += stride; } } static void hScale16To19_c(SwsContext *c, int16_t *_dst, int dstW, const uint8_t *_src, const int16_t *filter, const int32_t *filterPos, int filterSize) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(c->srcFormat); int i; int32_t *dst = (int32_t *) _dst; const uint16_t *src = (const uint16_t *) _src; int bits = desc->comp[0].depth - 1; int sh = bits - 4; if((isAnyRGB(c->srcFormat) || c->srcFormat==AV_PIX_FMT_PAL8) && desc->comp[0].depth<16) sh= 9; for (i = 0; i < dstW; i++) { int j; int srcPos = filterPos[i]; int val = 0; for (j = 0; j < filterSize; j++) { val += src[srcPos + j] * filter[filterSize * i + j]; } // filter=14 bit, input=16 bit, output=30 bit, >> 11 makes 19 bit dst[i] = FFMIN(val >> sh, (1 << 19) - 1); } } static void hScale16To15_c(SwsContext *c, int16_t *dst, int dstW, const uint8_t *_src, const int16_t *filter, const int32_t *filterPos, int filterSize) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(c->srcFormat); int i; const uint16_t *src = (const uint16_t *) _src; int sh = desc->comp[0].depth - 1; if(sh<15) sh= isAnyRGB(c->srcFormat) || c->srcFormat==AV_PIX_FMT_PAL8 ? 13 : (desc->comp[0].depth - 1); for (i = 0; i < dstW; i++) { int j; int srcPos = filterPos[i]; int val = 0; for (j = 0; j < filterSize; j++) { val += src[srcPos + j] * filter[filterSize * i + j]; } // filter=14 bit, input=16 bit, output=30 bit, >> 15 makes 15 bit dst[i] = FFMIN(val >> sh, (1 << 15) - 1); } } // bilinear / bicubic scaling static void hScale8To15_c(SwsContext *c, int16_t *dst, int dstW, const uint8_t *src, const int16_t *filter, const int32_t *filterPos, int filterSize) { int i; for (i = 0; i < dstW; i++) { int j; int srcPos = filterPos[i]; int val = 0; for (j = 0; j < filterSize; j++) { val += ((int)src[srcPos + j]) * filter[filterSize * i + j]; } dst[i] = FFMIN(val >> 7, (1 << 15) - 1); // the cubic equation does overflow ... } } static void hScale8To19_c(SwsContext *c, int16_t *_dst, int dstW, const uint8_t *src, const int16_t *filter, const int32_t *filterPos, int filterSize) { int i; int32_t *dst = (int32_t *) _dst; for (i = 0; i < dstW; i++) { int j; int srcPos = filterPos[i]; int val = 0; for (j = 0; j < filterSize; j++) { val += ((int)src[srcPos + j]) * filter[filterSize * i + j]; } dst[i] = FFMIN(val >> 3, (1 << 19) - 1); // the cubic equation does overflow ... } } // FIXME all pal and rgb srcFormats could do this conversion as well // FIXME all scalers more complex than bilinear could do half of this transform static void chrRangeToJpeg_c(int16_t *dstU, int16_t *dstV, int width) { int i; for (i = 0; i < width; i++) { dstU[i] = (FFMIN(dstU[i], 30775) * 4663 - 9289992) >> 12; // -264 dstV[i] = (FFMIN(dstV[i], 30775) * 4663 - 9289992) >> 12; // -264 } } static void chrRangeFromJpeg_c(int16_t *dstU, int16_t *dstV, int width) { int i; for (i = 0; i < width; i++) { dstU[i] = (dstU[i] * 1799 + 4081085) >> 11; // 1469 dstV[i] = (dstV[i] * 1799 + 4081085) >> 11; // 1469 } } static void lumRangeToJpeg_c(int16_t *dst, int width) { int i; for (i = 0; i < width; i++) dst[i] = (FFMIN(dst[i], 30189) * 19077 - 39057361) >> 14; } static void lumRangeFromJpeg_c(int16_t *dst, int width) { int i; for (i = 0; i < width; i++) dst[i] = (dst[i] * 14071 + 33561947) >> 14; } static void chrRangeToJpeg16_c(int16_t *_dstU, int16_t *_dstV, int width) { int i; int32_t *dstU = (int32_t *) _dstU; int32_t *dstV = (int32_t *) _dstV; for (i = 0; i < width; i++) { dstU[i] = (FFMIN(dstU[i], 30775 << 4) * 4663 - (9289992 << 4)) >> 12; // -264 dstV[i] = (FFMIN(dstV[i], 30775 << 4) * 4663 - (9289992 << 4)) >> 12; // -264 } } static void chrRangeFromJpeg16_c(int16_t *_dstU, int16_t *_dstV, int width) { int i; int32_t *dstU = (int32_t *) _dstU; int32_t *dstV = (int32_t *) _dstV; for (i = 0; i < width; i++) { dstU[i] = (dstU[i] * 1799 + (4081085 << 4)) >> 11; // 1469 dstV[i] = (dstV[i] * 1799 + (4081085 << 4)) >> 11; // 1469 } } static void lumRangeToJpeg16_c(int16_t *_dst, int width) { int i; int32_t *dst = (int32_t *) _dst; for (i = 0; i < width; i++) { dst[i] = ((int)(FFMIN(dst[i], 30189 << 4) * 4769U - (39057361 << 2))) >> 12; } } static void lumRangeFromJpeg16_c(int16_t *_dst, int width) { int i; int32_t *dst = (int32_t *) _dst; for (i = 0; i < width; i++) dst[i] = (dst[i]*(14071/4) + (33561947<<4)/4)>>12; } #define DEBUG_SWSCALE_BUFFERS 0 #define DEBUG_BUFFERS(...) \ if (DEBUG_SWSCALE_BUFFERS) \ av_log(c, AV_LOG_DEBUG, __VA_ARGS__) static int swscale(SwsContext *c, const uint8_t *src[], int srcStride[], int srcSliceY, int srcSliceH, uint8_t *dst[], int dstStride[]) { /* load a few things into local vars to make the code more readable? * and faster */ const int dstW = c->dstW; const int dstH = c->dstH; const enum AVPixelFormat dstFormat = c->dstFormat; const int flags = c->flags; int32_t *vLumFilterPos = c->vLumFilterPos; int32_t *vChrFilterPos = c->vChrFilterPos; const int vLumFilterSize = c->vLumFilterSize; const int vChrFilterSize = c->vChrFilterSize; yuv2planar1_fn yuv2plane1 = c->yuv2plane1; yuv2planarX_fn yuv2planeX = c->yuv2planeX; yuv2interleavedX_fn yuv2nv12cX = c->yuv2nv12cX; yuv2packed1_fn yuv2packed1 = c->yuv2packed1; yuv2packed2_fn yuv2packed2 = c->yuv2packed2; yuv2packedX_fn yuv2packedX = c->yuv2packedX; yuv2anyX_fn yuv2anyX = c->yuv2anyX; const int chrSrcSliceY = srcSliceY >> c->chrSrcVSubSample; const int chrSrcSliceH = AV_CEIL_RSHIFT(srcSliceH, c->chrSrcVSubSample); int should_dither = isNBPS(c->srcFormat) || is16BPS(c->srcFormat); int lastDstY; /* vars which will change and which we need to store back in the context */ int dstY = c->dstY; int lumBufIndex = c->lumBufIndex; int chrBufIndex = c->chrBufIndex; int lastInLumBuf = c->lastInLumBuf; int lastInChrBuf = c->lastInChrBuf; int lumStart = 0; int lumEnd = c->descIndex[0]; int chrStart = lumEnd; int chrEnd = c->descIndex[1]; int vStart = chrEnd; int vEnd = c->numDesc; SwsSlice *src_slice = &c->slice[lumStart]; SwsSlice *hout_slice = &c->slice[c->numSlice-2]; SwsSlice *vout_slice = &c->slice[c->numSlice-1]; SwsFilterDescriptor *desc = c->desc; int needAlpha = c->needAlpha; int hasLumHoles = 1; int hasChrHoles = 1; if (isPacked(c->srcFormat)) { src[0] = src[1] = src[2] = src[3] = src[0]; srcStride[0] = srcStride[1] = srcStride[2] = srcStride[3] = srcStride[0]; } srcStride[1] <<= c->vChrDrop; srcStride[2] <<= c->vChrDrop; DEBUG_BUFFERS("swscale() %p[%d] %p[%d] %p[%d] %p[%d] -> %p[%d] %p[%d] %p[%d] %p[%d]\n", src[0], srcStride[0], src[1], srcStride[1], src[2], srcStride[2], src[3], srcStride[3], dst[0], dstStride[0], dst[1], dstStride[1], dst[2], dstStride[2], dst[3], dstStride[3]); DEBUG_BUFFERS("srcSliceY: %d srcSliceH: %d dstY: %d dstH: %d\n", srcSliceY, srcSliceH, dstY, dstH); DEBUG_BUFFERS("vLumFilterSize: %d vChrFilterSize: %d\n", vLumFilterSize, vChrFilterSize); if (dstStride[0]&15 || dstStride[1]&15 || dstStride[2]&15 || dstStride[3]&15) { static int warnedAlready = 0; // FIXME maybe move this into the context if (flags & SWS_PRINT_INFO && !warnedAlready) { av_log(c, AV_LOG_WARNING, "Warning: dstStride is not aligned!\n" " ->cannot do aligned memory accesses anymore\n"); warnedAlready = 1; } } if ( (uintptr_t)dst[0]&15 || (uintptr_t)dst[1]&15 || (uintptr_t)dst[2]&15 || (uintptr_t)src[0]&15 || (uintptr_t)src[1]&15 || (uintptr_t)src[2]&15 || dstStride[0]&15 || dstStride[1]&15 || dstStride[2]&15 || dstStride[3]&15 || srcStride[0]&15 || srcStride[1]&15 || srcStride[2]&15 || srcStride[3]&15 ) { static int warnedAlready=0; int cpu_flags = av_get_cpu_flags(); if (HAVE_MMXEXT && (cpu_flags & AV_CPU_FLAG_SSE2) && !warnedAlready){ av_log(c, AV_LOG_WARNING, "Warning: data is not aligned! This can lead to a speed loss\n"); warnedAlready=1; } } /* Note the user might start scaling the picture in the middle so this * will not get executed. This is not really intended but works * currently, so people might do it. */ if (srcSliceY == 0) { lumBufIndex = -1; chrBufIndex = -1; dstY = 0; lastInLumBuf = -1; lastInChrBuf = -1; } if (!should_dither) { c->chrDither8 = c->lumDither8 = sws_pb_64; } lastDstY = dstY; ff_init_vscale_pfn(c, yuv2plane1, yuv2planeX, yuv2nv12cX, yuv2packed1, yuv2packed2, yuv2packedX, yuv2anyX, c->use_mmx_vfilter); ff_init_slice_from_src(src_slice, (uint8_t**)src, srcStride, c->srcW, srcSliceY, srcSliceH, chrSrcSliceY, chrSrcSliceH, 1); ff_init_slice_from_src(vout_slice, (uint8_t**)dst, dstStride, c->dstW, dstY, dstH, dstY >> c->chrDstVSubSample, AV_CEIL_RSHIFT(dstH, c->chrDstVSubSample), 0); if (srcSliceY == 0) { hout_slice->plane[0].sliceY = lastInLumBuf + 1; hout_slice->plane[1].sliceY = lastInChrBuf + 1; hout_slice->plane[2].sliceY = lastInChrBuf + 1; hout_slice->plane[3].sliceY = lastInLumBuf + 1; hout_slice->plane[0].sliceH = hout_slice->plane[1].sliceH = hout_slice->plane[2].sliceH = hout_slice->plane[3].sliceH = 0; hout_slice->width = dstW; } for (; dstY < dstH; dstY++) { const int chrDstY = dstY >> c->chrDstVSubSample; int use_mmx_vfilter= c->use_mmx_vfilter; // First line needed as input const int firstLumSrcY = FFMAX(1 - vLumFilterSize, vLumFilterPos[dstY]); const int firstLumSrcY2 = FFMAX(1 - vLumFilterSize, vLumFilterPos[FFMIN(dstY | ((1 << c->chrDstVSubSample) - 1), dstH - 1)]); // First line needed as input const int firstChrSrcY = FFMAX(1 - vChrFilterSize, vChrFilterPos[chrDstY]); // Last line needed as input int lastLumSrcY = FFMIN(c->srcH, firstLumSrcY + vLumFilterSize) - 1; int lastLumSrcY2 = FFMIN(c->srcH, firstLumSrcY2 + vLumFilterSize) - 1; int lastChrSrcY = FFMIN(c->chrSrcH, firstChrSrcY + vChrFilterSize) - 1; int enough_lines; int i; int posY, cPosY, firstPosY, lastPosY, firstCPosY, lastCPosY; // handle holes (FAST_BILINEAR & weird filters) if (firstLumSrcY > lastInLumBuf) { hasLumHoles = lastInLumBuf != firstLumSrcY - 1; if (hasLumHoles) { hout_slice->plane[0].sliceY = firstLumSrcY; hout_slice->plane[3].sliceY = firstLumSrcY; hout_slice->plane[0].sliceH = hout_slice->plane[3].sliceH = 0; } lastInLumBuf = firstLumSrcY - 1; } if (firstChrSrcY > lastInChrBuf) { hasChrHoles = lastInChrBuf != firstChrSrcY - 1; if (hasChrHoles) { hout_slice->plane[1].sliceY = firstChrSrcY; hout_slice->plane[2].sliceY = firstChrSrcY; hout_slice->plane[1].sliceH = hout_slice->plane[2].sliceH = 0; } lastInChrBuf = firstChrSrcY - 1; } DEBUG_BUFFERS("dstY: %d\n", dstY); DEBUG_BUFFERS("\tfirstLumSrcY: %d lastLumSrcY: %d lastInLumBuf: %d\n", firstLumSrcY, lastLumSrcY, lastInLumBuf); DEBUG_BUFFERS("\tfirstChrSrcY: %d lastChrSrcY: %d lastInChrBuf: %d\n", firstChrSrcY, lastChrSrcY, lastInChrBuf); // Do we have enough lines in this slice to output the dstY line enough_lines = lastLumSrcY2 < srcSliceY + srcSliceH && lastChrSrcY < AV_CEIL_RSHIFT(srcSliceY + srcSliceH, c->chrSrcVSubSample); if (!enough_lines) { lastLumSrcY = srcSliceY + srcSliceH - 1; lastChrSrcY = chrSrcSliceY + chrSrcSliceH - 1; DEBUG_BUFFERS("buffering slice: lastLumSrcY %d lastChrSrcY %d\n", lastLumSrcY, lastChrSrcY); } av_assert0((lastLumSrcY - firstLumSrcY + 1) <= hout_slice->plane[0].available_lines); av_assert0((lastChrSrcY - firstChrSrcY + 1) <= hout_slice->plane[1].available_lines); posY = hout_slice->plane[0].sliceY + hout_slice->plane[0].sliceH; if (posY <= lastLumSrcY && !hasLumHoles) { firstPosY = FFMAX(firstLumSrcY, posY); lastPosY = FFMIN(firstLumSrcY + hout_slice->plane[0].available_lines - 1, srcSliceY + srcSliceH - 1); } else { firstPosY = posY; lastPosY = lastLumSrcY; } cPosY = hout_slice->plane[1].sliceY + hout_slice->plane[1].sliceH; if (cPosY <= lastChrSrcY && !hasChrHoles) { firstCPosY = FFMAX(firstChrSrcY, cPosY); lastCPosY = FFMIN(firstChrSrcY + hout_slice->plane[1].available_lines - 1, AV_CEIL_RSHIFT(srcSliceY + srcSliceH, c->chrSrcVSubSample) - 1); } else { firstCPosY = cPosY; lastCPosY = lastChrSrcY; } ff_rotate_slice(hout_slice, lastPosY, lastCPosY); if (posY < lastLumSrcY + 1) { for (i = lumStart; i < lumEnd; ++i) desc[i].process(c, &desc[i], firstPosY, lastPosY - firstPosY + 1); } lumBufIndex += lastLumSrcY - lastInLumBuf; lastInLumBuf = lastLumSrcY; if (cPosY < lastChrSrcY + 1) { for (i = chrStart; i < chrEnd; ++i) desc[i].process(c, &desc[i], firstCPosY, lastCPosY - firstCPosY + 1); } chrBufIndex += lastChrSrcY - lastInChrBuf; lastInChrBuf = lastChrSrcY; // wrap buf index around to stay inside the ring buffer if (lumBufIndex >= vLumFilterSize) lumBufIndex -= vLumFilterSize; if (chrBufIndex >= vChrFilterSize) chrBufIndex -= vChrFilterSize; if (!enough_lines) break; // we can't output a dstY line so let's try with the next slice #if HAVE_MMX_INLINE ff_updateMMXDitherTables(c, dstY, lumBufIndex, chrBufIndex, lastInLumBuf, lastInChrBuf); #endif if (should_dither) { c->chrDither8 = ff_dither_8x8_128[chrDstY & 7]; c->lumDither8 = ff_dither_8x8_128[dstY & 7]; } if (dstY >= dstH - 2) { /* hmm looks like we can't use MMX here without overwriting * this array's tail */ ff_sws_init_output_funcs(c, &yuv2plane1, &yuv2planeX, &yuv2nv12cX, &yuv2packed1, &yuv2packed2, &yuv2packedX, &yuv2anyX); use_mmx_vfilter= 0; ff_init_vscale_pfn(c, yuv2plane1, yuv2planeX, yuv2nv12cX, yuv2packed1, yuv2packed2, yuv2packedX, yuv2anyX, use_mmx_vfilter); } { for (i = vStart; i < vEnd; ++i) desc[i].process(c, &desc[i], dstY, 1); } } if (isPlanar(dstFormat) && isALPHA(dstFormat) && !needAlpha) { int length = dstW; int height = dstY - lastDstY; if (is16BPS(dstFormat) || isNBPS(dstFormat)) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(dstFormat); fillPlane16(dst[3], dstStride[3], length, height, lastDstY, 1, desc->comp[3].depth, isBE(dstFormat)); } else fillPlane(dst[3], dstStride[3], length, height, lastDstY, 255); } #if HAVE_MMXEXT_INLINE if (av_get_cpu_flags() & AV_CPU_FLAG_MMXEXT) __asm__ volatile ("sfence" ::: "memory"); #endif emms_c(); /* store changed local vars back in the context */ c->dstY = dstY; c->lumBufIndex = lumBufIndex; c->chrBufIndex = chrBufIndex; c->lastInLumBuf = lastInLumBuf; c->lastInChrBuf = lastInChrBuf; return dstY - lastDstY; } av_cold void ff_sws_init_range_convert(SwsContext *c) { c->lumConvertRange = NULL; c->chrConvertRange = NULL; if (c->srcRange != c->dstRange && !isAnyRGB(c->dstFormat)) { if (c->dstBpc <= 14) { if (c->srcRange) { c->lumConvertRange = lumRangeFromJpeg_c; c->chrConvertRange = chrRangeFromJpeg_c; } else { c->lumConvertRange = lumRangeToJpeg_c; c->chrConvertRange = chrRangeToJpeg_c; } } else { if (c->srcRange) { c->lumConvertRange = lumRangeFromJpeg16_c; c->chrConvertRange = chrRangeFromJpeg16_c; } else { c->lumConvertRange = lumRangeToJpeg16_c; c->chrConvertRange = chrRangeToJpeg16_c; } } } } static av_cold void sws_init_swscale(SwsContext *c) { enum AVPixelFormat srcFormat = c->srcFormat; ff_sws_init_output_funcs(c, &c->yuv2plane1, &c->yuv2planeX, &c->yuv2nv12cX, &c->yuv2packed1, &c->yuv2packed2, &c->yuv2packedX, &c->yuv2anyX); ff_sws_init_input_funcs(c); if (c->srcBpc == 8) { if (c->dstBpc <= 14) { c->hyScale = c->hcScale = hScale8To15_c; if (c->flags & SWS_FAST_BILINEAR) { c->hyscale_fast = ff_hyscale_fast_c; c->hcscale_fast = ff_hcscale_fast_c; } } else { c->hyScale = c->hcScale = hScale8To19_c; } } else { c->hyScale = c->hcScale = c->dstBpc > 14 ? hScale16To19_c : hScale16To15_c; } ff_sws_init_range_convert(c); if (!(isGray(srcFormat) || isGray(c->dstFormat) || srcFormat == AV_PIX_FMT_MONOBLACK || srcFormat == AV_PIX_FMT_MONOWHITE)) c->needs_hcscale = 1; } SwsFunc ff_getSwsFunc(SwsContext *c) { sws_init_swscale(c); if (ARCH_PPC) ff_sws_init_swscale_ppc(c); if (ARCH_X86) ff_sws_init_swscale_x86(c); if (ARCH_AARCH64) ff_sws_init_swscale_aarch64(c); if (ARCH_ARM) ff_sws_init_swscale_arm(c); return swscale; } static void reset_ptr(const uint8_t *src[], enum AVPixelFormat format) { if (!isALPHA(format)) src[3] = NULL; if (!isPlanar(format)) { src[3] = src[2] = NULL; if (!usePal(format)) src[1] = NULL; } } static int check_image_pointers(const uint8_t * const data[4], enum AVPixelFormat pix_fmt, const int linesizes[4]) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt); int i; av_assert2(desc); for (i = 0; i < 4; i++) { int plane = desc->comp[i].plane; if (!data[plane] || !linesizes[plane]) return 0; } return 1; } static void xyz12Torgb48(struct SwsContext *c, uint16_t *dst, const uint16_t *src, int stride, int h) { int xp,yp; const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(c->srcFormat); for (yp=0; yp<h; yp++) { for (xp=0; xp+2<stride; xp+=3) { int x, y, z, r, g, b; if (desc->flags & AV_PIX_FMT_FLAG_BE) { x = AV_RB16(src + xp + 0); y = AV_RB16(src + xp + 1); z = AV_RB16(src + xp + 2); } else { x = AV_RL16(src + xp + 0); y = AV_RL16(src + xp + 1); z = AV_RL16(src + xp + 2); } x = c->xyzgamma[x>>4]; y = c->xyzgamma[y>>4]; z = c->xyzgamma[z>>4]; // convert from XYZlinear to sRGBlinear r = c->xyz2rgb_matrix[0][0] * x + c->xyz2rgb_matrix[0][1] * y + c->xyz2rgb_matrix[0][2] * z >> 12; g = c->xyz2rgb_matrix[1][0] * x + c->xyz2rgb_matrix[1][1] * y + c->xyz2rgb_matrix[1][2] * z >> 12; b = c->xyz2rgb_matrix[2][0] * x + c->xyz2rgb_matrix[2][1] * y + c->xyz2rgb_matrix[2][2] * z >> 12; // limit values to 12-bit depth r = av_clip_uintp2(r, 12); g = av_clip_uintp2(g, 12); b = av_clip_uintp2(b, 12); // convert from sRGBlinear to RGB and scale from 12bit to 16bit if (desc->flags & AV_PIX_FMT_FLAG_BE) { AV_WB16(dst + xp + 0, c->rgbgamma[r] << 4); AV_WB16(dst + xp + 1, c->rgbgamma[g] << 4); AV_WB16(dst + xp + 2, c->rgbgamma[b] << 4); } else { AV_WL16(dst + xp + 0, c->rgbgamma[r] << 4); AV_WL16(dst + xp + 1, c->rgbgamma[g] << 4); AV_WL16(dst + xp + 2, c->rgbgamma[b] << 4); } } src += stride; dst += stride; } } static void rgb48Toxyz12(struct SwsContext *c, uint16_t *dst, const uint16_t *src, int stride, int h) { int xp,yp; const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(c->dstFormat); for (yp=0; yp<h; yp++) { for (xp=0; xp+2<stride; xp+=3) { int x, y, z, r, g, b; if (desc->flags & AV_PIX_FMT_FLAG_BE) { r = AV_RB16(src + xp + 0); g = AV_RB16(src + xp + 1); b = AV_RB16(src + xp + 2); } else { r = AV_RL16(src + xp + 0); g = AV_RL16(src + xp + 1); b = AV_RL16(src + xp + 2); } r = c->rgbgammainv[r>>4]; g = c->rgbgammainv[g>>4]; b = c->rgbgammainv[b>>4]; // convert from sRGBlinear to XYZlinear x = c->rgb2xyz_matrix[0][0] * r + c->rgb2xyz_matrix[0][1] * g + c->rgb2xyz_matrix[0][2] * b >> 12; y = c->rgb2xyz_matrix[1][0] * r + c->rgb2xyz_matrix[1][1] * g + c->rgb2xyz_matrix[1][2] * b >> 12; z = c->rgb2xyz_matrix[2][0] * r + c->rgb2xyz_matrix[2][1] * g + c->rgb2xyz_matrix[2][2] * b >> 12; // limit values to 12-bit depth x = av_clip_uintp2(x, 12); y = av_clip_uintp2(y, 12); z = av_clip_uintp2(z, 12); // convert from XYZlinear to X'Y'Z' and scale from 12bit to 16bit if (desc->flags & AV_PIX_FMT_FLAG_BE) { AV_WB16(dst + xp + 0, c->xyzgammainv[x] << 4); AV_WB16(dst + xp + 1, c->xyzgammainv[y] << 4); AV_WB16(dst + xp + 2, c->xyzgammainv[z] << 4); } else { AV_WL16(dst + xp + 0, c->xyzgammainv[x] << 4); AV_WL16(dst + xp + 1, c->xyzgammainv[y] << 4); AV_WL16(dst + xp + 2, c->xyzgammainv[z] << 4); } } src += stride; dst += stride; } } /** * swscale wrapper, so we don't need to export the SwsContext. * Assumes planar YUV to be in YUV order instead of YVU. */ int attribute_align_arg sws_scale(struct SwsContext *c, const uint8_t * const srcSlice[], const int srcStride[], int srcSliceY, int srcSliceH, uint8_t *const dst[], const int dstStride[]) { int i, ret; const uint8_t *src2[4]; uint8_t *dst2[4]; uint8_t *rgb0_tmp = NULL; int macro_height = isBayer(c->srcFormat) ? 2 : (1 << c->chrSrcVSubSample); // copy strides, so they can safely be modified int srcStride2[4]; int dstStride2[4]; int srcSliceY_internal = srcSliceY; if (!srcStride || !dstStride || !dst || !srcSlice) { av_log(c, AV_LOG_ERROR, "One of the input parameters to sws_scale() is NULL, please check the calling code\n"); return 0; } for (i=0; i<4; i++) { srcStride2[i] = srcStride[i]; dstStride2[i] = dstStride[i]; } if ((srcSliceY & (macro_height-1)) || ((srcSliceH& (macro_height-1)) && srcSliceY + srcSliceH != c->srcH) || srcSliceY + srcSliceH > c->srcH) { av_log(c, AV_LOG_ERROR, "Slice parameters %d, %d are invalid\n", srcSliceY, srcSliceH); return AVERROR(EINVAL); } if (c->gamma_flag && c->cascaded_context[0]) { ret = sws_scale(c->cascaded_context[0], srcSlice, srcStride, srcSliceY, srcSliceH, c->cascaded_tmp, c->cascaded_tmpStride); if (ret < 0) return ret; if (c->cascaded_context[2]) ret = sws_scale(c->cascaded_context[1], (const uint8_t * const *)c->cascaded_tmp, c->cascaded_tmpStride, srcSliceY, srcSliceH, c->cascaded1_tmp, c->cascaded1_tmpStride); else ret = sws_scale(c->cascaded_context[1], (const uint8_t * const *)c->cascaded_tmp, c->cascaded_tmpStride, srcSliceY, srcSliceH, dst, dstStride); if (ret < 0) return ret; if (c->cascaded_context[2]) { ret = sws_scale(c->cascaded_context[2], (const uint8_t * const *)c->cascaded1_tmp, c->cascaded1_tmpStride, c->cascaded_context[1]->dstY - ret, c->cascaded_context[1]->dstY, dst, dstStride); } return ret; } if (c->cascaded_context[0] && srcSliceY == 0 && srcSliceH == c->cascaded_context[0]->srcH) { ret = sws_scale(c->cascaded_context[0], srcSlice, srcStride, srcSliceY, srcSliceH, c->cascaded_tmp, c->cascaded_tmpStride); if (ret < 0) return ret; ret = sws_scale(c->cascaded_context[1], (const uint8_t * const * )c->cascaded_tmp, c->cascaded_tmpStride, 0, c->cascaded_context[0]->dstH, dst, dstStride); return ret; } memcpy(src2, srcSlice, sizeof(src2)); memcpy(dst2, dst, sizeof(dst2)); // do not mess up sliceDir if we have a "trailing" 0-size slice if (srcSliceH == 0) return 0; if (!check_image_pointers(srcSlice, c->srcFormat, srcStride)) { av_log(c, AV_LOG_ERROR, "bad src image pointers\n"); return 0; } if (!check_image_pointers((const uint8_t* const*)dst, c->dstFormat, dstStride)) { av_log(c, AV_LOG_ERROR, "bad dst image pointers\n"); return 0; } if (c->sliceDir == 0 && srcSliceY != 0 && srcSliceY + srcSliceH != c->srcH) { av_log(c, AV_LOG_ERROR, "Slices start in the middle!\n"); return 0; } if (c->sliceDir == 0) { if (srcSliceY == 0) c->sliceDir = 1; else c->sliceDir = -1; } if (usePal(c->srcFormat)) { for (i = 0; i < 256; i++) { int r, g, b, y, u, v, a = 0xff; if (c->srcFormat == AV_PIX_FMT_PAL8) { uint32_t p = ((const uint32_t *)(srcSlice[1]))[i]; a = (p >> 24) & 0xFF; r = (p >> 16) & 0xFF; g = (p >> 8) & 0xFF; b = p & 0xFF; } else if (c->srcFormat == AV_PIX_FMT_RGB8) { r = ( i >> 5 ) * 36; g = ((i >> 2) & 7) * 36; b = ( i & 3) * 85; } else if (c->srcFormat == AV_PIX_FMT_BGR8) { b = ( i >> 6 ) * 85; g = ((i >> 3) & 7) * 36; r = ( i & 7) * 36; } else if (c->srcFormat == AV_PIX_FMT_RGB4_BYTE) { r = ( i >> 3 ) * 255; g = ((i >> 1) & 3) * 85; b = ( i & 1) * 255; } else if (c->srcFormat == AV_PIX_FMT_GRAY8 || c->srcFormat == AV_PIX_FMT_GRAY8A) { r = g = b = i; } else { av_assert1(c->srcFormat == AV_PIX_FMT_BGR4_BYTE); b = ( i >> 3 ) * 255; g = ((i >> 1) & 3) * 85; r = ( i & 1) * 255; } #define RGB2YUV_SHIFT 15 #define BY ( (int) (0.114 * 219 / 255 * (1 << RGB2YUV_SHIFT) + 0.5)) #define BV (-(int) (0.081 * 224 / 255 * (1 << RGB2YUV_SHIFT) + 0.5)) #define BU ( (int) (0.500 * 224 / 255 * (1 << RGB2YUV_SHIFT) + 0.5)) #define GY ( (int) (0.587 * 219 / 255 * (1 << RGB2YUV_SHIFT) + 0.5)) #define GV (-(int) (0.419 * 224 / 255 * (1 << RGB2YUV_SHIFT) + 0.5)) #define GU (-(int) (0.331 * 224 / 255 * (1 << RGB2YUV_SHIFT) + 0.5)) #define RY ( (int) (0.299 * 219 / 255 * (1 << RGB2YUV_SHIFT) + 0.5)) #define RV ( (int) (0.500 * 224 / 255 * (1 << RGB2YUV_SHIFT) + 0.5)) #define RU (-(int) (0.169 * 224 / 255 * (1 << RGB2YUV_SHIFT) + 0.5)) y = av_clip_uint8((RY * r + GY * g + BY * b + ( 33 << (RGB2YUV_SHIFT - 1))) >> RGB2YUV_SHIFT); u = av_clip_uint8((RU * r + GU * g + BU * b + (257 << (RGB2YUV_SHIFT - 1))) >> RGB2YUV_SHIFT); v = av_clip_uint8((RV * r + GV * g + BV * b + (257 << (RGB2YUV_SHIFT - 1))) >> RGB2YUV_SHIFT); c->pal_yuv[i]= y + (u<<8) + (v<<16) + ((unsigned)a<<24); switch (c->dstFormat) { case AV_PIX_FMT_BGR32: #if !HAVE_BIGENDIAN case AV_PIX_FMT_RGB24: #endif c->pal_rgb[i]= r + (g<<8) + (b<<16) + ((unsigned)a<<24); break; case AV_PIX_FMT_BGR32_1: #if HAVE_BIGENDIAN case AV_PIX_FMT_BGR24: #endif c->pal_rgb[i]= a + (r<<8) + (g<<16) + ((unsigned)b<<24); break; case AV_PIX_FMT_RGB32_1: #if HAVE_BIGENDIAN case AV_PIX_FMT_RGB24: #endif c->pal_rgb[i]= a + (b<<8) + (g<<16) + ((unsigned)r<<24); break; case AV_PIX_FMT_RGB32: #if !HAVE_BIGENDIAN case AV_PIX_FMT_BGR24: #endif default: c->pal_rgb[i]= b + (g<<8) + (r<<16) + ((unsigned)a<<24); } } } if (c->src0Alpha && !c->dst0Alpha && isALPHA(c->dstFormat)) { uint8_t *base; int x,y; rgb0_tmp = av_malloc(FFABS(srcStride[0]) * srcSliceH + 32); if (!rgb0_tmp) return AVERROR(ENOMEM); base = srcStride[0] < 0 ? rgb0_tmp - srcStride[0] * (srcSliceH-1) : rgb0_tmp; for (y=0; y<srcSliceH; y++){ memcpy(base + srcStride[0]*y, src2[0] + srcStride[0]*y, 4*c->srcW); for (x=c->src0Alpha-1; x<4*c->srcW; x+=4) { base[ srcStride[0]*y + x] = 0xFF; } } src2[0] = base; } if (c->srcXYZ && !(c->dstXYZ && c->srcW==c->dstW && c->srcH==c->dstH)) { uint8_t *base; rgb0_tmp = av_malloc(FFABS(srcStride[0]) * srcSliceH + 32); if (!rgb0_tmp) return AVERROR(ENOMEM); base = srcStride[0] < 0 ? rgb0_tmp - srcStride[0] * (srcSliceH-1) : rgb0_tmp; xyz12Torgb48(c, (uint16_t*)base, (const uint16_t*)src2[0], srcStride[0]/2, srcSliceH); src2[0] = base; } if (!srcSliceY && (c->flags & SWS_BITEXACT) && c->dither == SWS_DITHER_ED && c->dither_error[0]) for (i = 0; i < 4; i++) memset(c->dither_error[i], 0, sizeof(c->dither_error[0][0]) * (c->dstW+2)); if (c->sliceDir != 1) { // slices go from bottom to top => we flip the image internally for (i=0; i<4; i++) { srcStride2[i] *= -1; dstStride2[i] *= -1; } src2[0] += (srcSliceH - 1) * srcStride[0]; if (!usePal(c->srcFormat)) src2[1] += ((srcSliceH >> c->chrSrcVSubSample) - 1) * srcStride[1]; src2[2] += ((srcSliceH >> c->chrSrcVSubSample) - 1) * srcStride[2]; src2[3] += (srcSliceH - 1) * srcStride[3]; dst2[0] += ( c->dstH - 1) * dstStride[0]; dst2[1] += ((c->dstH >> c->chrDstVSubSample) - 1) * dstStride[1]; dst2[2] += ((c->dstH >> c->chrDstVSubSample) - 1) * dstStride[2]; dst2[3] += ( c->dstH - 1) * dstStride[3]; srcSliceY_internal = c->srcH-srcSliceY-srcSliceH; } reset_ptr(src2, c->srcFormat); reset_ptr((void*)dst2, c->dstFormat); /* reset slice direction at end of frame */ if (srcSliceY_internal + srcSliceH == c->srcH) c->sliceDir = 0; ret = c->swscale(c, src2, srcStride2, srcSliceY_internal, srcSliceH, dst2, dstStride2); if (c->dstXYZ && !(c->srcXYZ && c->srcW==c->dstW && c->srcH==c->dstH)) { int dstY = c->dstY ? c->dstY : srcSliceY + srcSliceH; uint16_t *dst16 = (uint16_t*)(dst2[0] + (dstY - ret) * dstStride2[0]); av_assert0(dstY >= ret); av_assert0(ret >= 0); av_assert0(c->dstH >= dstY); /* replace on the same data */ rgb48Toxyz12(c, dst16, dst16, dstStride2[0]/2, ret); } av_free(rgb0_tmp); return ret; }
36.224674
181
0.533614
[ "transform" ]
7f3f3829ade2460c32f2f2846345fdbadfcaaa31
998
h
C
gen/blink/bindings/modules/v8/V8SharedWorkerGlobalScopePartial.h
gergul/MiniBlink
7a11c52f141d54d5f8e1a9af31867cd120a2c3c4
[ "Apache-2.0" ]
8
2019-05-05T16:38:05.000Z
2021-11-09T11:45:38.000Z
gen/blink/bindings/modules/v8/V8SharedWorkerGlobalScopePartial.h
gergul/MiniBlink
7a11c52f141d54d5f8e1a9af31867cd120a2c3c4
[ "Apache-2.0" ]
null
null
null
gen/blink/bindings/modules/v8/V8SharedWorkerGlobalScopePartial.h
gergul/MiniBlink
7a11c52f141d54d5f8e1a9af31867cd120a2c3c4
[ "Apache-2.0" ]
4
2018-12-14T07:52:46.000Z
2021-06-11T18:06:09.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY! #ifndef V8SharedWorkerGlobalScopePartial_h #define V8SharedWorkerGlobalScopePartial_h #include "bindings/core/v8/ScriptWrappable.h" #include "bindings/core/v8/ToV8.h" #include "bindings/core/v8/V8Binding.h" #include "bindings/core/v8/V8DOMWrapper.h" #include "bindings/core/v8/WrapperTypeInfo.h" #include "core/workers/SharedWorkerGlobalScope.h" #include "platform/heap/Handle.h" namespace blink { class V8SharedWorkerGlobalScopePartial { public: static void initialize(); static void preparePrototypeObject(v8::Isolate*, v8::Local<v8::Object>, v8::Local<v8::FunctionTemplate>); private: static void installV8SharedWorkerGlobalScopeTemplate(v8::Local<v8::FunctionTemplate>, v8::Isolate*); }; } #endif // V8SharedWorkerGlobalScopePartial_h
34.413793
109
0.787575
[ "object" ]
7f3f6b78cd9f19f6733266478fc2e84a6df1a47f
8,112
h
C
src/Network/sockutil.h
xiongguangjie/ZLToolKit
1126175e2aabd811ba906e9699b43caf5837179d
[ "MIT" ]
608
2016-08-13T10:04:06.000Z
2020-07-23T15:24:16.000Z
src/Network/sockutil.h
xiongguangjie/ZLToolKit
1126175e2aabd811ba906e9699b43caf5837179d
[ "MIT" ]
30
2017-10-11T03:29:13.000Z
2020-07-22T09:45:43.000Z
src/Network/sockutil.h
xiongguangjie/ZLToolKit
1126175e2aabd811ba906e9699b43caf5837179d
[ "MIT" ]
222
2017-04-18T08:28:24.000Z
2020-07-23T19:25:10.000Z
/* * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved. * * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit). * * Use of this source code is governed by MIT license that can be found in the * LICENSE file in the root of the source tree. All contributing project authors * may be found in the AUTHORS file in the root of the source tree. */ #ifndef NETWORK_SOCKUTIL_H #define NETWORK_SOCKUTIL_H #if defined(_WIN32) #include <winsock2.h> #include <ws2tcpip.h> #include <iphlpapi.h> #pragma comment (lib, "Ws2_32.lib") #pragma comment(lib,"Iphlpapi.lib") #else #include <netdb.h> #include <arpa/inet.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <net/if.h> #include <netinet/in.h> #include <netinet/tcp.h> #endif // defined(_WIN32) #include <cstring> #include <cstdint> #include <map> #include <vector> #include <string> namespace toolkit { #if defined(_WIN32) #ifndef socklen_t #define socklen_t int #endif //!socklen_t #ifndef SHUT_RDWR #define SHUT_RDWR 2 #endif //!SHUT_RDWR int ioctl(int fd, long cmd, u_long *ptr); int close(int fd); #endif // defined(_WIN32) #define SOCKET_DEFAULT_BUF_SIZE (256 * 1024) //套接字工具类,封装了socket、网络的一些基本操作 class SockUtil { public: /** * 创建tcp客户端套接字并连接服务器 * @param host 服务器ip或域名 * @param port 服务器端口号 * @param async 是否异步连接 * @param local_ip 绑定的本地网卡ip * @param local_port 绑定的本地端口号 * @return -1代表失败,其他为socket fd号 */ static int connect(const char *host, uint16_t port, bool async = true, const char *local_ip = "::", uint16_t local_port = 0); /** * 创建tcp监听套接字 * @param port 监听的本地端口 * @param local_ip 绑定的本地网卡ip * @param back_log accept列队长度 * @return -1代表失败,其他为socket fd号 */ static int listen(const uint16_t port, const char *local_ip = "::", int back_log = 1024); /** * 创建udp套接字 * @param port 监听的本地端口 * @param local_ip 绑定的本地网卡ip * @param enable_reuse 是否允许重复bind端口 * @return -1代表失败,其他为socket fd号 */ static int bindUdpSock(const uint16_t port, const char *local_ip = "::", bool enable_reuse = true); /** * @brief 解除与 sock 相关的绑定关系 * @param sock, socket fd 号 * @return 0 成功, -1 失败 */ static int dissolveUdpSock(int sock); /** * 开启TCP_NODELAY,降低TCP交互延时 * @param fd socket fd号 * @param on 是否开启 * @return 0代表成功,-1为失败 */ static int setNoDelay(int fd, bool on = true); /** * 写socket不触发SIG_PIPE信号(貌似只有mac有效) * @param fd socket fd号 * @return 0代表成功,-1为失败 */ static int setNoSigpipe(int fd); /** * 设置读写socket是否阻塞 * @param fd socket fd号 * @param noblock 是否阻塞 * @return 0代表成功,-1为失败 */ static int setNoBlocked(int fd, bool noblock = true); /** * 设置socket接收缓存,默认貌似8K左右,一般有设置上限 * 可以通过配置内核配置文件调整 * @param fd socket fd号 * @param size 接收缓存大小 * @return 0代表成功,-1为失败 */ static int setRecvBuf(int fd, int size = SOCKET_DEFAULT_BUF_SIZE); /** * 设置socket接收缓存,默认貌似8K左右,一般有设置上限 * 可以通过配置内核配置文件调整 * @param fd socket fd号 * @param size 接收缓存大小 * @return 0代表成功,-1为失败 */ static int setSendBuf(int fd, int size = SOCKET_DEFAULT_BUF_SIZE); /** * 设置后续可绑定复用端口(处于TIME_WAITE状态) * @param fd socket fd号 * @param on 是否开启该特性 * @return 0代表成功,-1为失败 */ static int setReuseable(int fd, bool on = true, bool reuse_port = true); /** * 运行发送或接收udp广播信息 * @param fd socket fd号 * @param on 是否开启该特性 * @return 0代表成功,-1为失败 */ static int setBroadcast(int fd, bool on = true); /** * 是否开启TCP KeepAlive特性 * @param fd socket fd号 * @param on 是否开启该特性 * @return 0代表成功,-1为失败 */ static int setKeepAlive(int fd, bool on = true); /** * 是否开启FD_CLOEXEC特性(多进程相关) * @param fd fd号,不一定是socket * @param on 是否开启该特性 * @return 0代表成功,-1为失败 */ static int setCloExec(int fd, bool on = true); /** * 开启SO_LINGER特性 * @param sock socket fd号 * @param second 内核等待关闭socket超时时间,单位秒 * @return 0代表成功,-1为失败 */ static int setCloseWait(int sock, int second = 0); /** * dns解析 * @param host 域名或ip * @param port 端口号 * @param addr sockaddr结构体 * @return 是否成功 */ static bool getDomainIP(const char *host, uint16_t port, struct sockaddr_storage &addr, int ai_family = AF_INET, int ai_socktype = SOCK_STREAM, int ai_protocol = IPPROTO_TCP, int expire_sec = 60); /** * 设置组播ttl * @param sock socket fd号 * @param ttl ttl值 * @return 0代表成功,-1为失败 */ static int setMultiTTL(int sock, uint8_t ttl = 64); /** * 设置组播发送网卡 * @param sock socket fd号 * @param local_ip 本机网卡ip * @return 0代表成功,-1为失败 */ static int setMultiIF(int sock, const char *local_ip); /** * 设置是否接收本机发出的组播包 * @param fd socket fd号 * @param acc 是否接收 * @return 0代表成功,-1为失败 */ static int setMultiLOOP(int fd, bool acc = false); /** * 加入组播 * @param fd socket fd号 * @param addr 组播地址 * @param local_ip 本机网卡ip * @return 0代表成功,-1为失败 */ static int joinMultiAddr(int fd, const char *addr, const char *local_ip = "0.0.0.0"); /** * 退出组播 * @param fd socket fd号 * @param addr 组播地址 * @param local_ip 本机网卡ip * @return 0代表成功,-1为失败 */ static int leaveMultiAddr(int fd, const char *addr, const char *local_ip = "0.0.0.0"); /** * 加入组播并只接受该源端的组播数据 * @param sock socket fd号 * @param addr 组播地址 * @param src_ip 数据源端地址 * @param local_ip 本机网卡ip * @return 0代表成功,-1为失败 */ static int joinMultiAddrFilter(int sock, const char *addr, const char *src_ip, const char *local_ip = "0.0.0.0"); /** * 退出组播 * @param fd socket fd号 * @param addr 组播地址 * @param src_ip 数据源端地址 * @param local_ip 本机网卡ip * @return 0代表成功,-1为失败 */ static int leaveMultiAddrFilter(int fd, const char *addr, const char *src_ip, const char *local_ip = "0.0.0.0"); /** * 获取该socket当前发生的错误 * @param fd socket fd号 * @return 错误代码 */ static int getSockError(int fd); /** * 获取网卡列表 * @return vector<map<ip:name> > */ static std::vector<std::map<std::string, std::string>> getInterfaceList(); /** * 获取本机默认网卡ip */ static std::string get_local_ip(); /** * 获取该socket绑定的本地ip * @param sock socket fd号 */ static std::string get_local_ip(int sock); /** * 获取该socket绑定的本地端口 * @param sock socket fd号 */ static uint16_t get_local_port(int sock); /** * 获取该socket绑定的远端ip * @param sock socket fd号 */ static std::string get_peer_ip(int sock); /** * 获取该socket绑定的远端端口 * @param sock socket fd号 */ static uint16_t get_peer_port(int sock); /** * 线程安全的in_addr转ip字符串 */ static std::string inet_ntoa(const struct in_addr &addr); static std::string inet_ntoa(const struct in6_addr &addr); static std::string inet_ntoa(const struct sockaddr *addr); static uint16_t inet_port(const struct sockaddr *addr); static struct sockaddr_storage make_sockaddr(const char *ip, uint16_t port); /** * 获取网卡ip * @param if_name 网卡名 */ static std::string get_ifr_ip(const char *if_name); /** * 获取网卡名 * @param local_op 网卡ip */ static std::string get_ifr_name(const char *local_op); /** * 根据网卡名获取子网掩码 * @param if_name 网卡名 */ static std::string get_ifr_mask(const char *if_name); /** * 根据网卡名获取广播地址 * @param if_name 网卡名 */ static std::string get_ifr_brdaddr(const char *if_name); /** * 判断两个ip是否为同一网段 * @param src_ip 我的ip * @param dts_ip 对方ip */ static bool in_same_lan(const char *src_ip, const char *dts_ip); /** * 判断是否为ipv4地址 */ static bool is_ipv4(const char *str); /** * 判断是否为ipv6地址 */ static bool is_ipv6(const char *str); }; } // namespace toolkit #endif // !NETWORK_SOCKUTIL_H
24
129
0.612426
[ "vector" ]
7f40b4cf74c88cb2682f129f0b1abebc279c4325
5,187
h
C
src/AppInstallerCommonCore/Public/winget/ManifestYamlPopulator.h
shashinma/winget-cli
2a9d1c66a32af0f44f6dd9b6ad76e88d427efc11
[ "MIT" ]
9
2021-09-16T00:00:31.000Z
2021-09-18T14:26:47.000Z
src/AppInstallerCommonCore/Public/winget/ManifestYamlPopulator.h
shashinma/winget-cli
2a9d1c66a32af0f44f6dd9b6ad76e88d427efc11
[ "MIT" ]
null
null
null
src/AppInstallerCommonCore/Public/winget/ManifestYamlPopulator.h
shashinma/winget-cli
2a9d1c66a32af0f44f6dd9b6ad76e88d427efc11
[ "MIT" ]
1
2021-09-17T11:33:54.000Z
2021-09-17T11:33:54.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include <winget/Manifest.h> #include <winget/ManifestValidation.h> #include <winget/Yaml.h> namespace AppInstaller::Manifest { struct ManifestYamlPopulator { static std::vector<ValidationError> PopulateManifest(const YAML::Node& rootNode, Manifest& manifest, const ManifestVer& manifestVersion, bool fullValidation); private: bool m_fullValidation = false; bool m_isMergedManifest = false; // Struct mapping a manifest field to its population logic struct FieldProcessInfo { FieldProcessInfo(std::string name, std::function<std::vector<ValidationError>(const YAML::Node&)> func) : Name(std::move(name)), ProcessFunc(func) {} std::string Name; std::function<std::vector<ValidationError>(const YAML::Node&)> ProcessFunc; }; std::vector<FieldProcessInfo> RootFieldInfos; std::vector<FieldProcessInfo> InstallerFieldInfos; std::vector<FieldProcessInfo> SwitchesFieldInfos; std::vector<FieldProcessInfo> ExpectedReturnCodesFieldInfos; std::vector<FieldProcessInfo> DependenciesFieldInfos; std::vector<FieldProcessInfo> PackageDependenciesFieldInfos; std::vector<FieldProcessInfo> LocalizationFieldInfos; std::vector<FieldProcessInfo> AgreementFieldInfos; std::vector<FieldProcessInfo> MarketsFieldInfos; std::vector<FieldProcessInfo> AppsAndFeaturesEntryFieldInfos; // These pointers are referenced in the processing functions in manifest field process info table. AppInstaller::Manifest::Manifest* m_p_manifest = nullptr; AppInstaller::Manifest::ManifestInstaller* m_p_installer = nullptr; std::map<InstallerSwitchType, Utility::NormalizedString>* m_p_switches = nullptr; AppInstaller::Manifest::ExpectedReturnCode* m_p_expectedReturnCode = nullptr; AppInstaller::Manifest::DependencyList* m_p_dependencyList = nullptr; AppInstaller::Manifest::Dependency* m_p_packageDependency = nullptr; AppInstaller::Manifest::ManifestLocalization* m_p_localization = nullptr; AppInstaller::Manifest::Agreement* m_p_agreement = nullptr; AppInstaller::Manifest::MarketsInfo* m_p_markets = nullptr; AppInstaller::Manifest::AppsAndFeaturesEntry* m_p_appsAndFeaturesEntry = nullptr; // Cache of Installers node and Localization node YAML::Node const* m_p_installersNode = nullptr; YAML::Node const* m_p_localizationsNode = nullptr; std::vector<FieldProcessInfo> GetRootFieldProcessInfo(const ManifestVer& manifestVersion); std::vector<FieldProcessInfo> GetInstallerFieldProcessInfo(const ManifestVer& manifestVersion, bool forRootFields = false); std::vector<FieldProcessInfo> GetSwitchesFieldProcessInfo(const ManifestVer& manifestVersion); std::vector<FieldProcessInfo> GetExpectedReturnCodesFieldProcessInfo(const ManifestVer& manifestVersion); std::vector<FieldProcessInfo> GetDependenciesFieldProcessInfo(const ManifestVer& manifestVersion); std::vector<FieldProcessInfo> GetPackageDependenciesFieldProcessInfo(const ManifestVer& manifestVersion); std::vector<FieldProcessInfo> GetLocalizationFieldProcessInfo(const ManifestVer& manifestVersion, bool forRootFields = false); std::vector<FieldProcessInfo> GetAgreementFieldProcessInfo(const ManifestVer& manifestVersion); std::vector<FieldProcessInfo> GetMarketsFieldProcessInfo(const ManifestVer& manifestVersion); std::vector<FieldProcessInfo> GetAppsAndFeaturesEntryFieldProcessInfo(const ManifestVer& manifestVersion); // This method takes YAML root node and list of manifest field info. // Yaml lib does not support case insensitive search and it allows duplicate keys. If duplicate keys exist, // the value is undefined. So in this method, we will iterate through the node map and process each individual // pair ourselves. This also helps with generating aggregated error rather than throwing on first failure. std::vector<ValidationError> ValidateAndProcessFields( const YAML::Node& rootNode, const std::vector<FieldProcessInfo>& fieldInfos); void ProcessDependenciesNode(DependencyType type, const YAML::Node& rootNode); std::vector<ValidationError> ProcessPackageDependenciesNode(const YAML::Node& rootNode); std::vector<ValidationError> ProcessAgreementsNode(const YAML::Node& agreementsNode); std::vector<ValidationError> ProcessMarketsNode(const YAML::Node& marketsNode); std::vector<ValidationError> ProcessAppsAndFeaturesEntriesNode(const YAML::Node& appsAndFeaturesEntriesNode); std::vector<ValidationError> ProcessExpectedReturnCodesNode(const YAML::Node& returnCodesNode); std::vector<ValidationError> PopulateManifestInternal(const YAML::Node& rootNode, Manifest& manifest, const ManifestVer& manifestVersion, bool fullValidation); }; }
61.75
168
0.736264
[ "vector" ]
7f4691e84a790304a54cbf0532751d062376375c
9,626
h
C
c10/core/impl/InlineStreamGuard.h
vuanvin/pytorch
9267fd8d7395074001ad7cf2a8f28082dbff6b0b
[ "Intel" ]
183
2018-04-06T21:10:36.000Z
2022-03-30T15:05:24.000Z
c10/core/impl/InlineStreamGuard.h
vuanvin/pytorch
9267fd8d7395074001ad7cf2a8f28082dbff6b0b
[ "Intel" ]
631
2018-06-05T16:59:11.000Z
2022-03-31T16:26:57.000Z
c10/core/impl/InlineStreamGuard.h
vuanvin/pytorch
9267fd8d7395074001ad7cf2a8f28082dbff6b0b
[ "Intel" ]
58
2018-06-05T16:40:18.000Z
2022-03-16T15:37:29.000Z
#pragma once #include <c10/core/impl/InlineDeviceGuard.h> #include <c10/util/ArrayRef.h> #include <c10/util/irange.h> namespace c10 { namespace impl { /** * A StreamGuard is an RAII class that changes the current device * to the device corresponding to some stream, and changes the * default stream on that device to be this stream. * * InlineStreamGuard is a helper class for implementing StreamGuards. * See InlineDeviceGuard for guidance on how to use this class. */ template <typename T> class InlineStreamGuard : private InlineDeviceGuard<T> { public: /// No default constructor, see Note [Omitted default constructor from RAII] explicit InlineStreamGuard() = delete; /// Set the current device to the device associated with the passed stream, /// and set the current stream on that device to the passed stream. explicit InlineStreamGuard(Stream stream) : InlineDeviceGuard<T>(stream.device()), original_stream_of_original_device_( this->impl_.getStream(original_device())), original_stream_of_current_device_(this->impl_.exchangeStream(stream)), current_stream_(stream) {} /// This constructor exists purely for testing template < typename U = T, typename = typename std::enable_if< std::is_same<U, VirtualGuardImpl>::value>::type> explicit InlineStreamGuard( Stream stream, const DeviceGuardImplInterface* impl) : InlineDeviceGuard<T>( stream.device(), impl ? impl : getDeviceGuardImpl(stream.device_type())), original_stream_of_original_device_( this->impl_.getStream(original_device())), original_stream_of_current_device_(this->impl_.exchangeStream(stream)), current_stream_(stream) {} /// Copy is disallowed InlineStreamGuard(const InlineStreamGuard<T>&) = delete; InlineStreamGuard<T>& operator=(const InlineStreamGuard<T>&) = delete; /// Move is disallowed, as StreamGuard does not have an uninitialized state, /// which is required for moves on types with nontrivial destructors. InlineStreamGuard(InlineStreamGuard<T>&& other) = delete; InlineStreamGuard& operator=(InlineStreamGuard<T>&& other) = delete; ~InlineStreamGuard() { this->impl_.exchangeStream(original_stream_of_current_device_); } /// Resets the currently set stream to the original stream and /// the currently set device to the original device. Then, /// set the current device to the device associated with the passed stream, /// and set the current stream on that device to the passed stream. /// /// NOTE: this implementation may skip some stream/device setting if /// it can prove that it is unnecessary. /// /// WARNING: reset_stream does NOT preserve previously set streams on /// different devices. If you need to set streams on multiple devices /// use MultiStreamGuard instead. void reset_stream(Stream stream) { // TODO: make a version that takes an impl argument. Unfortunately, // that will require SFINAE because impl is only valid for the // VirtualGuardImpl specialization. if (stream.device() == this->current_device()) { this->impl_.exchangeStream(stream); current_stream_ = stream; } else { // Destruct and reconstruct the StreamGuard in-place this->impl_.exchangeStream(original_stream_of_current_device_); this->reset_device(stream.device()); original_stream_of_current_device_ = this->impl_.exchangeStream(stream); current_stream_ = stream; } } // It's not clear if set_device should also reset the current stream // if the device is unchanged; therefore, we don't provide it. // The situation is somewhat clearer with reset_device, but it's still // a pretty weird thing to do, so haven't added this either. /// Returns the stream of the original device prior to this guard. Subtly, /// the stream returned here is the original stream of the *original* /// device; i.e., it's the stream that your computation *would* have /// been put on, if it hadn't been for this meddling stream guard. /// This is usually what you want. Stream original_stream() const { return original_stream_of_original_device_; } /// Returns the most recent stream that was set using this device guard, /// either from construction, or via set_stream. Stream current_stream() const { return current_stream_; } /// Returns the most recent device that was set using this device guard, /// either from construction, or via set_device/reset_device/set_index. Device current_device() const { return InlineDeviceGuard<T>::current_device(); } /// Returns the device that was set at the most recent reset_stream(), /// or otherwise the device at construction time. Device original_device() const { return InlineDeviceGuard<T>::original_device(); } private: Stream original_stream_of_original_device_; // what the user probably cares about Stream original_stream_of_current_device_; // what we need to restore Stream current_stream_; }; /** * An OptionalStreamGuard is an RAII class that sets a device to some value on * initialization, and resets the device to its original value on destruction. * See InlineOptionalDeviceGuard for more guidance on how to use this class. */ template <typename T> class InlineOptionalStreamGuard { public: /// Creates an uninitialized stream guard. explicit InlineOptionalStreamGuard() : guard_() // See Note [Explicit initialization of optional fields] {} /// Set the current device to the device associated with the passed stream, /// and set the current stream on that device to the passed stream, /// if the passed stream is not nullopt. explicit InlineOptionalStreamGuard(optional<Stream> stream_opt) : guard_() { if (stream_opt.has_value()) { guard_.emplace(stream_opt.value()); } } /// All constructors of StreamGuard are valid for OptionalStreamGuard template <typename... Args> explicit InlineOptionalStreamGuard(Args&&... args) : guard_(in_place, std::forward<Args>(args)...) {} // See Note [Move construction for RAII guards is tricky] InlineOptionalStreamGuard(InlineOptionalStreamGuard<T>&& other) = delete; // See Note [Move assignment for RAII guards is tricky] InlineOptionalStreamGuard& operator=(InlineOptionalStreamGuard&& other) = delete; /// Resets the currently set stream to the original stream and /// the currently set device to the original device. Then, /// set the current device to the device associated with the passed stream, /// and set the current stream on that device to the passed stream. /// Initializes the OptionalStreamGuard if it was not previously initialized. void reset_stream(Stream stream) { if (guard_.has_value()) { guard_->reset_stream(stream); } else { guard_.emplace(stream); } } /// Returns the stream that was set at the time the guard was most recently /// initialized, or nullopt if the guard is uninitialized. optional<Stream> original_stream() const { return guard_.has_value() ? make_optional(guard_->original_stream()) : nullopt; } /// Returns the most recent stream that was set using this stream guard, /// either from construction, or via reset_stream, if the guard is /// initialized, or nullopt if the guard is uninitialized. optional<Stream> current_stream() const { return guard_.has_value() ? make_optional(guard_->current_stream()) : nullopt; } /// Restore the original device and stream, resetting this guard to /// uninitialized state. void reset() { guard_.reset(); } private: optional<InlineStreamGuard<T>> guard_; }; template <typename T> class InlineMultiStreamGuard { public: /// Calls `set_stream` on each of the streams in the list. /// This may be useful if you need to set different streams /// for different devices. explicit InlineMultiStreamGuard(ArrayRef<Stream> streams) { if (!streams.empty()) { impl_.emplace(getDeviceTypeOfStreams(streams)); original_streams_.reserve(streams.size()); for (const Stream& s : streams) { original_streams_.push_back(this->impl_->exchangeStream(s)); } } } /// Copy is disallowed InlineMultiStreamGuard(const InlineMultiStreamGuard&) = delete; InlineMultiStreamGuard<T>& operator=(const InlineMultiStreamGuard&) = delete; /// Move is disallowed, as StreamGuard does not have an uninitialized state, /// which is required for moves on types with nontrivial destructors. InlineMultiStreamGuard(InlineMultiStreamGuard&& other) = delete; InlineMultiStreamGuard& operator=(InlineMultiStreamGuard&& other) = delete; ~InlineMultiStreamGuard() { for (const Stream& s : original_streams_) { this->impl_->exchangeStream(s); } } protected: optional<T> impl_; private: /// The original streams that were active on all devices. std::vector<Stream> original_streams_; static DeviceType getDeviceTypeOfStreams(ArrayRef<Stream> streams) { TORCH_INTERNAL_ASSERT(!streams.empty()); DeviceType type = streams[0].device_type(); for (const auto idx : c10::irange(1, streams.size())) { TORCH_CHECK_VALUE( streams[idx].device_type() == type, "Streams have a mix of device types: stream 0 is on ", streams[0].device(), " while stream ", idx, " is on device ", streams[idx].device()); } return type; } }; } // namespace impl } // namespace c10
37.455253
80
0.710576
[ "vector" ]
7f46b1e46863ccd96927b2a32ba4cab9e94f77bd
10,575
c
C
third_party/UVM/uvm-1.2/src/dpi/uvm_hdl_vcs.c
parzival3/Surelog
cf126533ebfb2af7df321057af9e3535feb30487
[ "Apache-2.0" ]
156
2019-11-16T17:29:55.000Z
2022-01-21T05:41:13.000Z
third_party/UVM/uvm-1.2/src/dpi/uvm_hdl_vcs.c
parzival3/Surelog
cf126533ebfb2af7df321057af9e3535feb30487
[ "Apache-2.0" ]
414
2021-06-11T07:22:01.000Z
2022-03-31T22:06:14.000Z
third_party/UVM/uvm-1.2/src/dpi/uvm_hdl_vcs.c
parzival3/Surelog
cf126533ebfb2af7df321057af9e3535feb30487
[ "Apache-2.0" ]
30
2019-11-18T16:31:40.000Z
2021-12-26T01:22:51.000Z
//---------------------------------------------------------------------- // Copyright 2007-2011 Cadence Design Systems, Inc. // Copyright 2009-2010 Mentor Graphics Corporation // Copyright 2010-2011 Synopsys, Inc. // All Rights Reserved Worldwide // // 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 "uvm_dpi.h" #include <math.h> #include "svdpi.h" #include "vcsuser.h" #ifdef VCSMX #include "mhpi_user.h" #include "vhpi_user.h" #endif /* * UVM HDL access C code. * */ /* * This C code checks to see if there is PLI handle * with a value set to define the maximum bit width. * * If no such variable is found, then the default * width of 1024 is used. * * This function should only get called once or twice, * its return value is cached in the caller. * */ static int uvm_hdl_max_width() { vpiHandle ms; s_vpi_value value_s = { vpiIntVal, { 0 } }; ms = vpi_handle_by_name((PLI_BYTE8*) "uvm_pkg::UVM_HDL_MAX_WIDTH", 0); if(ms == 0) return 1024; /* If nothing else is defined, this is the DEFAULT */ vpi_get_value(ms, &value_s); return value_s.value.integer; } /* * Given a path, look the path name up using the PLI, * and set it to 'value'. */ static int uvm_hdl_set_vlog(char *path, p_vpi_vecval value, PLI_INT32 flag) { static int maxsize = -1; vpiHandle r; s_vpi_value value_s = { vpiIntVal, { 0 } }; s_vpi_time time_s = { vpiSimTime, 0, 0, 0.0 }; //vpi_printf("uvm_hdl_set_vlog(%s,%0x)\n",path,value[0].aval); r = vpi_handle_by_name(path, 0); if(r == 0) { const char * err_str = "set: unable to locate hdl path (%s)\n Either the name is incorrect, or you may not have PLI/ACC visibility to that name"; char buffer[strlen(err_str) + strlen(path)]; sprintf(buffer, err_str, path); m_uvm_report_dpi(M_UVM_ERROR, (char*) "UVM/DPI/HDL_SET", &buffer[0], M_UVM_NONE, (char*)__FILE__, __LINE__); return 0; } else { if(maxsize == -1) maxsize = uvm_hdl_max_width(); if (flag == vpiReleaseFlag) { //size = vpi_get(vpiSize, r); //value_p = (p_vpi_vecval)(malloc(((size-1)/32+1)*8*sizeof(s_vpi_vecval))); //value = &value_p; } value_s.format = vpiVectorVal; value_s.value.vector = value; vpi_put_value(r, &value_s, &time_s, flag); //if (value_p != NULL) // free(value_p); if (value == NULL) { value = value_s.value.vector; } } return 1; } /* * Given a path, look the path name up using the PLI * and return its 'value'. */ static int uvm_hdl_get_vlog(char *path, p_vpi_vecval value, PLI_INT32 flag) { static int maxsize = -1; int i, size, chunks; vpiHandle r; s_vpi_value value_s; r = vpi_handle_by_name(path, 0); if(r == 0) { const char * err_str = "get: unable to locate hdl path (%s)\n Either the name is incorrect, or you may not have PLI/ACC visibility to that name"; char buffer[strlen(err_str) + strlen(path)]; sprintf(buffer, err_str, path); m_uvm_report_dpi(M_UVM_ERROR, (char*)"UVM/DPI/HDL_GET", &buffer[0], M_UVM_NONE, (char*)__FILE__, __LINE__); // Exiting is too harsh. Just return instead. // tf_dofinish(); return 0; } else { if(maxsize == -1) maxsize = uvm_hdl_max_width(); size = vpi_get(vpiSize, r); if(size > maxsize) { const char * err_str = "uvm_reg : hdl path '%s' is %0d bits, but the maximum size is %0d. You can increase the maximum via a compile-time flag: +define+UVM_HDL_MAX_WIDTH=<value>"; char buffer[strlen(err_str) + strlen(path) + (2*int_str_max(10))]; sprintf(buffer, err_str, path, size, maxsize); m_uvm_report_dpi(M_UVM_ERROR, (char*)"UVM/DPI/HDL_SET", &buffer[0], M_UVM_NONE, (char*)__FILE__, __LINE__); return 0; } chunks = (size-1)/32 + 1; value_s.format = vpiVectorVal; vpi_get_value(r, &value_s); /*dpi and vpi are reversed*/ for(i=0;i<chunks; ++i) { value[i].aval = value_s.value.vector[i].aval; value[i].bval = value_s.value.vector[i].bval; } } //vpi_printf("uvm_hdl_get_vlog(%s,%0x)\n",path,value[0].aval); return 1; } /* * Given a path, look the path name up using the PLI, * but don't set or get. Just check. * * Return 0 if NOT found. * Return 1 if found. */ int uvm_hdl_check_path(char *path) { vpiHandle r; r = vpi_handle_by_name(path, 0); if(r == 0) return 0; else return 1; } /* * convert binary to integer */ long int uvm_hdl_btoi(char *binVal) { long int remainder, dec=0, j = 0; unsigned long long int bin; int i; char tmp[2]; tmp[1] = '\0'; for(i= strlen(binVal) -1 ; i >= 0 ; i--) { tmp[0] = binVal[i]; bin = atoi(tmp); dec = dec+(bin*(pow(2,j))); j++; } return(dec); } /* *decimal to hex conversion */ char *uvm_hdl_dtob(long int decimalNumber) { int remainder, quotient; int i=0,j, length; int binN[65]; static char binaryNumber[65]; char *str = (char*) malloc(sizeof(char)); quotient = decimalNumber; do { binN[i++] = quotient%2; quotient = quotient/2; } while (quotient!=0); length = i; for (i=length-1, j = 0; i>=0; i--) { binaryNumber[j++] = binN[i]?'1':'0'; } binaryNumber[j] = '\0'; return(binaryNumber); } /* * Mixed lanaguage API Get calls */ #ifdef VCSMX int uvm_hdl_get_mhdl(char *path, p_vpi_vecval value) { long int value_int; char *binVal; int i = 0; vhpiValueT value1; p_vpi_vecval vecval; mhpi_initialize('/'); mhpiHandleT mhpiH = mhpi_handle_by_name(path, 0); vhpiHandleT vhpiH = (long unsigned int *)mhpi_get_vhpi_handle(mhpiH); value1.format=vhpiStrVal; value1.bufSize = vhpi_get(vhpiSizeP, vhpiH); value1.value.str = (char*)malloc(value1.bufSize*sizeof(char)+1); if (vhpi_get_value(vhpiH, &value1) == 0) { binVal = value1.value.str; value_int = uvm_hdl_btoi(binVal); value->aval = (PLI_UINT32) value_int; value->bval = 0; mhpi_release_parent_handle(mhpiH); free(value1.value.str); return(1); } else { mhpi_release_parent_handle(mhpiH); free(value1.value.str); return (0); } } #endif /* * Given a path, look the path name up using the PLI * or the VHPI, and return its 'value'. */ int uvm_hdl_read(char *path, p_vpi_vecval value) { #ifndef VCSMX return uvm_hdl_get_vlog(path, value, vpiNoDelay); #else mhpi_initialize('/'); mhpiHandleT h = mhpi_handle_by_name(path, 0); if (mhpi_get(mhpiPliP, h) == mhpiVpiPli) { mhpi_release_parent_handle(h); return uvm_hdl_get_vlog(path, value, vpiNoDelay); } else if (mhpi_get(mhpiPliP, h) == mhpiVhpiPli) { mhpi_release_parent_handle(h); return uvm_hdl_get_mhdl(path,value); } #endif } /* * Mixed Language API Set calls */ #ifdef VCSMX int uvm_hdl_set_mhdl(char *path, p_vpi_vecval value, mhpiPutValueFlagsT flags) { mhpi_initialize('/'); mhpiRealT forceDelay = 0; mhpiRealT cancelDelay = -1; mhpiReturnT ret; mhpiHandleT h = mhpi_handle_by_name(path, 0); mhpiHandleT mhpi_mhRegion = mhpi_handle(mhpiScope, h); int val = value->aval; char *force_value = uvm_hdl_dtob(val); ret = mhpi_force_value(path, mhpi_mhRegion, force_value, flags, forceDelay, cancelDelay); mhpi_release_parent_handle(h); if (ret == mhpiRetOk) { return(1); } else return(0); } #endif /* * Given a path, look the path name up using the PLI * or the VHPI, and set it to 'value'. */ int uvm_hdl_deposit(char *path, p_vpi_vecval value) { #ifndef VCSMX return uvm_hdl_set_vlog(path, value, vpiNoDelay); #else mhpi_initialize('/'); mhpiHandleT h = mhpi_handle_by_name(path, 0); if (mhpi_get(mhpiPliP, h) == mhpiVpiPli) { mhpi_release_parent_handle(h); return uvm_hdl_set_vlog(path, value, vpiNoDelay); } else if (mhpi_get(mhpiPliP, h) == mhpiVhpiPli) { mhpi_release_parent_handle(h); return uvm_hdl_set_mhdl(path, value, mhpiNoDelay); } else return (0); #endif } /* * Given a path, look the path name up using the PLI * or the VHPI, and set it to 'value'. */ int uvm_hdl_force(char *path, p_vpi_vecval value) { #ifndef VCSMX return uvm_hdl_set_vlog(path, value, vpiForceFlag); #else mhpi_initialize('/'); mhpiHandleT h = mhpi_handle_by_name(path, 0); if (mhpi_get(mhpiPliP, h) == mhpiVpiPli) { mhpi_release_parent_handle(h); return uvm_hdl_set_vlog(path, value, vpiForceFlag); } else if (mhpi_get(mhpiPliP, h) == mhpiVhpiPli) { mhpi_release_parent_handle(h); return uvm_hdl_set_mhdl(path, value, mhpiForce); } else return (0); #endif } /* * Given a path, look the path name up using the PLI * or the VHPI, and release it. */ int uvm_hdl_release_and_read(char *path, p_vpi_vecval value) { return uvm_hdl_set_vlog(path, value, vpiReleaseFlag); } /* * Given a path, look the path name up using the PLI * or the VHPI, and release it. */ int uvm_hdl_release(char *path) { s_vpi_vecval value; p_vpi_vecval valuep = &value; #ifndef VCSMX return uvm_hdl_set_vlog(path, valuep, vpiReleaseFlag); #else mhpi_initialize('/'); mhpiHandleT h = mhpi_handle_by_name(path, 0); mhpiReturnT ret; if (mhpi_get(mhpiPliP, h) == mhpiVpiPli) { return uvm_hdl_set_vlog(path, valuep, vpiReleaseFlag); } else if (mhpi_get(mhpiPliP, h) == mhpiVhpiPli) { mhpiHandleT mhpi_mhRegion = mhpi_handle(mhpiScope, h); ret = mhpi_release_force(path, mhpi_mhRegion); if (ret == mhpiRetOk) { return(1); } else return(0); } else return (0); #endif }
24.765808
186
0.621749
[ "vector" ]
7f4c3470020c1297cbc8d63e2eaef2e8b84e7a53
32,379
h
C
source/blender/editors/include/ED_anim_api.h
ColinKinloch/blender
f149d5e4b21f372f779fdb28b39984355c9682a6
[ "Naumen", "Condor-1.1", "MS-PL" ]
1
2020-07-19T21:49:43.000Z
2020-07-19T21:49:43.000Z
source/blender/editors/include/ED_anim_api.h
ColinKinloch/blender
f149d5e4b21f372f779fdb28b39984355c9682a6
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
source/blender/editors/include/ED_anim_api.h
ColinKinloch/blender
f149d5e4b21f372f779fdb28b39984355c9682a6
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2008 Blender Foundation. * All rights reserved. */ /** \file * \ingroup editors */ #ifndef __ED_ANIM_API_H__ #define __ED_ANIM_API_H__ #ifdef __cplusplus extern "C" { #endif struct AnimData; struct Depsgraph; struct ID; struct ListBase; struct ARegion; struct Main; struct ReportList; struct ScrArea; struct SpaceLink; struct View2D; struct bContext; struct wmKeyConfig; struct Object; struct Scene; struct bDopeSheet; struct FCurve; struct FModifier; struct bAction; struct uiBlock; struct uiLayout; struct PointerRNA; struct PropertyRNA; /* ************************************************ */ /* ANIMATION CHANNEL FILTERING */ /* anim_filter.c */ /* --------------- Context --------------------- */ /* This struct defines a structure used for animation-specific * 'context' information */ typedef struct bAnimContext { /** data to be filtered for use in animation editor */ void *data; /** type of data eAnimCont_Types */ short datatype; /** editor->mode */ short mode; /** sa->spacetype */ short spacetype; /** active region -> type (channels or main) */ short regiontype; /** editor host */ struct ScrArea *sa; /** editor data */ struct SpaceLink *sl; /** region within editor */ struct ARegion *region; /** dopesheet data for editor (or which is being used) */ struct bDopeSheet *ads; /** Current Main */ struct Main *bmain; /** active scene */ struct Scene *scene; /** active scene layer */ struct ViewLayer *view_layer; /** active object */ struct Object *obact; /** active set of markers */ ListBase *markers; /** pointer to current reports list */ struct ReportList *reports; /** Scale factor for height of channels (i.e. based on the size of keyframes). */ float yscale_fac; } bAnimContext; /* Main Data container types */ typedef enum eAnimCont_Types { ANIMCONT_NONE = 0, /* invalid or no data */ ANIMCONT_ACTION = 1, /* action (bAction) */ ANIMCONT_SHAPEKEY = 2, /* shapekey (Key) */ ANIMCONT_GPENCIL = 3, /* grease pencil (screen) */ ANIMCONT_DOPESHEET = 4, /* dopesheet (bDopesheet) */ ANIMCONT_FCURVES = 5, /* animation F-Curves (bDopesheet) */ ANIMCONT_DRIVERS = 6, /* drivers (bDopesheet) */ ANIMCONT_NLA = 7, /* nla (bDopesheet) */ ANIMCONT_CHANNEL = 8, /* animation channel (bAnimListElem) */ ANIMCONT_MASK = 9, /* mask dopesheet */ ANIMCONT_TIMELINE = 10, /* "timeline" editor (bDopeSheet) */ } eAnimCont_Types; /* --------------- Channels -------------------- */ /* This struct defines a structure used for quick and uniform access for * channels of animation data */ typedef struct bAnimListElem { struct bAnimListElem *next, *prev; /** source data this elem represents */ void *data; /** (eAnim_ChannelType) one of the ANIMTYPE_* values */ int type; /** copy of elem's flags for quick access */ int flag; /** for un-named data, the index of the data in its collection */ int index; /** (eAnim_Update_Flags) tag the element for updating */ char update; /** tag the included data. Temporary always */ char tag; /** (eAnim_KeyType) type of motion data to expect */ short datatype; /** motion data - mostly F-Curves, but can be other types too */ void *key_data; /** * \note * id here is the "IdAdtTemplate"-style datablock (e.g. Object, Material, Texture, NodeTree) * from which evaluation of the RNA-paths takes place. It's used to figure out how deep * channels should be nested (e.g. for Textures/NodeTrees) in the tree, and allows property * lookups (e.g. for sliders and for inserting keyframes) to work. If we had instead used * bAction or something similar, none of this would be possible: although it's trivial * to use an IdAdtTemplate type to find the source action a channel (e.g. F-Curve) comes from * (i.e. in the AnimEditors, it *must* be the active action, as only that can be edited), * it's impossible to go the other way (i.e. one action may be used in multiple places). */ /** ID block that channel is attached to */ struct ID *id; /** source of the animation data attached to ID block (for convenience) */ struct AnimData *adt; /** * For list element which corresponds to a f-curve, this is an ID which * owns the f-curve. * * For example, if the f-curve is coming from Action, this id will be set to * action's ID. But if this is a f-curve which is a driver, then the owner * is set to, for example, object. * * Note, that this is different from id above. The id above will be set to * an object if the f-curve is coming from action associated with that * object. */ struct ID *fcurve_owner_id; /** * for per-element F-Curves * (e.g. NLA Control Curves), the element that this represents (e.g. NlaStrip) */ void *owner; } bAnimListElem; /** * Some types for easier type-testing * * \note need to keep the order of these synchronized with the channels define code * which is used for drawing and handling channel lists for. */ typedef enum eAnim_ChannelType { ANIMTYPE_NONE = 0, ANIMTYPE_ANIMDATA, ANIMTYPE_SPECIALDATA__UNUSED, ANIMTYPE_SUMMARY, ANIMTYPE_SCENE, ANIMTYPE_OBJECT, ANIMTYPE_GROUP, ANIMTYPE_FCURVE, ANIMTYPE_NLACONTROLS, ANIMTYPE_NLACURVE, ANIMTYPE_FILLACTD, ANIMTYPE_FILLDRIVERS, ANIMTYPE_DSMAT, ANIMTYPE_DSLAM, ANIMTYPE_DSCAM, ANIMTYPE_DSCACHEFILE, ANIMTYPE_DSCUR, ANIMTYPE_DSSKEY, ANIMTYPE_DSWOR, ANIMTYPE_DSNTREE, ANIMTYPE_DSPART, ANIMTYPE_DSMBALL, ANIMTYPE_DSARM, ANIMTYPE_DSMESH, ANIMTYPE_DSTEX, ANIMTYPE_DSLAT, ANIMTYPE_DSLINESTYLE, ANIMTYPE_DSSPK, ANIMTYPE_DSGPENCIL, ANIMTYPE_DSMCLIP, ANIMTYPE_DSHAIR, ANIMTYPE_DSPOINTCLOUD, ANIMTYPE_DSVOLUME, ANIMTYPE_SHAPEKEY, ANIMTYPE_GPDATABLOCK, ANIMTYPE_GPLAYER, ANIMTYPE_MASKDATABLOCK, ANIMTYPE_MASKLAYER, ANIMTYPE_NLATRACK, ANIMTYPE_NLAACTION, ANIMTYPE_PALETTE, /* always as last item, the total number of channel types... */ ANIMTYPE_NUM_TYPES, } eAnim_ChannelType; /* types of keyframe data in bAnimListElem */ typedef enum eAnim_KeyType { ALE_NONE = 0, /* no keyframe data */ ALE_FCURVE, /* F-Curve */ ALE_GPFRAME, /* Grease Pencil Frames */ ALE_MASKLAY, /* Mask */ ALE_NLASTRIP, /* NLA Strips */ ALE_ALL, /* All channels summary */ ALE_SCE, /* Scene summary */ ALE_OB, /* Object summary */ ALE_ACT, /* Action summary */ ALE_GROUP, /* Action Group summary */ } eAnim_KeyType; /* Flags for specifying the types of updates (i.e. recalculation/refreshing) that * needs to be performed to the data contained in a channel following editing. * For use with ANIM_animdata_update() */ typedef enum eAnim_Update_Flags { ANIM_UPDATE_DEPS = (1 << 0), /* referenced data and dependencies get refreshed */ ANIM_UPDATE_ORDER = (1 << 1), /* keyframes need to be sorted */ ANIM_UPDATE_HANDLES = (1 << 2), /* recalculate handles */ } eAnim_Update_Flags; /* used for most tools which change keyframes (flushed by ANIM_animdata_update) */ #define ANIM_UPDATE_DEFAULT (ANIM_UPDATE_DEPS | ANIM_UPDATE_ORDER | ANIM_UPDATE_HANDLES) #define ANIM_UPDATE_DEFAULT_NOHANDLES (ANIM_UPDATE_DEFAULT & ~ANIM_UPDATE_HANDLES) /* ----------------- Filtering -------------------- */ /* filtering flags - under what circumstances should a channel be returned */ typedef enum eAnimFilter_Flags { /** data which channel represents is fits the dopesheet filters * (i.e. scene visibility criteria) */ /* XXX: it's hard to think of any examples where this *ISN'T* the case... * perhaps becomes implicit?. */ ANIMFILTER_DATA_VISIBLE = (1 << 0), /** channel is visible within the channel-list hierarchy * (i.e. F-Curves within Groups in ActEdit) */ ANIMFILTER_LIST_VISIBLE = (1 << 1), /** channel has specifically been tagged as visible in Graph Editor (* Graph Editor Only) */ ANIMFILTER_CURVE_VISIBLE = (1 << 2), /** include summary channels and "expanders" (for drawing/mouse-selection in channel list) */ ANIMFILTER_LIST_CHANNELS = (1 << 3), /** for its type, channel should be "active" one */ ANIMFILTER_ACTIVE = (1 << 4), /** channel is a child of the active group (* Actions speciality) */ ANIMFILTER_ACTGROUPED = (1 << 5), /** channel must be selected/not-selected, but both must not be set together */ ANIMFILTER_SEL = (1 << 6), ANIMFILTER_UNSEL = (1 << 7), /** editability status - must be editable to be included */ ANIMFILTER_FOREDIT = (1 << 8), /** only selected animchannels should be considerable as editable - mainly * for Graph Editor's option for keys on select curves only */ ANIMFILTER_SELEDIT = (1 << 9), /** flags used to enforce certain data types * \node the ones for curves and NLA tracks were redundant and have been removed for now... */ ANIMFILTER_ANIMDATA = (1 << 10), /** duplicate entries for animation data attached to multi-user blocks must not occur */ ANIMFILTER_NODUPLIS = (1 << 11), /** for checking if we should keep some collapsed channel around (internal use only!) */ ANIMFILTER_TMP_PEEK = (1 << 30), /** ignore ONLYSEL flag from filterflag, (internal use only!) */ ANIMFILTER_TMP_IGNORE_ONLYSEL = (1u << 31), } eAnimFilter_Flags; /* ---------- Flag Checking Macros ------------ */ // xxx check on all of these flags again... /* Dopesheet only */ /* 'Scene' channels */ #define SEL_SCEC(sce) (CHECK_TYPE_INLINE(sce, Scene *), ((sce->flag & SCE_DS_SELECTED))) #define EXPANDED_SCEC(sce) (CHECK_TYPE_INLINE(sce, Scene *), ((sce->flag & SCE_DS_COLLAPSED) == 0)) /* 'Sub-Scene' channels (flags stored in Data block) */ #define FILTER_WOR_SCED(wo) (CHECK_TYPE_INLINE(wo, World *), (wo->flag & WO_DS_EXPAND)) #define FILTER_LS_SCED(linestyle) ((linestyle->flag & LS_DS_EXPAND)) /* 'Object' channels */ #define SEL_OBJC(base) (CHECK_TYPE_INLINE(base, Base *), ((base->flag & SELECT))) #define EXPANDED_OBJC(ob) \ (CHECK_TYPE_INLINE(ob, Object *), ((ob->nlaflag & OB_ADS_COLLAPSED) == 0)) /* 'Sub-object' channels (flags stored in Data block) */ #define FILTER_SKE_OBJD(key) (CHECK_TYPE_INLINE(key, Key *), ((key->flag & KEY_DS_EXPAND))) #define FILTER_MAT_OBJD(ma) (CHECK_TYPE_INLINE(ma, Material *), ((ma->flag & MA_DS_EXPAND))) #define FILTER_LAM_OBJD(la) (CHECK_TYPE_INLINE(la, Light *), ((la->flag & LA_DS_EXPAND))) #define FILTER_CAM_OBJD(ca) (CHECK_TYPE_INLINE(ca, Camera *), ((ca->flag & CAM_DS_EXPAND))) #define FILTER_CACHEFILE_OBJD(cf) \ (CHECK_TYPE_INLINE(cf, CacheFile *), ((cf->flag & CACHEFILE_DS_EXPAND))) #define FILTER_CUR_OBJD(cu) (CHECK_TYPE_INLINE(cu, Curve *), ((cu->flag & CU_DS_EXPAND))) #define FILTER_PART_OBJD(part) \ (CHECK_TYPE_INLINE(part, ParticleSettings *), ((part->flag & PART_DS_EXPAND))) #define FILTER_MBALL_OBJD(mb) (CHECK_TYPE_INLINE(mb, MetaBall *), ((mb->flag2 & MB_DS_EXPAND))) #define FILTER_ARM_OBJD(arm) (CHECK_TYPE_INLINE(arm, bArmature *), ((arm->flag & ARM_DS_EXPAND))) #define FILTER_MESH_OBJD(me) (CHECK_TYPE_INLINE(me, Mesh *), ((me->flag & ME_DS_EXPAND))) #define FILTER_LATTICE_OBJD(lt) (CHECK_TYPE_INLINE(lt, Lattice *), ((lt->flag & LT_DS_EXPAND))) #define FILTER_SPK_OBJD(spk) (CHECK_TYPE_INLINE(spk, Speaker *), ((spk->flag & SPK_DS_EXPAND))) #define FILTER_HAIR_OBJD(ha) (CHECK_TYPE_INLINE(ha, Hair *), ((ha->flag & HA_DS_EXPAND))) #define FILTER_POINTS_OBJD(pt) (CHECK_TYPE_INLINE(pt, PointCloud *), ((pt->flag & PT_DS_EXPAND))) #define FILTER_VOLUME_OBJD(vo) (CHECK_TYPE_INLINE(vo, Volume *), ((vo->flag & VO_DS_EXPAND))) /* Variable use expanders */ #define FILTER_NTREE_DATA(ntree) \ (CHECK_TYPE_INLINE(ntree, bNodeTree *), ((ntree->flag & NTREE_DS_EXPAND))) #define FILTER_TEX_DATA(tex) (CHECK_TYPE_INLINE(tex, Tex *), ((tex->flag & TEX_DS_EXPAND))) /* 'Sub-object/Action' channels (flags stored in Action) */ #define SEL_ACTC(actc) ((actc->flag & ACT_SELECTED)) #define EXPANDED_ACTC(actc) ((actc->flag & ACT_COLLAPSED) == 0) /* 'Sub-AnimData' channels */ #define EXPANDED_DRVD(adt) ((adt->flag & ADT_DRIVERS_COLLAPSED) == 0) /* Actions (also used for Dopesheet) */ /* Action Channel Group */ #define EDITABLE_AGRP(agrp) ((agrp->flag & AGRP_PROTECTED) == 0) #define EXPANDED_AGRP(ac, agrp) \ (((!(ac) || ((ac)->spacetype != SPACE_GRAPH)) && (agrp->flag & AGRP_EXPANDED)) || \ (((ac) && ((ac)->spacetype == SPACE_GRAPH)) && (agrp->flag & AGRP_EXPANDED_G))) #define SEL_AGRP(agrp) ((agrp->flag & AGRP_SELECTED) || (agrp->flag & AGRP_ACTIVE)) /* F-Curve Channels */ #define EDITABLE_FCU(fcu) ((fcu->flag & FCURVE_PROTECTED) == 0) #define SEL_FCU(fcu) (fcu->flag & FCURVE_SELECTED) /* ShapeKey mode only */ #define EDITABLE_SHAPEKEY(kb) ((kb->flag & KEYBLOCK_LOCKED) == 0) #define SEL_SHAPEKEY(kb) (kb->flag & KEYBLOCK_SEL) /* Grease Pencil only */ /* Grease Pencil datablock settings */ #define EXPANDED_GPD(gpd) (gpd->flag & GP_DATA_EXPAND) /* Grease Pencil Layer settings */ #define EDITABLE_GPL(gpl) ((gpl->flag & GP_LAYER_LOCKED) == 0) #define SEL_GPL(gpl) (gpl->flag & GP_LAYER_SELECT) /* Mask Only */ /* Grease Pencil datablock settings */ #define EXPANDED_MASK(mask) (mask->flag & MASK_ANIMF_EXPAND) /* Grease Pencil Layer settings */ #define EDITABLE_MASK(masklay) ((masklay->flag & MASK_LAYERFLAG_LOCKED) == 0) #define SEL_MASKLAY(masklay) (masklay->flag & SELECT) /* NLA only */ #define SEL_NLT(nlt) (nlt->flag & NLATRACK_SELECTED) #define EDITABLE_NLT(nlt) ((nlt->flag & NLATRACK_PROTECTED) == 0) /* Movie clip only */ #define EXPANDED_MCLIP(clip) (clip->flag & MCLIP_DATA_EXPAND) /* Palette only */ #define EXPANDED_PALETTE(palette) (palette->flag & PALETTE_DATA_EXPAND) /* AnimData - NLA mostly... */ #define SEL_ANIMDATA(adt) (adt->flag & ADT_UI_SELECTED) /* -------------- Channel Defines -------------- */ /* channel heights */ #define ACHANNEL_FIRST_TOP(ac) \ (UI_view2d_scale_get_y(&(ac)->region->v2d) * -UI_TIME_SCRUB_MARGIN_Y - ACHANNEL_SKIP) #define ACHANNEL_HEIGHT(ac) (0.8f * (ac)->yscale_fac * U.widget_unit) #define ACHANNEL_SKIP (0.1f * U.widget_unit) #define ACHANNEL_STEP(ac) (ACHANNEL_HEIGHT(ac) + ACHANNEL_SKIP) /* Additional offset to give some room at the end. */ #define ACHANNEL_TOT_HEIGHT(ac, item_amount) \ (-ACHANNEL_FIRST_TOP(ac) + ACHANNEL_STEP(ac) * (item_amount + 1)) /* channel widths */ #define ACHANNEL_NAMEWIDTH (10 * U.widget_unit) /* channel toggle-buttons */ #define ACHANNEL_BUTTON_WIDTH (0.8f * U.widget_unit) /* -------------- NLA Channel Defines -------------- */ /* NLA channel heights */ #define NLACHANNEL_FIRST_TOP(ac) \ (UI_view2d_scale_get_y(&(ac)->region->v2d) * -UI_TIME_SCRUB_MARGIN_Y - NLACHANNEL_SKIP) #define NLACHANNEL_HEIGHT(snla) \ ((snla && (snla->flag & SNLA_NOSTRIPCURVES)) ? (0.8f * U.widget_unit) : (1.2f * U.widget_unit)) #define NLACHANNEL_SKIP (0.1f * U.widget_unit) #define NLACHANNEL_STEP(snla) (NLACHANNEL_HEIGHT(snla) + NLACHANNEL_SKIP) /* Additional offset to give some room at the end. */ #define NLACHANNEL_TOT_HEIGHT(ac, item_amount) \ (-NLACHANNEL_FIRST_TOP(ac) + NLACHANNEL_STEP(((SpaceNla *)(ac)->sl)) * (item_amount + 1)) /* channel widths */ #define NLACHANNEL_NAMEWIDTH (10 * U.widget_unit) /* channel toggle-buttons */ #define NLACHANNEL_BUTTON_WIDTH (0.8f * U.widget_unit) /* ---------------- API -------------------- */ /* Obtain list of filtered Animation channels to operate on. * Returns the number of channels in the list */ size_t ANIM_animdata_filter(bAnimContext *ac, ListBase *anim_data, eAnimFilter_Flags filter_mode, void *data, eAnimCont_Types datatype); /* Obtain current anim-data context from Blender Context info. * Returns whether the operation was successful. */ bool ANIM_animdata_get_context(const struct bContext *C, bAnimContext *ac); /* Obtain current anim-data context (from Animation Editor) given * that Blender Context info has already been set. * Returns whether the operation was successful. */ bool ANIM_animdata_context_getdata(bAnimContext *ac); /* Acts on bAnimListElem eAnim_Update_Flags */ void ANIM_animdata_update(bAnimContext *ac, ListBase *anim_data); void ANIM_animdata_freelist(ListBase *anim_data); /* ************************************************ */ /* ANIMATION CHANNELS LIST */ /* anim_channels_*.c */ /* ------------------------ Drawing TypeInfo -------------------------- */ /* role or level of animchannel in the hierarchy */ typedef enum eAnimChannel_Role { /** datablock expander - a "composite" channel type */ ACHANNEL_ROLE_EXPANDER = -1, /** special purposes - not generally for hierarchy processing */ /* ACHANNEL_ROLE_SPECIAL = 0, */ /* UNUSED */ /** data channel - a channel representing one of the actual building blocks of channels */ ACHANNEL_ROLE_CHANNEL = 1, } eAnimChannel_Role; /* flag-setting behavior */ typedef enum eAnimChannels_SetFlag { /** turn off */ ACHANNEL_SETFLAG_CLEAR = 0, /** turn on */ ACHANNEL_SETFLAG_ADD = 1, /** on->off, off->on */ ACHANNEL_SETFLAG_INVERT = 2, /** some on -> all off // all on */ ACHANNEL_SETFLAG_TOGGLE = 3, } eAnimChannels_SetFlag; /* types of settings for AnimChannels */ typedef enum eAnimChannel_Settings { ACHANNEL_SETTING_SELECT = 0, /** warning: for drawing UI's, need to check if this is off (maybe inverse this later) */ ACHANNEL_SETTING_PROTECT = 1, ACHANNEL_SETTING_MUTE = 2, ACHANNEL_SETTING_EXPAND = 3, /** only for Graph Editor */ ACHANNEL_SETTING_VISIBLE = 4, /** only for NLA Tracks */ ACHANNEL_SETTING_SOLO = 5, /** only for NLA Actions */ ACHANNEL_SETTING_PINNED = 6, ACHANNEL_SETTING_MOD_OFF = 7, /** channel is pinned and always visible */ ACHANNEL_SETTING_ALWAYS_VISIBLE = 8, } eAnimChannel_Settings; /* Drawing, mouse handling, and flag setting behavior... */ typedef struct bAnimChannelType { /* -- Type data -- */ /* name of the channel type, for debugging */ const char *channel_type_name; /* "level" or role in hierarchy - for finding the active channel */ eAnimChannel_Role channel_role; /* -- Drawing -- */ /* get RGB color that is used to draw the majority of the backdrop */ void (*get_backdrop_color)(bAnimContext *ac, bAnimListElem *ale, float r_color[3]); /* draw backdrop strip for channel */ void (*draw_backdrop)(bAnimContext *ac, bAnimListElem *ale, float yminc, float ymaxc); /* get depth of indention (relative to the depth channel is nested at) */ short (*get_indent_level)(bAnimContext *ac, bAnimListElem *ale); /* get offset in pixels for the start of the channel (in addition to the indent depth) */ short (*get_offset)(bAnimContext *ac, bAnimListElem *ale); /* get name (for channel lists) */ void (*name)(bAnimListElem *ale, char *name); /* get RNA property+pointer for editing the name */ bool (*name_prop)(bAnimListElem *ale, struct PointerRNA *ptr, struct PropertyRNA **prop); /* get icon (for channel lists) */ int (*icon)(bAnimListElem *ale); /* -- Settings -- */ /* check if the given setting is valid in the current context */ bool (*has_setting)(bAnimContext *ac, bAnimListElem *ale, eAnimChannel_Settings setting); /* get the flag used for this setting */ int (*setting_flag)(bAnimContext *ac, eAnimChannel_Settings setting, bool *neg); /* get the pointer to int/short where data is stored, * with type being sizeof(ptr_data) which should be fine for runtime use... * - assume that setting has been checked to be valid for current context */ void *(*setting_ptr)(bAnimListElem *ale, eAnimChannel_Settings setting, short *type); } bAnimChannelType; /* ------------------------ Drawing API -------------------------- */ /* Get typeinfo for the given channel */ const bAnimChannelType *ANIM_channel_get_typeinfo(bAnimListElem *ale); /* Print debugging info about a given channel */ void ANIM_channel_debug_print_info(bAnimListElem *ale, short indent_level); /* Draw the given channel */ void ANIM_channel_draw( bAnimContext *ac, bAnimListElem *ale, float yminc, float ymaxc, size_t channel_index); /* Draw the widgets for the given channel */ void ANIM_channel_draw_widgets(const struct bContext *C, bAnimContext *ac, bAnimListElem *ale, struct uiBlock *block, rctf *rect, size_t channel_index); /* ------------------------ Editing API -------------------------- */ /* Check if some setting for a channel is enabled * Returns: 1 = On, 0 = Off, -1 = Invalid * * - setting: eAnimChannel_Settings */ short ANIM_channel_setting_get(bAnimContext *ac, bAnimListElem *ale, eAnimChannel_Settings setting); /* Change value of some setting for a channel * - setting: eAnimChannel_Settings * - mode: eAnimChannels_SetFlag */ void ANIM_channel_setting_set(bAnimContext *ac, bAnimListElem *ale, eAnimChannel_Settings setting, eAnimChannels_SetFlag mode); /* Flush visibility (for Graph Editor) changes up/down hierarchy for changes in the given setting * - anim_data: list of the all the anim channels that can be chosen * -> filtered using ANIMFILTER_CHANNELS only, since if we took VISIBLE too, * then the channels under closed expanders get ignored... * - ale_setting: the anim channel (not in the anim_data list directly, though occurring there) * with the new state of the setting that we want flushed up/down the hierarchy * - setting: type of setting to set * - on: whether the visibility setting has been enabled or disabled */ void ANIM_flush_setting_anim_channels(bAnimContext *ac, ListBase *anim_data, bAnimListElem *ale_setting, eAnimChannel_Settings setting, eAnimChannels_SetFlag mode); /* Deselect all animation channels */ void ANIM_deselect_anim_channels( bAnimContext *ac, void *data, eAnimCont_Types datatype, bool test, eAnimChannels_SetFlag sel); /* Set the 'active' channel of type channel_type, in the given action */ void ANIM_set_active_channel(bAnimContext *ac, void *data, eAnimCont_Types datatype, eAnimFilter_Flags filter, void *channel_data, eAnim_ChannelType channel_type); /* Delete the F-Curve from the given AnimData block (if possible), * as appropriate according to animation context */ void ANIM_fcurve_delete_from_animdata(bAnimContext *ac, struct AnimData *adt, struct FCurve *fcu); /* Unlink the action from animdata if it's empty. */ bool ANIM_remove_empty_action_from_animdata(struct AnimData *adt); /* ************************************************ */ /* DRAWING API */ /* anim_draw.c */ /* ---------- Current Frame Drawing ---------------- */ /* flags for Current Frame Drawing */ enum eAnimEditDraw_CurrentFrame { /* plain time indicator with no special indicators */ /* DRAWCFRA_PLAIN = 0, */ /* UNUSED */ /* time indication in seconds or frames */ DRAWCFRA_UNIT_SECONDS = (1 << 0), /* draw indicator extra wide (for timeline) */ DRAWCFRA_WIDE = (1 << 1), }; /* main call to draw current-frame indicator in an Animation Editor */ void ANIM_draw_cfra(const struct bContext *C, struct View2D *v2d, short flag); /* main call to draw "number box" in scrollbar for current frame indicator */ void ANIM_draw_cfra_number(const struct bContext *C, struct View2D *v2d, short flag); /* ------------- Preview Range Drawing -------------- */ /* main call to draw preview range curtains */ void ANIM_draw_previewrange(const struct bContext *C, struct View2D *v2d, int end_frame_width); /* -------------- Frame Range Drawing --------------- */ /* main call to draw normal frame range indicators */ void ANIM_draw_framerange(struct Scene *scene, struct View2D *v2d); /* ************************************************* */ /* F-MODIFIER TOOLS */ /* ------------- UI Panel Drawing -------------- */ /* draw a given F-Modifier for some layout/UI-Block */ void ANIM_uiTemplate_fmodifier_draw(struct uiLayout *layout, struct ID *fcurve_owner_id, ListBase *modifiers, struct FModifier *fcm); /* ------------- Copy/Paste Buffer -------------- */ /* free the copy/paste buffer */ void ANIM_fmodifiers_copybuf_free(void); /* copy the given F-Modifiers to the buffer, returning whether anything was copied or not * assuming that the buffer has been cleared already with ANIM_fmodifiers_copybuf_free() * - active: only copy the active modifier */ bool ANIM_fmodifiers_copy_to_buf(ListBase *modifiers, bool active); /* 'Paste' the F-Modifier(s) from the buffer to the specified list * - replace: free all the existing modifiers to leave only the pasted ones */ bool ANIM_fmodifiers_paste_from_buf(ListBase *modifiers, bool replace, struct FCurve *curve); /* ************************************************* */ /* ASSORTED TOOLS */ /* ------------ Animation F-Curves <-> Icons/Names Mapping ------------ */ /* anim_ipo_utils.c */ /* Get icon + name for channel-list displays for F-Curve */ int getname_anim_fcurve(char *name, struct ID *id, struct FCurve *fcu); /* Automatically determine a color for the nth F-Curve */ void getcolor_fcurve_rainbow(int cur, int tot, float out[3]); /* ----------------- NLA Drawing ----------------------- */ /* NOTE: Technically, this is not in the animation module (it's in space_nla) * but these are sometimes needed by various animation apis. */ /* Get color to use for NLA Action channel's background */ void nla_action_get_color(struct AnimData *adt, struct bAction *act, float color[4]); /* ----------------- NLA-Mapping ----------------------- */ /* anim_draw.c */ /* Obtain the AnimData block providing NLA-scaling for the given channel if applicable */ struct AnimData *ANIM_nla_mapping_get(bAnimContext *ac, bAnimListElem *ale); /* Apply/Unapply NLA mapping to all keyframes in the nominated F-Curve */ void ANIM_nla_mapping_apply_fcurve(struct AnimData *adt, struct FCurve *fcu, bool restore, bool only_keys); /* ..... */ /* Perform auto-blending/extend refreshes after some operations */ // NOTE: defined in space_nla/nla_edit.c, not in animation/ void ED_nla_postop_refresh(bAnimContext *ac); /* ------------- Unit Conversion Mappings ------------- */ /* anim_draw.c */ /* flags for conversion mapping */ typedef enum eAnimUnitConv_Flags { /* restore to original internal values */ ANIM_UNITCONV_RESTORE = (1 << 0), /* ignore handles (i.e. only touch main keyframes) */ ANIM_UNITCONV_ONLYKEYS = (1 << 1), /* only touch selected BezTriples */ ANIM_UNITCONV_ONLYSEL = (1 << 2), /* only touch selected vertices */ ANIM_UNITCONV_SELVERTS = (1 << 3), /* ANIM_UNITCONV_SKIPKNOTS = (1 << 4), */ /* UNUSED */ /* Scale FCurve i a way it fits to -1..1 space */ ANIM_UNITCONV_NORMALIZE = (1 << 5), /* Only when normalization is used: use scale factor from previous run, * prevents curves from jumping all over the place when tweaking them. */ ANIM_UNITCONV_NORMALIZE_FREEZE = (1 << 6), } eAnimUnitConv_Flags; /* Normalization flags from Space Graph passing to ANIM_unit_mapping_get_factor */ short ANIM_get_normalization_flags(bAnimContext *ac); /* Get unit conversion factor for given ID + F-Curve */ float ANIM_unit_mapping_get_factor( struct Scene *scene, struct ID *id, struct FCurve *fcu, short flag, float *r_offset); /* ------------- Utility macros ----------------------- */ /* provide access to Keyframe Type info in BezTriple * NOTE: this is so that we can change it from being stored in 'hide' */ #define BEZKEYTYPE(bezt) ((bezt)->hide) /* set/clear/toggle macro * - channel - channel with a 'flag' member that we're setting * - smode - 0=clear, 1=set, 2=invert * - sflag - bitflag to set */ #define ACHANNEL_SET_FLAG(channel, smode, sflag) \ { \ if (smode == ACHANNEL_SETFLAG_INVERT) { \ (channel)->flag ^= (sflag); \ } \ else if (smode == ACHANNEL_SETFLAG_ADD) { \ (channel)->flag |= (sflag); \ } \ else { \ (channel)->flag &= ~(sflag); \ } \ } \ ((void)0) /* set/clear/toggle macro, where the flag is negative * - channel - channel with a 'flag' member that we're setting * - smode - 0=clear, 1=set, 2=invert * - sflag - bitflag to set */ #define ACHANNEL_SET_FLAG_NEG(channel, smode, sflag) \ { \ if (smode == ACHANNEL_SETFLAG_INVERT) { \ (channel)->flag ^= (sflag); \ } \ else if (smode == ACHANNEL_SETFLAG_ADD) { \ (channel)->flag &= ~(sflag); \ } \ else { \ (channel)->flag |= (sflag); \ } \ } \ ((void)0) /* --------- anim_deps.c, animation updates -------- */ void ANIM_id_update(struct Main *bmain, struct ID *id); void ANIM_list_elem_update(struct Main *bmain, struct Scene *scene, bAnimListElem *ale); /* data -> channels syncing */ void ANIM_sync_animchannels_to_data(const struct bContext *C); void ANIM_center_frame(struct bContext *C, int smooth_viewtx); /* ************************************************* */ /* OPERATORS */ /* generic animation channels */ void ED_operatortypes_animchannels(void); void ED_keymap_animchannels(struct wmKeyConfig *keyconf); /* generic time editing */ void ED_operatortypes_anim(void); void ED_keymap_anim(struct wmKeyConfig *keyconf); /* space_graph */ void ED_operatormacros_graph(void); /* space_action */ void ED_operatormacros_action(void); /* ************************************************ */ /* Animation Editor Exports */ /* XXX: Should we be doing these here, or at all? */ /* Action Editor - Action Management */ struct AnimData *ED_actedit_animdata_from_context(struct bContext *C); void ED_animedit_unlink_action(struct bContext *C, struct ID *id, struct AnimData *adt, struct bAction *act, struct ReportList *reports, bool force_delete); /* Drivers Editor - Utility to set up UI correctly */ void ED_drivers_editor_init(struct bContext *C, struct ScrArea *sa); /* ************************************************ */ typedef enum eAnimvizCalcRange { /* Update motion paths at the current frame only. */ ANIMVIZ_CALC_RANGE_CURRENT_FRAME, /* Try to limit updates to a close neighborhood of the current frame. */ ANIMVIZ_CALC_RANGE_CHANGED, /* Update an entire range of the motion paths. */ ANIMVIZ_CALC_RANGE_FULL, } eAnimvizCalcRange; struct Depsgraph *animviz_depsgraph_build(struct Main *bmain, struct Scene *scene, struct ViewLayer *view_layer, struct ListBase *targets); void animviz_calc_motionpaths(struct Depsgraph *depsgraph, struct Main *bmain, struct Scene *scene, ListBase *targets, eAnimvizCalcRange range, bool restore); void animviz_get_object_motionpaths(struct Object *ob, ListBase *targets); #ifdef __cplusplus } #endif #endif /* __ED_ANIM_API_H__ */
36.920182
99
0.664103
[ "mesh", "object" ]
7f4df8cbdf0f0c0a7af88fc722c2c6bcb95eef57
15,697
c
C
third_party/gst-plugins-base/tests/check/gst/typefindfunctions.c
isabella232/aistreams
209f4385425405676a581a749bb915e257dbc1c1
[ "Apache-2.0" ]
6
2020-09-22T18:07:15.000Z
2021-10-21T01:34:04.000Z
third_party/gst-plugins-base/tests/check/gst/typefindfunctions.c
isabella232/aistreams
209f4385425405676a581a749bb915e257dbc1c1
[ "Apache-2.0" ]
2
2020-11-10T13:17:39.000Z
2022-03-30T11:22:14.000Z
third_party/gst-plugins-base/tests/check/gst/typefindfunctions.c
isabella232/aistreams
209f4385425405676a581a749bb915e257dbc1c1
[ "Apache-2.0" ]
3
2020-09-26T08:40:35.000Z
2021-10-21T01:33:56.000Z
/* GStreamer unit tests for the -base typefind functions * * Copyright (C) 2007 Tim-Philipp Müller <tim centricular net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <gst/check/gstcheck.h> #include <gst/base/gsttypefindhelper.h> static GstCaps * typefind_data (const guint8 * data, gsize data_size, GstTypeFindProbability * prob) { GstBuffer *buf; GstCaps *caps; GST_MEMDUMP ("typefind data", data, data_size); buf = gst_buffer_new (); gst_buffer_append_memory (buf, gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY, (guint8 *) data, data_size, 0, data_size, NULL, NULL)); GST_BUFFER_OFFSET (buf) = 0; caps = gst_type_find_helper_for_buffer (NULL, buf, prob); GST_INFO ("caps: %" GST_PTR_FORMAT ", probability=%u", caps, *prob); gst_buffer_unref (buf); return caps; } GST_START_TEST (test_quicktime_mpeg4video) { /* quicktime redirect file which starts with what could also be interpreted * as an MPEG-4 video object layer start code */ const guint8 qt_redirect_396042[] = { 0x00, 0x00, 0x01, 0x22, 0x6d, 0x6f, 0x6f, 0x76, 0x00, 0x00, 0x01, 0x1a, 0x72, 0x6d, 0x72, 0x61, 0x00, 0x00, 0x00, 0x86, 0x72, 0x6d, 0x64, 0x61, 0x00, 0x00, 0x00, 0x54, 0x72, 0x64, 0x72, 0x66, 0x00, 0x00, 0x00, 0x00, 0x75, 0x72, 0x6c, 0x20, 0x00, 0x00, 0x00, 0x40, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x2e, 0x71, 0x74, 0x76, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x2f, 0x6a, 0x61, 0x6e, 0x2f, 0x6a, 0x34, 0x37, 0x64, 0x35, 0x32, 0x6f, 0x6f, 0x2f, 0x71, 0x74, 0x37, 0x72, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x2e, 0x6d, 0x6f, 0x76, 0x00, 0x00, 0x00, 0x00, 0x10, 0x72, 0x6d, 0x64, 0x72, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0xf0, 0x00, 0x00, 0x00, 0x1a, 0x72, 0x6d, 0x76, 0x63, 0x00, 0x00, 0x00, 0x00, 0x71, 0x74, 0x69, 0x6d, 0x06, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8c, 0x72, 0x6d, 0x64, 0x61, 0x00, 0x00, 0x00, 0x5a, 0x72, 0x64, 0x72, 0x66, 0x00, 0x00, 0x00, 0x00, 0x75, 0x72, 0x6c, 0x20, 0x00, 0x00, 0x00, 0x46, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x2e, 0x71, 0x74, 0x76, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x73, 0x2f, 0x6a, 0x61, 0x6e, 0x2f, 0x6a, 0x34, 0x37, 0x64, 0x35, 0x32, 0x6f, 0x6f, 0x2f, 0x38, 0x38, 0x34, 0x38, 0x31, 0x32, 0x35, 0x5f, 0x32, 0x5f, 0x33, 0x35, 0x30, 0x5f, 0x72, 0x65, 0x66, 0x2e, 0x6d, 0x6f, 0x76, 0x00, 0x00, 0x00, 0x00, 0x10, 0x72, 0x6d, 0x64, 0x72, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0xf0, 0x00, 0x00, 0x00, 0x1a, 0x72, 0x6d, 0x76, 0x63, 0x00, 0x00, 0x00, 0x00, 0x71, 0x74, 0x69, 0x6d, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; GstTypeFindProbability prob; const gchar *type; GstBuffer *buf; GstCaps *caps = NULL; buf = gst_buffer_new (); gst_buffer_append_memory (buf, gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY, (gpointer) qt_redirect_396042, sizeof (qt_redirect_396042), 0, sizeof (qt_redirect_396042), NULL, NULL)); GST_BUFFER_OFFSET (buf) = 0; caps = gst_type_find_helper_for_buffer (NULL, buf, &prob); fail_unless (caps != NULL); GST_LOG ("Found type: %" GST_PTR_FORMAT, caps); type = gst_structure_get_name (gst_caps_get_structure (caps, 0)); fail_unless_equals_string (type, "video/quicktime"); fail_unless (prob > GST_TYPE_FIND_MINIMUM && prob <= GST_TYPE_FIND_MAXIMUM); gst_buffer_unref (buf); gst_caps_unref (caps); } GST_END_TEST; GST_START_TEST (test_broken_flac_in_ogg) { const guint8 flac_id_packet[4] = { 'f', 'L', 'a', 'C' }; GstTypeFindProbability prob; const gchar *type; GstBuffer *buf; GstCaps *caps = NULL; buf = gst_buffer_new (); gst_buffer_append_memory (buf, gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY, (gpointer) flac_id_packet, sizeof (flac_id_packet), 0, sizeof (flac_id_packet), NULL, NULL)); GST_BUFFER_OFFSET (buf) = 0; caps = gst_type_find_helper_for_buffer (NULL, buf, &prob); fail_unless (caps != NULL); GST_LOG ("Found type: %" GST_PTR_FORMAT, caps); type = gst_structure_get_name (gst_caps_get_structure (caps, 0)); fail_unless_equals_string (type, "audio/x-flac"); fail_unless (prob > GST_TYPE_FIND_MINIMUM && prob <= GST_TYPE_FIND_MAXIMUM); gst_buffer_unref (buf); gst_caps_unref (caps); } GST_END_TEST; static GstCaps * typefind_test_file (const gchar * filename) { GstBuffer *buf; GError *err = NULL; GstCaps *caps = NULL; gchar *path, *data = NULL; gsize data_len; path = g_build_filename (GST_TEST_FILES_PATH, filename, NULL); GST_LOG ("reading file '%s'", path); if (!g_file_get_contents (path, &data, &data_len, &err)) { g_error ("error loading test file: %s", err->message); g_clear_error (&err); } buf = gst_buffer_new (); gst_buffer_append_memory (buf, gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY, (gpointer) data, data_len, 0, data_len, NULL, NULL)); GST_BUFFER_OFFSET (buf) = 0; caps = gst_type_find_helper_for_buffer (NULL, buf, NULL); fail_unless (caps != NULL); GST_LOG ("Found type: %" GST_PTR_FORMAT, caps); gst_buffer_unref (buf); g_free (data); g_free (path); return caps; } GST_START_TEST (test_jpeg_not_ac3) { const gchar *type; GstCaps *caps = NULL; caps = typefind_test_file ("partialframe.mjpeg"); type = gst_structure_get_name (gst_caps_get_structure (caps, 0)); fail_unless_equals_string (type, "image/jpeg"); gst_caps_unref (caps); } GST_END_TEST; GST_START_TEST (test_mpegts) { GstStructure *s; gboolean systemstream = FALSE; GstCaps *caps = NULL; gint packetsize = -1; caps = typefind_test_file ("623663.mts"); s = gst_caps_get_structure (caps, 0); fail_unless (gst_structure_has_name (s, "video/mpegts")); fail_unless (gst_structure_has_field (s, "systemstream")); fail_unless (gst_structure_get_boolean (s, "systemstream", &systemstream)); fail_unless_equals_int (systemstream, TRUE); fail_unless (gst_structure_has_field (s, "packetsize")); fail_unless (gst_structure_get_int (s, "packetsize", &packetsize)); fail_unless_equals_int (packetsize, 192); gst_caps_unref (caps); } GST_END_TEST; struct ac3_frmsize { unsigned frmsizecod; unsigned frmsize; }; static void make_ac3_packet (guint8 * data, guint bytesize, guint bsid) { /* Actually not a fully valid packet; if the typefinder starts to * check e.g. the CRCs, this test needs to be improved as well. */ const guint8 ac3_header[] = { 0x0b, 0x77, /* syncword */ 0x00, 0x00, /* crc1 */ 0x00, /* fscod 0xc0, frmsizecod 0x3f */ 0x00 /* bsid 0xf8, bsmod 0x07 */ }; const struct ac3_frmsize frmsize[] = { {17, 256}, {26, 640} /* small subset of supported sizes */ }; guint wordsize = bytesize >> 1, frmsizecod = 0; int i; fail_unless ((bytesize & 0x01) == 0); fail_unless (bytesize >= sizeof (ac3_header)); for (i = 0; i < G_N_ELEMENTS (frmsize); i++) { if (frmsize[i].frmsize == wordsize) { frmsizecod = frmsize[i].frmsizecod; break; } } fail_unless (frmsizecod); memcpy (data, ac3_header, sizeof (ac3_header)); data[4] = (data[4] & ~0x3f) | (frmsizecod & 0x3f); data[5] = (bsid & 0x1f) << 3; memset (data + 6, 0, bytesize - 6); } GST_START_TEST (test_ac3) { GstTypeFindProbability prob; const gchar *type; GstBuffer *buf; GstCaps *caps = NULL; guint bsid; for (bsid = 0; bsid < 32; bsid++) { GstMapInfo map; buf = gst_buffer_new_and_alloc ((256 + 640) * 2); gst_buffer_map (buf, &map, GST_MAP_WRITE); make_ac3_packet (map.data, 256 * 2, bsid); make_ac3_packet (map.data + 256 * 2, 640 * 2, bsid); gst_buffer_unmap (buf, &map); caps = gst_type_find_helper_for_buffer (NULL, buf, &prob); if (bsid <= 8) { fail_unless (caps != NULL); GST_LOG ("Found type for BSID %u: %" GST_PTR_FORMAT, bsid, caps); type = gst_structure_get_name (gst_caps_get_structure (caps, 0)); fail_unless_equals_string (type, "audio/x-ac3"); fail_unless (prob > GST_TYPE_FIND_MINIMUM && prob <= GST_TYPE_FIND_MAXIMUM); gst_caps_unref (caps); } else { fail_unless (caps == NULL); } gst_buffer_unref (buf); } } GST_END_TEST; static void make_eac3_packet (guint8 * data, guint bytesize, guint bsid) { /* Actually not a fully valid packet; if the typefinder starts to * check e.g. the CRCs, this test needs to be improved as well. */ const guint8 eac3_header[] = { 0x0b, 0x77, /* syncword */ 0x00, /* strmtyp 0xc0, substreamid 0x38, * frmsize 0x07 (3 high bits) */ 0x00, /* frmsize (low bits -> 11 total) */ 0x00, /* fscod 0xc0, fscod2/numblocks 0x30, * acmod 0x0e, lfeon 0x01 */ 0x00 /* bsid 0xf8, dialnorm 0x07 (3 high bits) */ }; guint wordsize = bytesize >> 1; fail_unless ((bytesize & 0x01) == 0); fail_unless (bytesize >= sizeof (eac3_header)); memcpy (data, eac3_header, sizeof (eac3_header)); data[2] = (data[2] & ~0x07) | ((((wordsize - 1) & 0x700) >> 8) & 0xff); data[3] = (wordsize - 1) & 0xff; data[5] = (bsid & 0x1f) << 3; memset (data + 6, 0, bytesize - 6); } GST_START_TEST (test_eac3) { GstTypeFindProbability prob; const gchar *type; GstBuffer *buf; GstCaps *caps = NULL; guint bsid; for (bsid = 0; bsid <= 32; bsid++) { GstMapInfo map; buf = gst_buffer_new_and_alloc (558 + 384); gst_buffer_map (buf, &map, GST_MAP_WRITE); make_eac3_packet (map.data, 558, bsid); make_eac3_packet (map.data + 558, 384, bsid); gst_buffer_unmap (buf, &map); caps = gst_type_find_helper_for_buffer (NULL, buf, &prob); if (bsid > 10 && bsid <= 16) { /* Only BSIs 11..16 are valid for Annex E */ fail_unless (caps != NULL); GST_LOG ("Found type for BSID %u: %" GST_PTR_FORMAT, bsid, caps); type = gst_structure_get_name (gst_caps_get_structure (caps, 0)); fail_unless_equals_string (type, "audio/x-eac3"); fail_unless (prob > GST_TYPE_FIND_MINIMUM && prob <= GST_TYPE_FIND_MAXIMUM); gst_caps_unref (caps); } else { /* Invalid E-AC-3 BSID, must not be detected as anything: */ fail_unless (caps == NULL); } gst_buffer_unref (buf); } } GST_END_TEST; #define TEST_RANDOM_DATA_SIZE (4*1024) /* typefind random data, to make sure all typefinders are called */ GST_START_TEST (test_random_data) { GstTypeFindProbability prob; const gchar *seed_env; GstBuffer *buf; GstCaps *caps; guint32 seed; guint8 *data; gint i; seed_env = g_getenv ("GST_TYPEFIND_TEST_SEED"); if (seed_env != NULL) seed = atoi (seed_env); else seed = (guint32) time (NULL); g_random_set_seed (seed); data = g_malloc (TEST_RANDOM_DATA_SIZE); for (i = 0; i < TEST_RANDOM_DATA_SIZE; ++i) data[i] = g_random_int () & 0xff; buf = gst_buffer_new (); gst_buffer_append_memory (buf, gst_memory_new_wrapped (GST_MEMORY_FLAG_READONLY, data, TEST_RANDOM_DATA_SIZE, 0, TEST_RANDOM_DATA_SIZE, NULL, NULL)); GST_BUFFER_OFFSET (buf) = 0; caps = gst_type_find_helper_for_buffer (NULL, buf, &prob); GST_INFO ("caps: %" GST_PTR_FORMAT ", probability=%u", caps, prob); /* for now we just print an error log message */ if (caps != NULL /* && prob >= GST_TYPE_FIND_LIKELY */ ) { GST_ERROR ("typefinder thinks random data is %" GST_PTR_FORMAT ", with a " "probability of %u (seed was %u)", caps, prob, seed); gst_caps_unref (caps); } gst_buffer_unref (buf); g_free (data); } GST_END_TEST; GST_START_TEST (test_hls_m3u8) { const gchar *type; GstCaps *caps = NULL; caps = typefind_test_file ("hls.m3u8"); type = gst_structure_get_name (gst_caps_get_structure (caps, 0)); fail_unless_equals_string (type, "application/x-hls"); gst_caps_unref (caps); } GST_END_TEST; static const gchar MANIFEST[] = "<?xml version=\"1.0\" encoding=\"utf-16\"?>\n" "<!--Created with Expression Encoder version 2.1.1216.0-->\n" "<SmoothStreamingMedia\n" " MajorVersion=\"1\"\n" " MinorVersion=\"0\"\n" " Duration=\"5965419999\">\n" " <StreamIndex\n" " Type=\"video\"\n" " Subtype=\"WVC1\"\n" " Chunks=\"299\"\n" " Url=\"QualityLevels({bitrate})/Fragments(video={start time})\">\n" " <QualityLevel\n" " Bitrate=\"2750000\"\n" " FourCC=\"WVC1\"\n" " Width=\"1280\"\n" " Height=\"720\"\n"; static guint8 * generate_utf16 (guint off_lo, guint off_hi) { guint8 *utf16; gsize len, i; len = strlen (MANIFEST); /* BOM + UTF-16 string */ utf16 = g_malloc (2 + len * 2); utf16[off_lo] = 0xff; utf16[off_hi] = 0xfe; for (i = 0; i < len; ++i) { utf16[2 + (2 * i) + off_lo] = MANIFEST[i]; utf16[2 + (2 * i) + off_hi] = 0x00; } return utf16; } /* Test that we can typefind UTF16-LE and UTF16-BE variants * of smooth streaming manifests (even without iconv) */ GST_START_TEST (test_manifest_typefinding) { GstTypeFindProbability prob; const gchar *media_type; GstCaps *caps; guint8 *utf16; utf16 = generate_utf16 (0, 1); prob = 0; caps = typefind_data (utf16, 2 + strlen (MANIFEST) * 2, &prob); fail_unless (caps != NULL); media_type = gst_structure_get_name (gst_caps_get_structure (caps, 0)); fail_unless_equals_string (media_type, "application/vnd.ms-sstr+xml"); fail_unless_equals_int (prob, GST_TYPE_FIND_MAXIMUM); gst_caps_unref (caps); g_free (utf16); utf16 = generate_utf16 (1, 0); prob = 0; caps = typefind_data (utf16, 2 + strlen (MANIFEST) * 2, &prob); fail_unless (caps != NULL); media_type = gst_structure_get_name (gst_caps_get_structure (caps, 0)); fail_unless_equals_string (media_type, "application/vnd.ms-sstr+xml"); fail_unless_equals_int (prob, GST_TYPE_FIND_MAXIMUM); gst_caps_unref (caps); g_free (utf16); } GST_END_TEST; static Suite * typefindfunctions_suite (void) { Suite *s = suite_create ("typefindfunctions"); TCase *tc_chain = tcase_create ("general"); suite_add_tcase (s, tc_chain); tcase_add_test (tc_chain, test_quicktime_mpeg4video); tcase_add_test (tc_chain, test_broken_flac_in_ogg); tcase_add_test (tc_chain, test_jpeg_not_ac3); tcase_add_test (tc_chain, test_mpegts); tcase_add_test (tc_chain, test_ac3); tcase_add_test (tc_chain, test_eac3); tcase_add_test (tc_chain, test_random_data); tcase_add_test (tc_chain, test_hls_m3u8); tcase_add_test (tc_chain, test_manifest_typefinding); return s; } GST_CHECK_MAIN (typefindfunctions);
31.268924
80
0.662802
[ "object" ]
7f4e6284ef3d7e573afd841410487e876932e46d
2,699
h
C
ble-mesh-model/sources/models/schedulersr/mmdl_scheduler_sr_main.h
lonesomebyte537/cordio
c0db6dc27d1931feafa7f8db018cd9095416f978
[ "Apache-2.0" ]
1
2022-02-15T03:51:14.000Z
2022-02-15T03:51:14.000Z
ble-mesh-model/sources/models/schedulersr/mmdl_scheduler_sr_main.h
lonesomebyte537/cordio
c0db6dc27d1931feafa7f8db018cd9095416f978
[ "Apache-2.0" ]
null
null
null
ble-mesh-model/sources/models/schedulersr/mmdl_scheduler_sr_main.h
lonesomebyte537/cordio
c0db6dc27d1931feafa7f8db018cd9095416f978
[ "Apache-2.0" ]
2
2022-01-21T08:00:37.000Z
2022-02-15T03:51:23.000Z
/*************************************************************************************************/ /*! * \file mmdl_scheduler_sr_main.h * * \brief Internal interface of the Scheduler Server model. * * Copyright (c) 2010-2018 Arm Ltd. * * Copyright (c) 2019 Packetcraft, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /*************************************************************************************************/ #ifndef MMDL_SCHEDULER_SR_MAIN_H #define MMDL_SCHEDULER_SR_MAIN_H #ifdef __cplusplus extern "C" { #endif /************************************************************************************************** Macros **************************************************************************************************/ /*! Initializer of a message info for the specified model ID */ #define MSG_INFO(modelId) {{(meshSigModelId_t)modelId }, {{0,0,0}},\ 0xFF, NULL, MESH_ADDR_TYPE_UNASSIGNED, 0xFF, 0xFF} /*! Initializer of a publish message info for the specified model ID */ #define PUB_MSG_INFO(modelId) {{{0,0,0}}, 0xFF , {(meshSigModelId_t)modelId}} /************************************************************************************************** Function Declarations **************************************************************************************************/ void mmdlSchedulerSrHandleGet(const meshModelMsgRecvEvt_t *pMsg); void mmdlSchedulerSrHandleActionGet(const meshModelMsgRecvEvt_t *pMsg); void mmdlSchedulerSrGetDesc(meshElementId_t elementId, mmdlSchedulerSrDesc_t **ppOutDesc); void mmdlSchedulerSrScheduleEvent(meshElementId_t elementId, uint8_t index, mmdlSchedulerSrRegisterEntry_t *pEntry); void mmdlSchedulerSrSendActionStatus(meshElementId_t elementId, meshAddress_t dstAddr, uint16_t appKeyIndex, bool_t recvOnUnicast, uint8_t index); void mmdlSchedulerUnpackActionParams(uint8_t *pMsgParams, uint8_t *pOutIndex, mmdlSchedulerRegisterEntry_t *pOutEntry); #ifdef __cplusplus } #endif #endif /* MMDL_SCHEDULER_SR_MAIN_H */
39.691176
99
0.552056
[ "model" ]
7f52929f50419c007e7417554fe1073ebdfb9c43
77,105
c
C
mono/metadata/domain.c
jogibear9988/mono
b3b28212f6a26cc906c8d4737966b44f281856b5
[ "Apache-2.0" ]
3
2015-01-14T01:19:53.000Z
2018-05-22T00:48:45.000Z
mono/metadata/domain.c
matthid/mono
79a3a432a705b3a4e397c844cbc42604a9b71ea5
[ "Apache-2.0" ]
null
null
null
mono/metadata/domain.c
matthid/mono
79a3a432a705b3a4e397c844cbc42604a9b71ea5
[ "Apache-2.0" ]
null
null
null
/* * domain.c: MonoDomain functions * * Author: * Dietmar Maurer (dietmar@ximian.com) * Patrik Torstensson * * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com) * Copyright 2004-2009 Novell, Inc (http://www.novell.com) * Copyright 2011-2012 Xamarin, Inc (http://www.xamarin.com) */ #include <config.h> #include <glib.h> #include <string.h> #include <sys/stat.h> #include <mono/metadata/gc-internal.h> #include <mono/utils/atomic.h> #include <mono/utils/mono-compiler.h> #include <mono/utils/mono-logger-internal.h> #include <mono/utils/mono-membar.h> #include <mono/utils/mono-counters.h> #include <mono/utils/hazard-pointer.h> #include <mono/utils/mono-tls.h> #include <mono/utils/mono-mmap.h> #include <mono/metadata/object.h> #include <mono/metadata/object-internals.h> #include <mono/metadata/domain-internals.h> #include <mono/metadata/class-internals.h> #include <mono/metadata/assembly.h> #include <mono/metadata/exception.h> #include <mono/metadata/metadata-internals.h> #include <mono/metadata/gc-internal.h> #include <mono/metadata/appdomain.h> #include <mono/metadata/mono-debug-debugger.h> #include <mono/metadata/mono-config.h> #include <mono/metadata/threads-types.h> #include <mono/metadata/runtime.h> #include <metadata/threads.h> #include <metadata/profiler-private.h> #include <mono/metadata/coree.h> /* #define DEBUG_DOMAIN_UNLOAD */ /* we need to use both the Tls* functions and __thread because * some archs may generate faster jit code with one meachanism * or the other (we used to do it because tls slots were GC-tracked, * but we can't depend on this). */ static MonoNativeTlsKey appdomain_thread_id; #ifdef MONO_HAVE_FAST_TLS MONO_FAST_TLS_DECLARE(tls_appdomain); #define GET_APPDOMAIN() ((MonoDomain*)MONO_FAST_TLS_GET(tls_appdomain)) #define SET_APPDOMAIN(x) do { \ MONO_FAST_TLS_SET (tls_appdomain,x); \ mono_native_tls_set_value (appdomain_thread_id, x); \ mono_gc_set_current_thread_appdomain (x); \ } while (FALSE) #else /* !MONO_HAVE_FAST_TLS */ #define GET_APPDOMAIN() ((MonoDomain *)mono_native_tls_get_value (appdomain_thread_id)) #define SET_APPDOMAIN(x) do { \ mono_native_tls_set_value (appdomain_thread_id, x); \ mono_gc_set_current_thread_appdomain (x); \ } while (FALSE) #endif #define GET_APPCONTEXT() (mono_thread_internal_current ()->current_appcontext) #define SET_APPCONTEXT(x) MONO_OBJECT_SETREF (mono_thread_internal_current (), current_appcontext, (x)) static guint16 appdomain_list_size = 0; static guint16 appdomain_next = 0; static MonoDomain **appdomains_list = NULL; static MonoImage *exe_image; gboolean mono_dont_free_domains; #define mono_appdomains_lock() EnterCriticalSection (&appdomains_mutex) #define mono_appdomains_unlock() LeaveCriticalSection (&appdomains_mutex) static CRITICAL_SECTION appdomains_mutex; static MonoDomain *mono_root_domain = NULL; /* some statistics */ static int max_domain_code_size = 0; static int max_domain_code_alloc = 0; static int total_domain_code_alloc = 0; /* AppConfigInfo: Information about runtime versions supported by an * aplication. */ typedef struct { GSList *supported_runtimes; char *required_runtime; int configuration_count; int startup_count; } AppConfigInfo; static const MonoRuntimeInfo *current_runtime = NULL; static MonoJitInfoFindInAot jit_info_find_in_aot_func = NULL; /* This is the list of runtime versions supported by this JIT. */ static const MonoRuntimeInfo supported_runtimes[] = { {"v2.0.50215","2.0", { {2,0,0,0}, { 8,0,0,0}, {3,5,0,0}, {3,0,0,0} } }, {"v2.0.50727","2.0", { {2,0,0,0}, { 8,0,0,0}, {3,5,0,0}, {3,0,0,0} } }, {"v4.0.30319","4.5", { {4,0,0,0}, {10,0,0,0}, {4,0,0,0}, {4,0,0,0} } }, {"v4.0.30128","4.0", { {4,0,0,0}, {10,0,0,0}, {4,0,0,0}, {4,0,0,0} } }, {"v4.0.20506","4.0", { {4,0,0,0}, {10,0,0,0}, {4,0,0,0}, {4,0,0,0} } }, {"moonlight", "2.1", { {2,0,5,0}, { 9,0,0,0}, {3,5,0,0}, {3,0,0,0} } }, }; /* The stable runtime version */ #define DEFAULT_RUNTIME_VERSION "v2.0.50727" /* Callbacks installed by the JIT */ static MonoCreateDomainFunc create_domain_hook; static MonoFreeDomainFunc free_domain_hook; /* This is intentionally not in the header file, so people don't misuse it. */ extern void _mono_debug_init_corlib (MonoDomain *domain); static void get_runtimes_from_exe (const char *exe_file, MonoImage **exe_image, const MonoRuntimeInfo** runtimes); static const MonoRuntimeInfo* get_runtime_by_version (const char *version); MonoNativeTlsKey mono_domain_get_tls_key (void) { return appdomain_thread_id; } gint32 mono_domain_get_tls_offset (void) { int offset = -1; MONO_THREAD_VAR_OFFSET (tls_appdomain, offset); /* __asm ("jmp 1f; .section writetext, \"awx\"; 1: movl $tls_appdomain@ntpoff, %0; jmp 2f; .previous; 2:" : "=r" (offset));*/ return offset; } #define JIT_INFO_TABLE_FILL_RATIO_NOM 3 #define JIT_INFO_TABLE_FILL_RATIO_DENOM 4 #define JIT_INFO_TABLE_FILLED_NUM_ELEMENTS (MONO_JIT_INFO_TABLE_CHUNK_SIZE * JIT_INFO_TABLE_FILL_RATIO_NOM / JIT_INFO_TABLE_FILL_RATIO_DENOM) #define JIT_INFO_TABLE_LOW_WATERMARK(n) ((n) / 2) #define JIT_INFO_TABLE_HIGH_WATERMARK(n) ((n) * 5 / 6) #define JIT_INFO_TOMBSTONE_MARKER ((MonoMethod*)NULL) #define IS_JIT_INFO_TOMBSTONE(ji) ((ji)->d.method == JIT_INFO_TOMBSTONE_MARKER) #define JIT_INFO_TABLE_HAZARD_INDEX 0 #define JIT_INFO_HAZARD_INDEX 1 static int jit_info_table_num_elements (MonoJitInfoTable *table) { int i; int num_elements = 0; for (i = 0; i < table->num_chunks; ++i) { MonoJitInfoTableChunk *chunk = table->chunks [i]; int chunk_num_elements = chunk->num_elements; int j; for (j = 0; j < chunk_num_elements; ++j) { if (!IS_JIT_INFO_TOMBSTONE (chunk->data [j])) ++num_elements; } } return num_elements; } static MonoJitInfoTableChunk* jit_info_table_new_chunk (void) { MonoJitInfoTableChunk *chunk = g_new0 (MonoJitInfoTableChunk, 1); chunk->refcount = 1; return chunk; } static MonoJitInfoTable * jit_info_table_new (MonoDomain *domain) { MonoJitInfoTable *table = g_malloc0 (MONO_SIZEOF_JIT_INFO_TABLE + sizeof (MonoJitInfoTableChunk*)); table->domain = domain; table->num_chunks = 1; table->chunks [0] = jit_info_table_new_chunk (); return table; } static void jit_info_table_free (MonoJitInfoTable *table) { int i; int num_chunks = table->num_chunks; MonoDomain *domain = table->domain; mono_domain_lock (domain); table->domain->num_jit_info_tables--; if (table->domain->num_jit_info_tables <= 1) { GSList *list; for (list = table->domain->jit_info_free_queue; list; list = list->next) g_free (list->data); g_slist_free (table->domain->jit_info_free_queue); table->domain->jit_info_free_queue = NULL; } /* At this point we assume that there are no other threads still accessing the table, so we don't have to worry about hazardous pointers. */ for (i = 0; i < num_chunks; ++i) { MonoJitInfoTableChunk *chunk = table->chunks [i]; int num_elements; int j; if (--chunk->refcount > 0) continue; num_elements = chunk->num_elements; for (j = 0; j < num_elements; ++j) { MonoJitInfo *ji = chunk->data [j]; if (IS_JIT_INFO_TOMBSTONE (ji)) g_free (ji); } g_free (chunk); } mono_domain_unlock (domain); g_free (table); } /* The jit_info_table is sorted in ascending order by the end * addresses of the compiled methods. The reason why we have to do * this is that once we introduce tombstones, it becomes possible for * code ranges to overlap, and if we sort by code start and insert at * the back of the table, we cannot guarantee that we won't overlook * an entry. * * There are actually two possible ways to do the sorting and * inserting which work with our lock-free mechanism: * * 1. Sort by start address and insert at the front. When looking for * an entry, find the last one with a start address lower than the one * you're looking for, then work your way to the front of the table. * * 2. Sort by end address and insert at the back. When looking for an * entry, find the first one with an end address higher than the one * you're looking for, then work your way to the end of the table. * * We chose the latter out of convenience. */ static int jit_info_table_index (MonoJitInfoTable *table, gint8 *addr) { int left = 0, right = table->num_chunks; g_assert (left < right); do { int pos = (left + right) / 2; MonoJitInfoTableChunk *chunk = table->chunks [pos]; if (addr < chunk->last_code_end) right = pos; else left = pos + 1; } while (left < right); g_assert (left == right); if (left >= table->num_chunks) return table->num_chunks - 1; return left; } static int jit_info_table_chunk_index (MonoJitInfoTableChunk *chunk, MonoThreadHazardPointers *hp, gint8 *addr) { int left = 0, right = chunk->num_elements; while (left < right) { int pos = (left + right) / 2; MonoJitInfo *ji = get_hazardous_pointer((gpointer volatile*)&chunk->data [pos], hp, JIT_INFO_HAZARD_INDEX); gint8 *code_end = (gint8*)ji->code_start + ji->code_size; if (addr < code_end) right = pos; else left = pos + 1; } g_assert (left == right); return left; } static MonoJitInfo* jit_info_table_find (MonoJitInfoTable *table, MonoThreadHazardPointers *hp, gint8 *addr) { MonoJitInfo *ji; int chunk_pos, pos; chunk_pos = jit_info_table_index (table, (gint8*)addr); g_assert (chunk_pos < table->num_chunks); pos = jit_info_table_chunk_index (table->chunks [chunk_pos], hp, (gint8*)addr); /* We now have a position that's very close to that of the first element whose end address is higher than the one we're looking for. If we don't have the exact position, then we have a position below that one, so we'll just search upward until we find our element. */ do { MonoJitInfoTableChunk *chunk = table->chunks [chunk_pos]; while (pos < chunk->num_elements) { ji = get_hazardous_pointer ((gpointer volatile*)&chunk->data [pos], hp, JIT_INFO_HAZARD_INDEX); ++pos; if (IS_JIT_INFO_TOMBSTONE (ji)) { mono_hazard_pointer_clear (hp, JIT_INFO_HAZARD_INDEX); continue; } if ((gint8*)addr >= (gint8*)ji->code_start && (gint8*)addr < (gint8*)ji->code_start + ji->code_size) { mono_hazard_pointer_clear (hp, JIT_INFO_HAZARD_INDEX); return ji; } /* If we find a non-tombstone element which is already beyond what we're looking for, we have to end the search. */ if ((gint8*)addr < (gint8*)ji->code_start) goto not_found; } ++chunk_pos; pos = 0; } while (chunk_pos < table->num_chunks); not_found: if (hp) mono_hazard_pointer_clear (hp, JIT_INFO_HAZARD_INDEX); return NULL; } /* * mono_jit_info_table_find_internal: * * If TRY_AOT is FALSE, avoid loading information for missing methods from AOT images, which is currently not async safe. * In this case, only those AOT methods will be found whose jit info is already loaded. * ASYNC SAFETY: When called in an async context (mono_thread_info_is_async_context ()), this is async safe. * In this case, the returned MonoJitInfo might not have metadata information, in particular, * mono_jit_info_get_method () could fail. */ MonoJitInfo* mono_jit_info_table_find_internal (MonoDomain *domain, char *addr, gboolean try_aot) { MonoJitInfoTable *table; MonoJitInfo *ji, *module_ji; MonoThreadHazardPointers *hp = mono_hazard_pointer_get (); ++mono_stats.jit_info_table_lookup_count; /* First we have to get the domain's jit_info_table. This is complicated by the fact that a writer might substitute a new table and free the old one. What the writer guarantees us is that it looks at the hazard pointers after it has changed the jit_info_table pointer. So, if we guard the table by a hazard pointer and make sure that the pointer is still there after we've made it hazardous, we don't have to worry about the writer freeing the table. */ table = get_hazardous_pointer ((gpointer volatile*)&domain->jit_info_table, hp, JIT_INFO_TABLE_HAZARD_INDEX); ji = jit_info_table_find (table, hp, (gint8*)addr); if (hp) mono_hazard_pointer_clear (hp, JIT_INFO_TABLE_HAZARD_INDEX); if (ji) return ji; /* Maybe its an AOT module */ if (try_aot && mono_root_domain && mono_root_domain->aot_modules) { table = get_hazardous_pointer ((gpointer volatile*)&mono_root_domain->aot_modules, hp, JIT_INFO_TABLE_HAZARD_INDEX); module_ji = jit_info_table_find (table, hp, (gint8*)addr); if (module_ji) ji = jit_info_find_in_aot_func (domain, module_ji->d.image, addr); if (hp) mono_hazard_pointer_clear (hp, JIT_INFO_TABLE_HAZARD_INDEX); } return ji; } MonoJitInfo* mono_jit_info_table_find (MonoDomain *domain, char *addr) { return mono_jit_info_table_find_internal (domain, addr, TRUE); } static G_GNUC_UNUSED void jit_info_table_check (MonoJitInfoTable *table) { int i; for (i = 0; i < table->num_chunks; ++i) { MonoJitInfoTableChunk *chunk = table->chunks [i]; int j; g_assert (chunk->refcount > 0 /* && chunk->refcount <= 8 */); if (chunk->refcount > 10) printf("warning: chunk refcount is %d\n", chunk->refcount); g_assert (chunk->num_elements <= MONO_JIT_INFO_TABLE_CHUNK_SIZE); for (j = 0; j < chunk->num_elements; ++j) { MonoJitInfo *this = chunk->data [j]; MonoJitInfo *next; g_assert ((gint8*)this->code_start + this->code_size <= chunk->last_code_end); if (j < chunk->num_elements - 1) next = chunk->data [j + 1]; else if (i < table->num_chunks - 1) { int k; for (k = i + 1; k < table->num_chunks; ++k) if (table->chunks [k]->num_elements > 0) break; if (k >= table->num_chunks) return; g_assert (table->chunks [k]->num_elements > 0); next = table->chunks [k]->data [0]; } else return; g_assert ((gint8*)this->code_start + this->code_size <= (gint8*)next->code_start + next->code_size); } } } static MonoJitInfoTable* jit_info_table_realloc (MonoJitInfoTable *old) { int i; int num_elements = jit_info_table_num_elements (old); int required_size; int num_chunks; int new_chunk, new_element; MonoJitInfoTable *new; /* number of needed places for elements needed */ required_size = (int)((long)num_elements * JIT_INFO_TABLE_FILL_RATIO_DENOM / JIT_INFO_TABLE_FILL_RATIO_NOM); num_chunks = (required_size + MONO_JIT_INFO_TABLE_CHUNK_SIZE - 1) / MONO_JIT_INFO_TABLE_CHUNK_SIZE; if (num_chunks == 0) { g_assert (num_elements == 0); return jit_info_table_new (old->domain); } g_assert (num_chunks > 0); new = g_malloc (MONO_SIZEOF_JIT_INFO_TABLE + sizeof (MonoJitInfoTableChunk*) * num_chunks); new->domain = old->domain; new->num_chunks = num_chunks; for (i = 0; i < num_chunks; ++i) new->chunks [i] = jit_info_table_new_chunk (); new_chunk = 0; new_element = 0; for (i = 0; i < old->num_chunks; ++i) { MonoJitInfoTableChunk *chunk = old->chunks [i]; int chunk_num_elements = chunk->num_elements; int j; for (j = 0; j < chunk_num_elements; ++j) { if (!IS_JIT_INFO_TOMBSTONE (chunk->data [j])) { g_assert (new_chunk < num_chunks); new->chunks [new_chunk]->data [new_element] = chunk->data [j]; if (++new_element >= JIT_INFO_TABLE_FILLED_NUM_ELEMENTS) { new->chunks [new_chunk]->num_elements = new_element; ++new_chunk; new_element = 0; } } } } if (new_chunk < num_chunks) { g_assert (new_chunk == num_chunks - 1); new->chunks [new_chunk]->num_elements = new_element; g_assert (new->chunks [new_chunk]->num_elements > 0); } for (i = 0; i < num_chunks; ++i) { MonoJitInfoTableChunk *chunk = new->chunks [i]; MonoJitInfo *ji = chunk->data [chunk->num_elements - 1]; new->chunks [i]->last_code_end = (gint8*)ji->code_start + ji->code_size; } return new; } static void jit_info_table_split_chunk (MonoJitInfoTableChunk *chunk, MonoJitInfoTableChunk **new1p, MonoJitInfoTableChunk **new2p) { MonoJitInfoTableChunk *new1 = jit_info_table_new_chunk (); MonoJitInfoTableChunk *new2 = jit_info_table_new_chunk (); g_assert (chunk->num_elements == MONO_JIT_INFO_TABLE_CHUNK_SIZE); new1->num_elements = MONO_JIT_INFO_TABLE_CHUNK_SIZE / 2; new2->num_elements = MONO_JIT_INFO_TABLE_CHUNK_SIZE - new1->num_elements; memcpy ((void*)new1->data, (void*)chunk->data, sizeof (MonoJitInfo*) * new1->num_elements); memcpy ((void*)new2->data, (void*)(chunk->data + new1->num_elements), sizeof (MonoJitInfo*) * new2->num_elements); new1->last_code_end = (gint8*)new1->data [new1->num_elements - 1]->code_start + new1->data [new1->num_elements - 1]->code_size; new2->last_code_end = (gint8*)new2->data [new2->num_elements - 1]->code_start + new2->data [new2->num_elements - 1]->code_size; *new1p = new1; *new2p = new2; } static MonoJitInfoTable* jit_info_table_copy_and_split_chunk (MonoJitInfoTable *table, MonoJitInfoTableChunk *chunk) { MonoJitInfoTable *new_table = g_malloc (MONO_SIZEOF_JIT_INFO_TABLE + sizeof (MonoJitInfoTableChunk*) * (table->num_chunks + 1)); int i, j; new_table->domain = table->domain; new_table->num_chunks = table->num_chunks + 1; j = 0; for (i = 0; i < table->num_chunks; ++i) { if (table->chunks [i] == chunk) { jit_info_table_split_chunk (chunk, &new_table->chunks [j], &new_table->chunks [j + 1]); j += 2; } else { new_table->chunks [j] = table->chunks [i]; ++new_table->chunks [j]->refcount; ++j; } } g_assert (j == new_table->num_chunks); return new_table; } static MonoJitInfoTableChunk* jit_info_table_purify_chunk (MonoJitInfoTableChunk *old) { MonoJitInfoTableChunk *new = jit_info_table_new_chunk (); int i, j; j = 0; for (i = 0; i < old->num_elements; ++i) { if (!IS_JIT_INFO_TOMBSTONE (old->data [i])) new->data [j++] = old->data [i]; } new->num_elements = j; if (new->num_elements > 0) new->last_code_end = (gint8*)new->data [j - 1]->code_start + new->data [j - 1]->code_size; else new->last_code_end = old->last_code_end; return new; } static MonoJitInfoTable* jit_info_table_copy_and_purify_chunk (MonoJitInfoTable *table, MonoJitInfoTableChunk *chunk) { MonoJitInfoTable *new_table = g_malloc (MONO_SIZEOF_JIT_INFO_TABLE + sizeof (MonoJitInfoTableChunk*) * table->num_chunks); int i, j; new_table->domain = table->domain; new_table->num_chunks = table->num_chunks; j = 0; for (i = 0; i < table->num_chunks; ++i) { if (table->chunks [i] == chunk) new_table->chunks [j++] = jit_info_table_purify_chunk (table->chunks [i]); else { new_table->chunks [j] = table->chunks [i]; ++new_table->chunks [j]->refcount; ++j; } } g_assert (j == new_table->num_chunks); return new_table; } /* As we add an element to the table the case can arise that the chunk * to which we need to add is already full. In that case we have to * allocate a new table and do something about that chunk. We have * several strategies: * * If the number of elements in the table is below the low watermark * or above the high watermark, we reallocate the whole table. * Otherwise we only concern ourselves with the overflowing chunk: * * If there are no tombstones in the chunk then we split the chunk in * two, each half full. * * If the chunk does contain tombstones, we just make a new copy of * the chunk without the tombstones, which will have room for at least * the one element we have to add. */ static MonoJitInfoTable* jit_info_table_chunk_overflow (MonoJitInfoTable *table, MonoJitInfoTableChunk *chunk) { int num_elements = jit_info_table_num_elements (table); int i; if (num_elements < JIT_INFO_TABLE_LOW_WATERMARK (table->num_chunks * MONO_JIT_INFO_TABLE_CHUNK_SIZE) || num_elements > JIT_INFO_TABLE_HIGH_WATERMARK (table->num_chunks * MONO_JIT_INFO_TABLE_CHUNK_SIZE)) { //printf ("reallocing table\n"); return jit_info_table_realloc (table); } /* count the number of non-tombstone elements in the chunk */ num_elements = 0; for (i = 0; i < chunk->num_elements; ++i) { if (!IS_JIT_INFO_TOMBSTONE (chunk->data [i])) ++num_elements; } if (num_elements == MONO_JIT_INFO_TABLE_CHUNK_SIZE) { //printf ("splitting chunk\n"); return jit_info_table_copy_and_split_chunk (table, chunk); } //printf ("purifying chunk\n"); return jit_info_table_copy_and_purify_chunk (table, chunk); } /* We add elements to the table by first making space for them by * shifting the elements at the back to the right, one at a time. * This results in duplicate entries during the process, but during * all the time the table is in a sorted state. Also, when an element * is replaced by another one, the element that replaces it has an end * address that is equal to or lower than that of the replaced * element. That property is necessary to guarantee that when * searching for an element we end up at a position not higher than * the one we're looking for (i.e. we either find the element directly * or we end up to the left of it). */ static void jit_info_table_add (MonoDomain *domain, MonoJitInfoTable *volatile *table_ptr, MonoJitInfo *ji) { MonoJitInfoTable *table; MonoJitInfoTableChunk *chunk; int chunk_pos, pos; int num_elements; int i; table = *table_ptr; restart: chunk_pos = jit_info_table_index (table, (gint8*)ji->code_start + ji->code_size); g_assert (chunk_pos < table->num_chunks); chunk = table->chunks [chunk_pos]; if (chunk->num_elements >= MONO_JIT_INFO_TABLE_CHUNK_SIZE) { MonoJitInfoTable *new_table = jit_info_table_chunk_overflow (table, chunk); /* Debugging code, should be removed. */ //jit_info_table_check (new_table); *table_ptr = new_table; mono_memory_barrier (); domain->num_jit_info_tables++; mono_thread_hazardous_free_or_queue (table, (MonoHazardousFreeFunc)jit_info_table_free, TRUE, FALSE); table = new_table; goto restart; } /* Debugging code, should be removed. */ //jit_info_table_check (table); num_elements = chunk->num_elements; pos = jit_info_table_chunk_index (chunk, NULL, (gint8*)ji->code_start + ji->code_size); /* First we need to size up the chunk by one, by copying the last item, or inserting the first one, if the table is empty. */ if (num_elements > 0) chunk->data [num_elements] = chunk->data [num_elements - 1]; else chunk->data [0] = ji; mono_memory_write_barrier (); chunk->num_elements = ++num_elements; /* Shift the elements up one by one. */ for (i = num_elements - 2; i >= pos; --i) { mono_memory_write_barrier (); chunk->data [i + 1] = chunk->data [i]; } /* Now we have room and can insert the new item. */ mono_memory_write_barrier (); chunk->data [pos] = ji; /* Set the high code end address chunk entry. */ chunk->last_code_end = (gint8*)chunk->data [chunk->num_elements - 1]->code_start + chunk->data [chunk->num_elements - 1]->code_size; /* Debugging code, should be removed. */ //jit_info_table_check (table); } void mono_jit_info_table_add (MonoDomain *domain, MonoJitInfo *ji) { g_assert (ji->d.method != NULL); mono_domain_lock (domain); ++mono_stats.jit_info_table_insert_count; jit_info_table_add (domain, &domain->jit_info_table, ji); mono_domain_unlock (domain); } static MonoJitInfo* mono_jit_info_make_tombstone (MonoJitInfo *ji) { MonoJitInfo *tombstone = g_new0 (MonoJitInfo, 1); tombstone->code_start = ji->code_start; tombstone->code_size = ji->code_size; tombstone->d.method = JIT_INFO_TOMBSTONE_MARKER; return tombstone; } /* * LOCKING: domain lock */ static void mono_jit_info_free_or_queue (MonoDomain *domain, MonoJitInfo *ji) { if (domain->num_jit_info_tables <= 1) { /* Can it actually happen that we only have one table but ji is still hazardous? */ mono_thread_hazardous_free_or_queue (ji, g_free, TRUE, FALSE); } else { domain->jit_info_free_queue = g_slist_prepend (domain->jit_info_free_queue, ji); } } static void jit_info_table_remove (MonoJitInfoTable *table, MonoJitInfo *ji) { MonoJitInfoTableChunk *chunk; gpointer start = ji->code_start; int chunk_pos, pos; chunk_pos = jit_info_table_index (table, start); g_assert (chunk_pos < table->num_chunks); pos = jit_info_table_chunk_index (table->chunks [chunk_pos], NULL, start); do { chunk = table->chunks [chunk_pos]; while (pos < chunk->num_elements) { if (chunk->data [pos] == ji) goto found; g_assert (IS_JIT_INFO_TOMBSTONE (chunk->data [pos])); g_assert ((guint8*)chunk->data [pos]->code_start + chunk->data [pos]->code_size <= (guint8*)ji->code_start + ji->code_size); ++pos; } ++chunk_pos; pos = 0; } while (chunk_pos < table->num_chunks); found: g_assert (chunk->data [pos] == ji); chunk->data [pos] = mono_jit_info_make_tombstone (ji); /* Debugging code, should be removed. */ //jit_info_table_check (table); } void mono_jit_info_table_remove (MonoDomain *domain, MonoJitInfo *ji) { MonoJitInfoTable *table; mono_domain_lock (domain); table = domain->jit_info_table; ++mono_stats.jit_info_table_remove_count; jit_info_table_remove (table, ji); mono_jit_info_free_or_queue (domain, ji); mono_domain_unlock (domain); } void mono_jit_info_add_aot_module (MonoImage *image, gpointer start, gpointer end) { MonoJitInfo *ji; mono_appdomains_lock (); /* * We reuse MonoJitInfoTable to store AOT module info, * this gives us async-safe lookup. */ g_assert (mono_root_domain); if (!mono_root_domain->aot_modules) { mono_root_domain->num_jit_info_tables ++; mono_root_domain->aot_modules = jit_info_table_new (mono_root_domain); } ji = g_new0 (MonoJitInfo, 1); ji->d.image = image; ji->code_start = start; ji->code_size = (guint8*)end - (guint8*)start; jit_info_table_add (mono_root_domain, &mono_root_domain->aot_modules, ji); mono_appdomains_unlock (); } void mono_install_jit_info_find_in_aot (MonoJitInfoFindInAot func) { jit_info_find_in_aot_func = func; } gpointer mono_jit_info_get_code_start (MonoJitInfo* ji) { return ji->code_start; } int mono_jit_info_get_code_size (MonoJitInfo* ji) { return ji->code_size; } MonoMethod* mono_jit_info_get_method (MonoJitInfo* ji) { g_assert (!ji->async); return ji->d.method; } static gpointer jit_info_key_extract (gpointer value) { MonoJitInfo *info = (MonoJitInfo*)value; return info->d.method; } static gpointer* jit_info_next_value (gpointer value) { MonoJitInfo *info = (MonoJitInfo*)value; return (gpointer*)&info->next_jit_code_hash; } void mono_jit_code_hash_init (MonoInternalHashTable *jit_code_hash) { mono_internal_hash_table_init (jit_code_hash, mono_aligned_addr_hash, jit_info_key_extract, jit_info_next_value); } MonoGenericJitInfo* mono_jit_info_get_generic_jit_info (MonoJitInfo *ji) { if (ji->has_generic_jit_info) return (MonoGenericJitInfo*)&ji->clauses [ji->num_clauses]; else return NULL; } /* * mono_jit_info_get_generic_sharing_context: * @ji: a jit info * * Returns the jit info's generic sharing context, or NULL if it * doesn't have one. */ MonoGenericSharingContext* mono_jit_info_get_generic_sharing_context (MonoJitInfo *ji) { MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (ji); if (gi) return gi->generic_sharing_context; else return NULL; } /* * mono_jit_info_set_generic_sharing_context: * @ji: a jit info * @gsctx: a generic sharing context * * Sets the jit info's generic sharing context. The jit info must * have memory allocated for the context. */ void mono_jit_info_set_generic_sharing_context (MonoJitInfo *ji, MonoGenericSharingContext *gsctx) { MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (ji); g_assert (gi); gi->generic_sharing_context = gsctx; } MonoTryBlockHoleTableJitInfo* mono_jit_info_get_try_block_hole_table_info (MonoJitInfo *ji) { if (ji->has_try_block_holes) { char *ptr = (char*)&ji->clauses [ji->num_clauses]; if (ji->has_generic_jit_info) ptr += sizeof (MonoGenericJitInfo); return (MonoTryBlockHoleTableJitInfo*)ptr; } else { return NULL; } } MonoArchEHJitInfo* mono_jit_info_get_arch_eh_info (MonoJitInfo *ji) { if (ji->has_arch_eh_info) { char *ptr = (char*)&ji->clauses [ji->num_clauses]; if (ji->has_generic_jit_info) ptr += sizeof (MonoGenericJitInfo); if (ji->has_try_block_holes) ptr += sizeof (MonoTryBlockHoleTableJitInfo); return (MonoArchEHJitInfo*)ptr; } else { return NULL; } } MonoMethodCasInfo* mono_jit_info_get_cas_info (MonoJitInfo *ji) { if (ji->has_cas_info) { char *ptr = (char*)&ji->clauses [ji->num_clauses]; if (ji->has_generic_jit_info) ptr += sizeof (MonoGenericJitInfo); if (ji->has_try_block_holes) ptr += sizeof (MonoTryBlockHoleTableJitInfo); if (ji->has_arch_eh_info) ptr += sizeof (MonoArchEHJitInfo); return (MonoMethodCasInfo*)ptr; } else { return NULL; } } #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1)) #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1))) static LockFreeMempool* lock_free_mempool_new (void) { return g_new0 (LockFreeMempool, 1); } static void lock_free_mempool_free (LockFreeMempool *mp) { LockFreeMempoolChunk *chunk, *next; chunk = mp->chunks; while (chunk) { next = chunk->prev; mono_vfree (chunk, mono_pagesize ()); chunk = next; } } /* * This is async safe */ static LockFreeMempoolChunk* lock_free_mempool_chunk_new (LockFreeMempool *mp, int len) { LockFreeMempoolChunk *chunk, *prev; int size; size = mono_pagesize (); while (size - sizeof (LockFreeMempoolChunk) < len) size += mono_pagesize (); chunk = mono_valloc (0, size, MONO_MMAP_READ|MONO_MMAP_WRITE); g_assert (chunk); chunk->mem = ALIGN_PTR_TO ((char*)chunk + sizeof (LockFreeMempoolChunk), 16); chunk->size = ((char*)chunk + size) - (char*)chunk->mem; chunk->pos = 0; /* Add to list of chunks lock-free */ while (TRUE) { prev = mp->chunks; if (InterlockedCompareExchangePointer ((volatile gpointer*)&mp->chunks, chunk, prev) == prev) break; } chunk->prev = prev; return chunk; } /* * This is async safe */ static gpointer lock_free_mempool_alloc0 (LockFreeMempool *mp, guint size) { LockFreeMempoolChunk *chunk; gpointer res; int oldpos; // FIXME: Free the allocator size = ALIGN_TO (size, 8); chunk = mp->current; if (!chunk) { chunk = lock_free_mempool_chunk_new (mp, size); mono_memory_barrier (); /* Publish */ mp->current = chunk; } /* The code below is lock-free, 'chunk' is shared state */ oldpos = InterlockedExchangeAdd (&chunk->pos, size); if (oldpos + size > chunk->size) { chunk = lock_free_mempool_chunk_new (mp, size); g_assert (chunk->pos + size <= chunk->size); res = chunk->mem; chunk->pos += size; mono_memory_barrier (); mp->current = chunk; } else { res = (char*)chunk->mem + oldpos; } return res; } void mono_install_create_domain_hook (MonoCreateDomainFunc func) { create_domain_hook = func; } void mono_install_free_domain_hook (MonoFreeDomainFunc func) { free_domain_hook = func; } /** * mono_string_equal: * @s1: First string to compare * @s2: Second string to compare * * Returns FALSE if the strings differ. */ gboolean mono_string_equal (MonoString *s1, MonoString *s2) { int l1 = mono_string_length (s1); int l2 = mono_string_length (s2); if (s1 == s2) return TRUE; if (l1 != l2) return FALSE; return memcmp (mono_string_chars (s1), mono_string_chars (s2), l1 * 2) == 0; } /** * mono_string_hash: * @s: the string to hash * * Returns the hash for the string. */ guint mono_string_hash (MonoString *s) { const guint16 *p = mono_string_chars (s); int i, len = mono_string_length (s); guint h = 0; for (i = 0; i < len; i++) { h = (h << 5) - h + *p; p++; } return h; } static gboolean mono_ptrarray_equal (gpointer *s1, gpointer *s2) { int len = GPOINTER_TO_INT (s1 [0]); if (len != GPOINTER_TO_INT (s2 [0])) return FALSE; return memcmp (s1 + 1, s2 + 1, len * sizeof(gpointer)) == 0; } static guint mono_ptrarray_hash (gpointer *s) { int i; int len = GPOINTER_TO_INT (s [0]); guint hash = 0; for (i = 1; i < len; i++) hash += GPOINTER_TO_UINT (s [i]); return hash; } /* * Allocate an id for domain and set domain->domain_id. * LOCKING: must be called while holding appdomains_mutex. * We try to assign low numbers to the domain, so it can be used * as an index in data tables to lookup domain-specific info * with minimal memory overhead. We also try not to reuse the * same id too quickly (to help debugging). */ static int domain_id_alloc (MonoDomain *domain) { int id = -1, i; if (!appdomains_list) { appdomain_list_size = 2; appdomains_list = mono_gc_alloc_fixed (appdomain_list_size * sizeof (void*), NULL); } for (i = appdomain_next; i < appdomain_list_size; ++i) { if (!appdomains_list [i]) { id = i; break; } } if (id == -1) { for (i = 0; i < appdomain_next; ++i) { if (!appdomains_list [i]) { id = i; break; } } } if (id == -1) { MonoDomain **new_list; int new_size = appdomain_list_size * 2; if (new_size >= (1 << 16)) g_assert_not_reached (); id = appdomain_list_size; new_list = mono_gc_alloc_fixed (new_size * sizeof (void*), NULL); memcpy (new_list, appdomains_list, appdomain_list_size * sizeof (void*)); mono_gc_free_fixed (appdomains_list); appdomains_list = new_list; appdomain_list_size = new_size; } domain->domain_id = id; appdomains_list [id] = domain; appdomain_next++; if (appdomain_next > appdomain_list_size) appdomain_next = 0; return id; } static gsize domain_gc_bitmap [sizeof(MonoDomain)/4/32 + 1]; static gpointer domain_gc_desc = NULL; static guint32 domain_shadow_serial = 0L; MonoDomain * mono_domain_create (void) { MonoDomain *domain; guint32 shadow_serial; mono_appdomains_lock (); shadow_serial = domain_shadow_serial++; if (!domain_gc_desc) { unsigned int i, bit = 0; for (i = G_STRUCT_OFFSET (MonoDomain, MONO_DOMAIN_FIRST_OBJECT); i < G_STRUCT_OFFSET (MonoDomain, MONO_DOMAIN_FIRST_GC_TRACKED); i += sizeof (gpointer)) { bit = i / sizeof (gpointer); domain_gc_bitmap [bit / 32] |= (gsize) 1 << (bit % 32); } domain_gc_desc = mono_gc_make_descr_from_bitmap ((gsize*)domain_gc_bitmap, bit + 1); } mono_appdomains_unlock (); #ifdef HAVE_BOEHM_GC /* * Boehm doesn't like roots inside GC allocated objects, and alloc_fixed returns * a GC_MALLOC-ed object, contrary to the api docs. This causes random crashes when * running the corlib test suite. * To solve this, we pass a NULL descriptor, and don't register roots. */ domain = mono_gc_alloc_fixed (sizeof (MonoDomain), NULL); #else domain = mono_gc_alloc_fixed (sizeof (MonoDomain), domain_gc_desc); mono_gc_register_root ((char*)&(domain->MONO_DOMAIN_FIRST_GC_TRACKED), G_STRUCT_OFFSET (MonoDomain, MONO_DOMAIN_LAST_GC_TRACKED) - G_STRUCT_OFFSET (MonoDomain, MONO_DOMAIN_FIRST_GC_TRACKED), NULL); #endif domain->shadow_serial = shadow_serial; domain->domain = NULL; domain->setup = NULL; domain->friendly_name = NULL; domain->search_path = NULL; mono_profiler_appdomain_event (domain, MONO_PROFILE_START_LOAD); domain->mp = mono_mempool_new (); domain->code_mp = mono_code_manager_new (); domain->lock_free_mp = lock_free_mempool_new (); domain->env = mono_g_hash_table_new_type ((GHashFunc)mono_string_hash, (GCompareFunc)mono_string_equal, MONO_HASH_KEY_VALUE_GC); domain->domain_assemblies = NULL; domain->assembly_bindings = NULL; domain->assembly_bindings_parsed = FALSE; domain->class_vtable_array = g_ptr_array_new (); domain->proxy_vtable_hash = g_hash_table_new ((GHashFunc)mono_ptrarray_hash, (GCompareFunc)mono_ptrarray_equal); domain->static_data_array = NULL; mono_jit_code_hash_init (&domain->jit_code_hash); domain->ldstr_table = mono_g_hash_table_new_type ((GHashFunc)mono_string_hash, (GCompareFunc)mono_string_equal, MONO_HASH_KEY_VALUE_GC); domain->num_jit_info_tables = 1; domain->jit_info_table = jit_info_table_new (domain); domain->jit_info_free_queue = NULL; domain->finalizable_objects_hash = g_hash_table_new (mono_aligned_addr_hash, NULL); domain->ftnptrs_hash = g_hash_table_new (mono_aligned_addr_hash, NULL); InitializeCriticalSection (&domain->lock); InitializeCriticalSection (&domain->assemblies_lock); InitializeCriticalSection (&domain->jit_code_hash_lock); InitializeCriticalSection (&domain->finalizable_objects_hash_lock); domain->method_rgctx_hash = NULL; mono_appdomains_lock (); domain_id_alloc (domain); mono_appdomains_unlock (); #ifndef DISABLE_PERFCOUNTERS mono_perfcounters->loader_appdomains++; mono_perfcounters->loader_total_appdomains++; #endif mono_debug_domain_create (domain); if (create_domain_hook) create_domain_hook (domain); mono_profiler_appdomain_loaded (domain, MONO_PROFILE_OK); return domain; } /** * mono_init_internal: * * Creates the initial application domain and initializes the mono_defaults * structure. * This function is guaranteed to not run any IL code. * If exe_filename is not NULL, the method will determine the required runtime * from the exe configuration file or the version PE field. * If runtime_version is not NULL, that runtime version will be used. * Either exe_filename or runtime_version must be provided. * * Returns: the initial domain. */ static MonoDomain * mono_init_internal (const char *filename, const char *exe_filename, const char *runtime_version) { static MonoDomain *domain = NULL; MonoAssembly *ass = NULL; MonoImageOpenStatus status = MONO_IMAGE_OK; const MonoRuntimeInfo* runtimes [G_N_ELEMENTS (supported_runtimes) + 1]; int n; if (domain) g_assert_not_reached (); #ifdef HOST_WIN32 /* Avoid system error message boxes. */ SetErrorMode (SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX); #endif #ifndef HOST_WIN32 wapi_init (); #endif #ifndef DISABLE_PERFCOUNTERS mono_perfcounters_init (); #endif mono_counters_register ("Max native code in a domain", MONO_COUNTER_INT|MONO_COUNTER_JIT, &max_domain_code_size); mono_counters_register ("Max code space allocated in a domain", MONO_COUNTER_INT|MONO_COUNTER_JIT, &max_domain_code_alloc); mono_counters_register ("Total code space allocated", MONO_COUNTER_INT|MONO_COUNTER_JIT, &total_domain_code_alloc); mono_gc_base_init (); MONO_FAST_TLS_INIT (tls_appdomain); mono_native_tls_alloc (&appdomain_thread_id, NULL); InitializeCriticalSection (&appdomains_mutex); mono_metadata_init (); mono_images_init (); mono_assemblies_init (); mono_classes_init (); mono_loader_init (); mono_reflection_init (); mono_runtime_init_tls (); /* FIXME: When should we release this memory? */ MONO_GC_REGISTER_ROOT_FIXED (appdomains_list); domain = mono_domain_create (); mono_root_domain = domain; SET_APPDOMAIN (domain); /* Get a list of runtimes supported by the exe */ if (exe_filename != NULL) { /* * This function will load the exe file as a MonoImage. We need to close it, but * that would mean it would be reloaded later. So instead, we save it to * exe_image, and close it during shutdown. */ get_runtimes_from_exe (exe_filename, &exe_image, runtimes); #ifdef HOST_WIN32 if (!exe_image) { exe_image = mono_assembly_open_from_bundle (exe_filename, NULL, FALSE); if (!exe_image) exe_image = mono_image_open (exe_filename, NULL); } mono_fixup_exe_image (exe_image); #endif } else if (runtime_version != NULL) { runtimes [0] = get_runtime_by_version (runtime_version); runtimes [1] = NULL; } if (runtimes [0] == NULL) { const MonoRuntimeInfo *default_runtime = get_runtime_by_version (DEFAULT_RUNTIME_VERSION); runtimes [0] = default_runtime; runtimes [1] = NULL; g_print ("WARNING: The runtime version supported by this application is unavailable.\n"); g_print ("Using default runtime: %s\n", default_runtime->runtime_version); } /* The selected runtime will be the first one for which there is a mscrolib.dll */ for (n = 0; runtimes [n] != NULL && ass == NULL; n++) { current_runtime = runtimes [n]; ass = mono_assembly_load_corlib (current_runtime, &status); if (status != MONO_IMAGE_OK && status != MONO_IMAGE_ERROR_ERRNO) break; } if ((status != MONO_IMAGE_OK) || (ass == NULL)) { switch (status){ case MONO_IMAGE_ERROR_ERRNO: { char *corlib_file = g_build_filename (mono_assembly_getrootdir (), "mono", current_runtime->framework_version, "mscorlib.dll", NULL); g_print ("The assembly mscorlib.dll was not found or could not be loaded.\n"); g_print ("It should have been installed in the `%s' directory.\n", corlib_file); g_free (corlib_file); break; } case MONO_IMAGE_IMAGE_INVALID: g_print ("The file %s/mscorlib.dll is an invalid CIL image\n", mono_assembly_getrootdir ()); break; case MONO_IMAGE_MISSING_ASSEMBLYREF: g_print ("Missing assembly reference in %s/mscorlib.dll\n", mono_assembly_getrootdir ()); break; case MONO_IMAGE_OK: /* to suppress compiler warning */ break; } exit (1); } mono_defaults.corlib = mono_assembly_get_image (ass); mono_defaults.object_class = mono_class_from_name ( mono_defaults.corlib, "System", "Object"); g_assert (mono_defaults.object_class != 0); mono_defaults.void_class = mono_class_from_name ( mono_defaults.corlib, "System", "Void"); g_assert (mono_defaults.void_class != 0); mono_defaults.boolean_class = mono_class_from_name ( mono_defaults.corlib, "System", "Boolean"); g_assert (mono_defaults.boolean_class != 0); mono_defaults.byte_class = mono_class_from_name ( mono_defaults.corlib, "System", "Byte"); g_assert (mono_defaults.byte_class != 0); mono_defaults.sbyte_class = mono_class_from_name ( mono_defaults.corlib, "System", "SByte"); g_assert (mono_defaults.sbyte_class != 0); mono_defaults.int16_class = mono_class_from_name ( mono_defaults.corlib, "System", "Int16"); g_assert (mono_defaults.int16_class != 0); mono_defaults.uint16_class = mono_class_from_name ( mono_defaults.corlib, "System", "UInt16"); g_assert (mono_defaults.uint16_class != 0); mono_defaults.int32_class = mono_class_from_name ( mono_defaults.corlib, "System", "Int32"); g_assert (mono_defaults.int32_class != 0); mono_defaults.uint32_class = mono_class_from_name ( mono_defaults.corlib, "System", "UInt32"); g_assert (mono_defaults.uint32_class != 0); mono_defaults.uint_class = mono_class_from_name ( mono_defaults.corlib, "System", "UIntPtr"); g_assert (mono_defaults.uint_class != 0); mono_defaults.int_class = mono_class_from_name ( mono_defaults.corlib, "System", "IntPtr"); g_assert (mono_defaults.int_class != 0); mono_defaults.int64_class = mono_class_from_name ( mono_defaults.corlib, "System", "Int64"); g_assert (mono_defaults.int64_class != 0); mono_defaults.uint64_class = mono_class_from_name ( mono_defaults.corlib, "System", "UInt64"); g_assert (mono_defaults.uint64_class != 0); mono_defaults.single_class = mono_class_from_name ( mono_defaults.corlib, "System", "Single"); g_assert (mono_defaults.single_class != 0); mono_defaults.double_class = mono_class_from_name ( mono_defaults.corlib, "System", "Double"); g_assert (mono_defaults.double_class != 0); mono_defaults.char_class = mono_class_from_name ( mono_defaults.corlib, "System", "Char"); g_assert (mono_defaults.char_class != 0); mono_defaults.string_class = mono_class_from_name ( mono_defaults.corlib, "System", "String"); g_assert (mono_defaults.string_class != 0); mono_defaults.enum_class = mono_class_from_name ( mono_defaults.corlib, "System", "Enum"); g_assert (mono_defaults.enum_class != 0); mono_defaults.array_class = mono_class_from_name ( mono_defaults.corlib, "System", "Array"); g_assert (mono_defaults.array_class != 0); mono_defaults.delegate_class = mono_class_from_name ( mono_defaults.corlib, "System", "Delegate"); g_assert (mono_defaults.delegate_class != 0 ); mono_defaults.multicastdelegate_class = mono_class_from_name ( mono_defaults.corlib, "System", "MulticastDelegate"); g_assert (mono_defaults.multicastdelegate_class != 0 ); mono_defaults.asyncresult_class = mono_class_from_name ( mono_defaults.corlib, "System.Runtime.Remoting.Messaging", "AsyncResult"); g_assert (mono_defaults.asyncresult_class != 0 ); mono_defaults.manualresetevent_class = mono_class_from_name ( mono_defaults.corlib, "System.Threading", "ManualResetEvent"); g_assert (mono_defaults.manualresetevent_class != 0 ); mono_defaults.typehandle_class = mono_class_from_name ( mono_defaults.corlib, "System", "RuntimeTypeHandle"); g_assert (mono_defaults.typehandle_class != 0); mono_defaults.methodhandle_class = mono_class_from_name ( mono_defaults.corlib, "System", "RuntimeMethodHandle"); g_assert (mono_defaults.methodhandle_class != 0); mono_defaults.fieldhandle_class = mono_class_from_name ( mono_defaults.corlib, "System", "RuntimeFieldHandle"); g_assert (mono_defaults.fieldhandle_class != 0); mono_defaults.systemtype_class = mono_class_from_name ( mono_defaults.corlib, "System", "Type"); g_assert (mono_defaults.systemtype_class != 0); mono_defaults.monotype_class = mono_class_from_name ( mono_defaults.corlib, "System", "MonoType"); g_assert (mono_defaults.monotype_class != 0); mono_defaults.exception_class = mono_class_from_name ( mono_defaults.corlib, "System", "Exception"); g_assert (mono_defaults.exception_class != 0); mono_defaults.threadabortexception_class = mono_class_from_name ( mono_defaults.corlib, "System.Threading", "ThreadAbortException"); g_assert (mono_defaults.threadabortexception_class != 0); mono_defaults.thread_class = mono_class_from_name ( mono_defaults.corlib, "System.Threading", "Thread"); g_assert (mono_defaults.thread_class != 0); mono_defaults.internal_thread_class = mono_class_from_name ( mono_defaults.corlib, "System.Threading", "InternalThread"); if (!mono_defaults.internal_thread_class) { /* This can happen with an old mscorlib */ fprintf (stderr, "Corlib too old for this runtime.\n"); fprintf (stderr, "Loaded from: %s\n", mono_defaults.corlib? mono_image_get_filename (mono_defaults.corlib): "unknown"); exit (1); } mono_defaults.appdomain_class = mono_class_from_name ( mono_defaults.corlib, "System", "AppDomain"); g_assert (mono_defaults.appdomain_class != 0); #ifndef DISABLE_REMOTING mono_defaults.transparent_proxy_class = mono_class_from_name ( mono_defaults.corlib, "System.Runtime.Remoting.Proxies", "TransparentProxy"); g_assert (mono_defaults.transparent_proxy_class != 0); mono_defaults.real_proxy_class = mono_class_from_name ( mono_defaults.corlib, "System.Runtime.Remoting.Proxies", "RealProxy"); g_assert (mono_defaults.real_proxy_class != 0); mono_defaults.marshalbyrefobject_class = mono_class_from_name ( mono_defaults.corlib, "System", "MarshalByRefObject"); g_assert (mono_defaults.marshalbyrefobject_class != 0); mono_defaults.iremotingtypeinfo_class = mono_class_from_name ( mono_defaults.corlib, "System.Runtime.Remoting", "IRemotingTypeInfo"); g_assert (mono_defaults.iremotingtypeinfo_class != 0); #endif mono_defaults.mono_method_message_class = mono_class_from_name ( mono_defaults.corlib, "System.Runtime.Remoting.Messaging", "MonoMethodMessage"); g_assert (mono_defaults.mono_method_message_class != 0); mono_defaults.field_info_class = mono_class_from_name ( mono_defaults.corlib, "System.Reflection", "FieldInfo"); g_assert (mono_defaults.field_info_class != 0); mono_defaults.method_info_class = mono_class_from_name ( mono_defaults.corlib, "System.Reflection", "MethodInfo"); g_assert (mono_defaults.method_info_class != 0); mono_defaults.stringbuilder_class = mono_class_from_name ( mono_defaults.corlib, "System.Text", "StringBuilder"); g_assert (mono_defaults.stringbuilder_class != 0); mono_defaults.math_class = mono_class_from_name ( mono_defaults.corlib, "System", "Math"); g_assert (mono_defaults.math_class != 0); mono_defaults.stack_frame_class = mono_class_from_name ( mono_defaults.corlib, "System.Diagnostics", "StackFrame"); g_assert (mono_defaults.stack_frame_class != 0); mono_defaults.stack_trace_class = mono_class_from_name ( mono_defaults.corlib, "System.Diagnostics", "StackTrace"); g_assert (mono_defaults.stack_trace_class != 0); mono_defaults.marshal_class = mono_class_from_name ( mono_defaults.corlib, "System.Runtime.InteropServices", "Marshal"); g_assert (mono_defaults.marshal_class != 0); mono_defaults.typed_reference_class = mono_class_from_name ( mono_defaults.corlib, "System", "TypedReference"); g_assert (mono_defaults.typed_reference_class != 0); mono_defaults.argumenthandle_class = mono_class_from_name ( mono_defaults.corlib, "System", "RuntimeArgumentHandle"); g_assert (mono_defaults.argumenthandle_class != 0); mono_defaults.monitor_class = mono_class_from_name ( mono_defaults.corlib, "System.Threading", "Monitor"); g_assert (mono_defaults.monitor_class != 0); mono_defaults.runtimesecurityframe_class = mono_class_from_name ( mono_defaults.corlib, "System.Security", "RuntimeSecurityFrame"); mono_defaults.executioncontext_class = mono_class_from_name ( mono_defaults.corlib, "System.Threading", "ExecutionContext"); mono_defaults.internals_visible_class = mono_class_from_name ( mono_defaults.corlib, "System.Runtime.CompilerServices", "InternalsVisibleToAttribute"); mono_defaults.critical_finalizer_object = mono_class_from_name ( mono_defaults.corlib, "System.Runtime.ConstrainedExecution", "CriticalFinalizerObject"); /* * mscorlib needs a little help, only now it can load its friends list (after we have * loaded the InternalsVisibleToAttribute), load it now */ mono_assembly_load_friends (ass); mono_defaults.safehandle_class = mono_class_from_name ( mono_defaults.corlib, "System.Runtime.InteropServices", "SafeHandle"); mono_defaults.handleref_class = mono_class_from_name ( mono_defaults.corlib, "System.Runtime.InteropServices", "HandleRef"); mono_defaults.attribute_class = mono_class_from_name ( mono_defaults.corlib, "System", "Attribute"); mono_defaults.customattribute_data_class = mono_class_from_name ( mono_defaults.corlib, "System.Reflection", "CustomAttributeData"); /* these are initialized lazily when COM features are used */ mono_class_init (mono_defaults.array_class); mono_defaults.generic_nullable_class = mono_class_from_name ( mono_defaults.corlib, "System", "Nullable`1"); mono_defaults.generic_ilist_class = mono_class_from_name ( mono_defaults.corlib, "System.Collections.Generic", "IList`1"); mono_defaults.generic_ireadonlylist_class = mono_class_from_name ( mono_defaults.corlib, "System.Collections.Generic", "IReadOnlyList`1"); domain->friendly_name = g_path_get_basename (filename); _mono_debug_init_corlib (domain); return domain; } /** * mono_init: * * Creates the initial application domain and initializes the mono_defaults * structure. * This function is guaranteed to not run any IL code. * The runtime is initialized using the default runtime version. * * Returns: the initial domain. */ MonoDomain * mono_init (const char *domain_name) { return mono_init_internal (domain_name, NULL, DEFAULT_RUNTIME_VERSION); } /** * mono_init_from_assembly: * @domain_name: name to give to the initial domain * @filename: filename to load on startup * * Used by the runtime, users should use mono_jit_init instead. * * Creates the initial application domain and initializes the mono_defaults * structure. * This function is guaranteed to not run any IL code. * The runtime is initialized using the runtime version required by the * provided executable. The version is determined by looking at the exe * configuration file and the version PE field) * * Returns: the initial domain. */ MonoDomain * mono_init_from_assembly (const char *domain_name, const char *filename) { return mono_init_internal (domain_name, filename, NULL); } /** * mono_init_version: * * Used by the runtime, users should use mono_jit_init instead. * * Creates the initial application domain and initializes the mono_defaults * structure. * * This function is guaranteed to not run any IL code. * The runtime is initialized using the provided rutime version. * * Returns: the initial domain. */ MonoDomain * mono_init_version (const char *domain_name, const char *version) { return mono_init_internal (domain_name, NULL, version); } /** * mono_cleanup: * * Cleans up all metadata modules. */ void mono_cleanup (void) { mono_close_exe_image (); mono_defaults.corlib = NULL; mono_config_cleanup (); mono_loader_cleanup (); mono_classes_cleanup (); mono_assemblies_cleanup (); mono_images_cleanup (); mono_debug_cleanup (); mono_metadata_cleanup (); mono_native_tls_free (appdomain_thread_id); DeleteCriticalSection (&appdomains_mutex); #ifndef HOST_WIN32 wapi_cleanup (); #endif } void mono_close_exe_image (void) { if (exe_image) mono_image_close (exe_image); } /** * mono_get_root_domain: * * The root AppDomain is the initial domain created by the runtime when it is * initialized. Programs execute on this AppDomain, but can create new ones * later. Currently there is no unmanaged API to create new AppDomains, this * must be done from managed code. * * Returns: the root appdomain, to obtain the current domain, use mono_domain_get () */ MonoDomain* mono_get_root_domain (void) { return mono_root_domain; } /** * mono_domain_get: * * Returns: the current domain, to obtain the root domain use * mono_get_root_domain(). */ MonoDomain * mono_domain_get () { return GET_APPDOMAIN (); } void mono_domain_unset (void) { SET_APPDOMAIN (NULL); } void mono_domain_set_internal_with_options (MonoDomain *domain, gboolean migrate_exception) { MonoInternalThread *thread; if (mono_domain_get () == domain) return; SET_APPDOMAIN (domain); SET_APPCONTEXT (domain->default_context); if (migrate_exception) { thread = mono_thread_internal_current (); if (!thread->abort_exc) return; g_assert (thread->abort_exc->object.vtable->domain != domain); MONO_OBJECT_SETREF (thread, abort_exc, mono_get_exception_thread_abort ()); g_assert (thread->abort_exc->object.vtable->domain == domain); } } /** * mono_domain_set_internal: * @domain: the new domain * * Sets the current domain to @domain. */ void mono_domain_set_internal (MonoDomain *domain) { mono_domain_set_internal_with_options (domain, TRUE); } void mono_domain_foreach (MonoDomainFunc func, gpointer user_data) { int i, size; MonoDomain **copy; /* * Create a copy of the data to avoid calling the user callback * inside the lock because that could lead to deadlocks. * We can do this because this function is not perf. critical. */ mono_appdomains_lock (); size = appdomain_list_size; copy = mono_gc_alloc_fixed (appdomain_list_size * sizeof (void*), NULL); memcpy (copy, appdomains_list, appdomain_list_size * sizeof (void*)); mono_appdomains_unlock (); for (i = 0; i < size; ++i) { if (copy [i]) func (copy [i], user_data); } mono_gc_free_fixed (copy); } /** * mono_domain_assembly_open: * @domain: the application domain * @name: file name of the assembly * * fixme: maybe we should integrate this with mono_assembly_open ?? */ MonoAssembly * mono_domain_assembly_open (MonoDomain *domain, const char *name) { MonoDomain *current; MonoAssembly *ass; GSList *tmp; mono_domain_assemblies_lock (domain); for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) { ass = tmp->data; if (strcmp (name, ass->aname.name) == 0) { mono_domain_assemblies_unlock (domain); return ass; } } mono_domain_assemblies_unlock (domain); if (domain != mono_domain_get ()) { current = mono_domain_get (); mono_domain_set (domain, FALSE); ass = mono_assembly_open (name, NULL); mono_domain_set (current, FALSE); } else { ass = mono_assembly_open (name, NULL); } return ass; } static void unregister_vtable_reflection_type (MonoVTable *vtable) { MonoObject *type = vtable->type; if (type->vtable->klass != mono_defaults.monotype_class) MONO_GC_UNREGISTER_ROOT_IF_MOVING (vtable->type); } void mono_domain_free (MonoDomain *domain, gboolean force) { int code_size, code_alloc; GSList *tmp; gpointer *p; if ((domain == mono_root_domain) && !force) { g_warning ("cant unload root domain"); return; } if (mono_dont_free_domains) return; mono_profiler_appdomain_event (domain, MONO_PROFILE_START_UNLOAD); mono_debug_domain_unload (domain); mono_appdomains_lock (); appdomains_list [domain->domain_id] = NULL; mono_appdomains_unlock (); /* must do this early as it accesses fields and types */ if (domain->special_static_fields) { mono_alloc_special_static_data_free (domain->special_static_fields); g_hash_table_destroy (domain->special_static_fields); domain->special_static_fields = NULL; } /* * We must destroy all these hash tables here because they * contain references to managed objects belonging to the * domain. Once we let the GC clear the domain there must be * no more such references, or we'll crash if a collection * occurs. */ mono_g_hash_table_destroy (domain->ldstr_table); domain->ldstr_table = NULL; mono_g_hash_table_destroy (domain->env); domain->env = NULL; if (domain->tlsrec_list) { mono_thread_destroy_domain_tls (domain); domain->tlsrec_list = NULL; } mono_reflection_cleanup_domain (domain); if (domain->type_hash) { mono_g_hash_table_destroy (domain->type_hash); domain->type_hash = NULL; } if (domain->type_init_exception_hash) { mono_g_hash_table_destroy (domain->type_init_exception_hash); domain->type_init_exception_hash = NULL; } if (domain->class_vtable_array) { int i; for (i = 0; i < domain->class_vtable_array->len; ++i) unregister_vtable_reflection_type (g_ptr_array_index (domain->class_vtable_array, i)); } for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) { MonoAssembly *ass = tmp->data; mono_assembly_release_gc_roots (ass); } /* Have to zero out reference fields since they will be invalidated by the clear_domain () call below */ for (p = (gpointer*)&domain->MONO_DOMAIN_FIRST_OBJECT; p < (gpointer*)&domain->MONO_DOMAIN_FIRST_GC_TRACKED; ++p) *p = NULL; /* This needs to be done before closing assemblies */ mono_gc_clear_domain (domain); /* Close dynamic assemblies first, since they have no ref count */ for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) { MonoAssembly *ass = tmp->data; if (!ass->image || !ass->image->dynamic) continue; mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading domain %s[%p], assembly %s[%p], ref_count=%d", domain->friendly_name, domain, ass->aname.name, ass, ass->ref_count); if (!mono_assembly_close_except_image_pools (ass)) tmp->data = NULL; } for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) { MonoAssembly *ass = tmp->data; if (!ass) continue; if (!ass->image || ass->image->dynamic) continue; mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_ASSEMBLY, "Unloading domain %s[%p], assembly %s[%p], ref_count=%d", domain->friendly_name, domain, ass->aname.name, ass, ass->ref_count); if (!mono_assembly_close_except_image_pools (ass)) tmp->data = NULL; } for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) { MonoAssembly *ass = tmp->data; if (ass) mono_assembly_close_finish (ass); } g_slist_free (domain->domain_assemblies); domain->domain_assemblies = NULL; /* * Send this after the assemblies have been unloaded and the domain is still in a * usable state. */ mono_profiler_appdomain_event (domain, MONO_PROFILE_END_UNLOAD); if (free_domain_hook) free_domain_hook (domain); /* FIXME: free delegate_hash_table when it's used */ if (domain->search_path) { g_strfreev (domain->search_path); domain->search_path = NULL; } domain->create_proxy_for_type_method = NULL; domain->private_invoke_method = NULL; domain->default_context = NULL; domain->out_of_memory_ex = NULL; domain->null_reference_ex = NULL; domain->stack_overflow_ex = NULL; domain->ephemeron_tombstone = NULL; domain->entry_assembly = NULL; g_free (domain->friendly_name); domain->friendly_name = NULL; g_ptr_array_free (domain->class_vtable_array, TRUE); domain->class_vtable_array = NULL; g_hash_table_destroy (domain->proxy_vtable_hash); domain->proxy_vtable_hash = NULL; if (domain->static_data_array) { mono_gc_free_fixed (domain->static_data_array); domain->static_data_array = NULL; } mono_internal_hash_table_destroy (&domain->jit_code_hash); /* * There might still be jit info tables of this domain which * are not freed. Since the domain cannot be in use anymore, * this will free them. */ mono_thread_hazardous_try_free_all (); if (domain->aot_modules) jit_info_table_free (domain->aot_modules); g_assert (domain->num_jit_info_tables == 1); jit_info_table_free (domain->jit_info_table); domain->jit_info_table = NULL; g_assert (!domain->jit_info_free_queue); /* collect statistics */ code_alloc = mono_code_manager_size (domain->code_mp, &code_size); total_domain_code_alloc += code_alloc; max_domain_code_alloc = MAX (max_domain_code_alloc, code_alloc); max_domain_code_size = MAX (max_domain_code_size, code_size); #ifdef DEBUG_DOMAIN_UNLOAD mono_mempool_invalidate (domain->mp); mono_code_manager_invalidate (domain->code_mp); #else #ifndef DISABLE_PERFCOUNTERS mono_perfcounters->loader_bytes -= mono_mempool_get_allocated (domain->mp); #endif mono_mempool_destroy (domain->mp); domain->mp = NULL; mono_code_manager_destroy (domain->code_mp); domain->code_mp = NULL; #endif lock_free_mempool_free (domain->lock_free_mp); domain->lock_free_mp = NULL; g_hash_table_destroy (domain->finalizable_objects_hash); domain->finalizable_objects_hash = NULL; if (domain->method_rgctx_hash) { g_hash_table_destroy (domain->method_rgctx_hash); domain->method_rgctx_hash = NULL; } if (domain->generic_virtual_cases) { g_hash_table_destroy (domain->generic_virtual_cases); domain->generic_virtual_cases = NULL; } if (domain->generic_virtual_thunks) { g_hash_table_destroy (domain->generic_virtual_thunks); domain->generic_virtual_thunks = NULL; } if (domain->ftnptrs_hash) { g_hash_table_destroy (domain->ftnptrs_hash); domain->ftnptrs_hash = NULL; } DeleteCriticalSection (&domain->finalizable_objects_hash_lock); DeleteCriticalSection (&domain->assemblies_lock); DeleteCriticalSection (&domain->jit_code_hash_lock); DeleteCriticalSection (&domain->lock); domain->setup = NULL; mono_gc_deregister_root ((char*)&(domain->MONO_DOMAIN_FIRST_GC_TRACKED)); /* FIXME: anything else required ? */ mono_gc_free_fixed (domain); #ifndef DISABLE_PERFCOUNTERS mono_perfcounters->loader_appdomains--; #endif if (domain == mono_root_domain) mono_root_domain = NULL; } /** * mono_domain_get_id: * @domainid: the ID * * Returns: the a domain for a specific domain id. */ MonoDomain * mono_domain_get_by_id (gint32 domainid) { MonoDomain * domain; mono_appdomains_lock (); if (domainid < appdomain_list_size) domain = appdomains_list [domainid]; else domain = NULL; mono_appdomains_unlock (); return domain; } gint32 mono_domain_get_id (MonoDomain *domain) { return domain->domain_id; } /* * mono_domain_alloc: * * LOCKING: Acquires the domain lock. */ gpointer mono_domain_alloc (MonoDomain *domain, guint size) { gpointer res; mono_domain_lock (domain); #ifndef DISABLE_PERFCOUNTERS mono_perfcounters->loader_bytes += size; #endif res = mono_mempool_alloc (domain->mp, size); mono_domain_unlock (domain); return res; } /* * mono_domain_alloc0: * * LOCKING: Acquires the domain lock. */ gpointer mono_domain_alloc0 (MonoDomain *domain, guint size) { gpointer res; mono_domain_lock (domain); #ifndef DISABLE_PERFCOUNTERS mono_perfcounters->loader_bytes += size; #endif res = mono_mempool_alloc0 (domain->mp, size); mono_domain_unlock (domain); return res; } gpointer mono_domain_alloc0_lock_free (MonoDomain *domain, guint size) { return lock_free_mempool_alloc0 (domain->lock_free_mp, size); } /* * mono_domain_code_reserve: * * LOCKING: Acquires the domain lock. */ void* mono_domain_code_reserve (MonoDomain *domain, int size) { gpointer res; mono_domain_lock (domain); res = mono_code_manager_reserve (domain->code_mp, size); mono_domain_unlock (domain); return res; } /* * mono_domain_code_reserve_align: * * LOCKING: Acquires the domain lock. */ void* mono_domain_code_reserve_align (MonoDomain *domain, int size, int alignment) { gpointer res; mono_domain_lock (domain); res = mono_code_manager_reserve_align (domain->code_mp, size, alignment); mono_domain_unlock (domain); return res; } /* * mono_domain_code_commit: * * LOCKING: Acquires the domain lock. */ void mono_domain_code_commit (MonoDomain *domain, void *data, int size, int newsize) { mono_domain_lock (domain); mono_code_manager_commit (domain->code_mp, data, size, newsize); mono_domain_unlock (domain); } #if defined(__native_client_codegen__) && defined(__native_client__) /* * Given the temporary buffer (allocated by mono_domain_code_reserve) into which * we are generating code, return a pointer to the destination in the dynamic * code segment into which the code will be copied when mono_domain_code_commit * is called. * LOCKING: Acquires the domain lock. */ void * nacl_domain_get_code_dest (MonoDomain *domain, void *data) { void *dest; mono_domain_lock (domain); dest = nacl_code_manager_get_code_dest (domain->code_mp, data); mono_domain_unlock (domain); return dest; } /* * Convenience function which calls mono_domain_code_commit to validate and copy * the code. The caller sets *buf_base and *buf_size to the start and size of * the buffer (allocated by mono_domain_code_reserve), and *code_end to the byte * after the last instruction byte. On return, *buf_base will point to the start * of the copied in the code segment, and *code_end will point after the end of * the copied code. */ void nacl_domain_code_validate (MonoDomain *domain, guint8 **buf_base, int buf_size, guint8 **code_end) { guint8 *tmp = nacl_domain_get_code_dest (domain, *buf_base); mono_domain_code_commit (domain, *buf_base, buf_size, *code_end - *buf_base); *code_end = tmp + (*code_end - *buf_base); *buf_base = tmp; } #else /* no-op versions of Native Client functions */ void * nacl_domain_get_code_dest (MonoDomain *domain, void *data) { return data; } void nacl_domain_code_validate (MonoDomain *domain, guint8 **buf_base, int buf_size, guint8 **code_end) { } #endif /* * mono_domain_code_foreach: * Iterate over the code thunks of the code manager of @domain. * * The @func callback MUST not take any locks. If it really needs to, it must respect * the locking rules of the runtime: http://www.mono-project.com/Mono:Runtime:Documentation:ThreadSafety * LOCKING: Acquires the domain lock. */ void mono_domain_code_foreach (MonoDomain *domain, MonoCodeManagerFunc func, void *user_data) { mono_domain_lock (domain); mono_code_manager_foreach (domain->code_mp, func, user_data); mono_domain_unlock (domain); } void mono_context_set (MonoAppContext * new_context) { SET_APPCONTEXT (new_context); } MonoAppContext * mono_context_get (void) { return GET_APPCONTEXT (); } /* LOCKING: the caller holds the lock for this domain */ void mono_domain_add_class_static_data (MonoDomain *domain, MonoClass *klass, gpointer data, guint32 *bitmap) { /* The first entry in the array is the index of the next free slot * and the total size of the array */ int next; if (domain->static_data_array) { int size = GPOINTER_TO_INT (domain->static_data_array [1]); next = GPOINTER_TO_INT (domain->static_data_array [0]); if (next >= size) { /* 'data' is allocated by alloc_fixed */ gpointer *new_array = mono_gc_alloc_fixed (sizeof (gpointer) * (size * 2), MONO_GC_ROOT_DESCR_FOR_FIXED (size * 2)); mono_gc_memmove (new_array, domain->static_data_array, sizeof (gpointer) * size); size *= 2; new_array [1] = GINT_TO_POINTER (size); mono_gc_free_fixed (domain->static_data_array); domain->static_data_array = new_array; } } else { int size = 32; gpointer *new_array = mono_gc_alloc_fixed (sizeof (gpointer) * size, MONO_GC_ROOT_DESCR_FOR_FIXED (size)); next = 2; new_array [0] = GINT_TO_POINTER (next); new_array [1] = GINT_TO_POINTER (size); domain->static_data_array = new_array; } domain->static_data_array [next++] = data; domain->static_data_array [0] = GINT_TO_POINTER (next); } MonoImage* mono_get_corlib (void) { return mono_defaults.corlib; } MonoClass* mono_get_object_class (void) { return mono_defaults.object_class; } MonoClass* mono_get_byte_class (void) { return mono_defaults.byte_class; } MonoClass* mono_get_void_class (void) { return mono_defaults.void_class; } MonoClass* mono_get_boolean_class (void) { return mono_defaults.boolean_class; } MonoClass* mono_get_sbyte_class (void) { return mono_defaults.sbyte_class; } MonoClass* mono_get_int16_class (void) { return mono_defaults.int16_class; } MonoClass* mono_get_uint16_class (void) { return mono_defaults.uint16_class; } MonoClass* mono_get_int32_class (void) { return mono_defaults.int32_class; } MonoClass* mono_get_uint32_class (void) { return mono_defaults.uint32_class; } MonoClass* mono_get_intptr_class (void) { return mono_defaults.int_class; } MonoClass* mono_get_uintptr_class (void) { return mono_defaults.uint_class; } MonoClass* mono_get_int64_class (void) { return mono_defaults.int64_class; } MonoClass* mono_get_uint64_class (void) { return mono_defaults.uint64_class; } MonoClass* mono_get_single_class (void) { return mono_defaults.single_class; } MonoClass* mono_get_double_class (void) { return mono_defaults.double_class; } MonoClass* mono_get_char_class (void) { return mono_defaults.char_class; } MonoClass* mono_get_string_class (void) { return mono_defaults.string_class; } MonoClass* mono_get_enum_class (void) { return mono_defaults.enum_class; } MonoClass* mono_get_array_class (void) { return mono_defaults.array_class; } MonoClass* mono_get_thread_class (void) { return mono_defaults.thread_class; } MonoClass* mono_get_exception_class (void) { return mono_defaults.exception_class; } static char* get_attribute_value (const gchar **attribute_names, const gchar **attribute_values, const char *att_name) { int n; for (n=0; attribute_names[n] != NULL; n++) { if (strcmp (attribute_names[n], att_name) == 0) return g_strdup (attribute_values[n]); } return NULL; } static void start_element (GMarkupParseContext *context, const gchar *element_name, const gchar **attribute_names, const gchar **attribute_values, gpointer user_data, GError **error) { AppConfigInfo* app_config = (AppConfigInfo*) user_data; if (strcmp (element_name, "configuration") == 0) { app_config->configuration_count++; return; } if (strcmp (element_name, "startup") == 0) { app_config->startup_count++; return; } if (app_config->configuration_count != 1 || app_config->startup_count != 1) return; if (strcmp (element_name, "requiredRuntime") == 0) { app_config->required_runtime = get_attribute_value (attribute_names, attribute_values, "version"); } else if (strcmp (element_name, "supportedRuntime") == 0) { char *version = get_attribute_value (attribute_names, attribute_values, "version"); app_config->supported_runtimes = g_slist_append (app_config->supported_runtimes, version); } } static void end_element (GMarkupParseContext *context, const gchar *element_name, gpointer user_data, GError **error) { AppConfigInfo* app_config = (AppConfigInfo*) user_data; if (strcmp (element_name, "configuration") == 0) { app_config->configuration_count--; } else if (strcmp (element_name, "startup") == 0) { app_config->startup_count--; } } static const GMarkupParser mono_parser = { start_element, end_element, NULL, NULL, NULL }; static AppConfigInfo * app_config_parse (const char *exe_filename) { AppConfigInfo *app_config; GMarkupParseContext *context; char *text; gsize len; const char *bundled_config; char *config_filename; bundled_config = mono_config_string_for_assembly_file (exe_filename); if (bundled_config) { text = g_strdup (bundled_config); len = strlen (text); } else { config_filename = g_strconcat (exe_filename, ".config", NULL); if (!g_file_get_contents (config_filename, &text, &len, NULL)) { g_free (config_filename); return NULL; } g_free (config_filename); } app_config = g_new0 (AppConfigInfo, 1); context = g_markup_parse_context_new (&mono_parser, 0, app_config, NULL); if (g_markup_parse_context_parse (context, text, len, NULL)) { g_markup_parse_context_end_parse (context, NULL); } g_markup_parse_context_free (context); g_free (text); return app_config; } static void app_config_free (AppConfigInfo* app_config) { char *rt; GSList *list = app_config->supported_runtimes; while (list != NULL) { rt = (char*)list->data; g_free (rt); list = g_slist_next (list); } g_slist_free (app_config->supported_runtimes); g_free (app_config->required_runtime); g_free (app_config); } static const MonoRuntimeInfo* get_runtime_by_version (const char *version) { int n; int max = G_N_ELEMENTS (supported_runtimes); int vlen; if (!version) return NULL; for (n=0; n<max; n++) { if (strcmp (version, supported_runtimes[n].runtime_version) == 0) return &supported_runtimes[n]; } vlen = strlen (version); if (vlen >= 4 && version [1] - '0' >= 4) { for (n=0; n<max; n++) { if (strncmp (version, supported_runtimes[n].runtime_version, 4) == 0) return &supported_runtimes[n]; } } return NULL; } static void get_runtimes_from_exe (const char *exe_file, MonoImage **exe_image, const MonoRuntimeInfo** runtimes) { AppConfigInfo* app_config; char *version; const MonoRuntimeInfo* runtime = NULL; MonoImage *image = NULL; app_config = app_config_parse (exe_file); if (app_config != NULL) { /* Check supportedRuntime elements, if none is supported, fail. * If there are no such elements, look for a requiredRuntime element. */ if (app_config->supported_runtimes != NULL) { int n = 0; GSList *list = app_config->supported_runtimes; while (list != NULL) { version = (char*) list->data; runtime = get_runtime_by_version (version); if (runtime != NULL) runtimes [n++] = runtime; list = g_slist_next (list); } runtimes [n] = NULL; app_config_free (app_config); return; } /* Check the requiredRuntime element. This is for 1.0 apps only. */ if (app_config->required_runtime != NULL) { runtimes [0] = get_runtime_by_version (app_config->required_runtime); runtimes [1] = NULL; app_config_free (app_config); return; } app_config_free (app_config); } /* Look for a runtime with the exact version */ image = mono_assembly_open_from_bundle (exe_file, NULL, FALSE); if (image == NULL) image = mono_image_open (exe_file, NULL); if (image == NULL) { /* The image is wrong or the file was not found. In this case return * a default runtime and leave to the initialization method the work of * reporting the error. */ runtimes [0] = get_runtime_by_version (DEFAULT_RUNTIME_VERSION); runtimes [1] = NULL; return; } *exe_image = image; runtimes [0] = get_runtime_by_version (image->version); runtimes [1] = NULL; } /** * mono_get_runtime_info: * * Returns: the version of the current runtime instance. */ const MonoRuntimeInfo* mono_get_runtime_info (void) { return current_runtime; } gchar * mono_debugger_check_runtime_version (const char *filename) { const MonoRuntimeInfo* runtimes [G_N_ELEMENTS (supported_runtimes) + 1]; const MonoRuntimeInfo *rinfo; MonoImage *image; get_runtimes_from_exe (filename, &image, runtimes); rinfo = runtimes [0]; if (!rinfo) return g_strdup_printf ("Cannot get runtime version from assembly `%s'", filename); if (rinfo != current_runtime) return g_strdup_printf ("The Mono Debugger is currently using the `%s' runtime, but " "the assembly `%s' requires version `%s'", current_runtime->runtime_version, filename, rinfo->runtime_version); return NULL; } /** * mono_framework_version: * * Return the major version of the framework curently executing. */ int mono_framework_version (void) { return current_runtime->framework_version [0] - '0'; }
28.079024
198
0.730069
[ "object" ]
7f55337803b69bc7d732e9e5b2928c40b661b538
33,090
h
C
aws-cpp-sdk-batch/include/aws/batch/model/SubmitJobRequest.h
ploki/aws-sdk-cpp
17074e3e48c7411f81294e2ee9b1550c4dde842c
[ "Apache-2.0" ]
2
2019-03-11T15:50:55.000Z
2020-02-27T11:40:27.000Z
aws-cpp-sdk-batch/include/aws/batch/model/SubmitJobRequest.h
ploki/aws-sdk-cpp
17074e3e48c7411f81294e2ee9b1550c4dde842c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-batch/include/aws/batch/model/SubmitJobRequest.h
ploki/aws-sdk-cpp
17074e3e48c7411f81294e2ee9b1550c4dde842c
[ "Apache-2.0" ]
1
2019-01-18T13:03:55.000Z
2019-01-18T13:03:55.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #pragma once #include <aws/batch/Batch_EXPORTS.h> #include <aws/batch/BatchRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/batch/model/ArrayProperties.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/core/utils/memory/stl/AWSMap.h> #include <aws/batch/model/ContainerOverrides.h> #include <aws/batch/model/NodeOverrides.h> #include <aws/batch/model/RetryStrategy.h> #include <aws/batch/model/JobTimeout.h> #include <aws/batch/model/JobDependency.h> #include <utility> namespace Aws { namespace Batch { namespace Model { /** */ class AWS_BATCH_API SubmitJobRequest : public BatchRequest { public: SubmitJobRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "SubmitJob"; } Aws::String SerializePayload() const override; /** * <p>The name of the job. The first character must be alphanumeric, and up to 128 * letters (uppercase and lowercase), numbers, hyphens, and underscores are * allowed. </p> */ inline const Aws::String& GetJobName() const{ return m_jobName; } /** * <p>The name of the job. The first character must be alphanumeric, and up to 128 * letters (uppercase and lowercase), numbers, hyphens, and underscores are * allowed. </p> */ inline void SetJobName(const Aws::String& value) { m_jobNameHasBeenSet = true; m_jobName = value; } /** * <p>The name of the job. The first character must be alphanumeric, and up to 128 * letters (uppercase and lowercase), numbers, hyphens, and underscores are * allowed. </p> */ inline void SetJobName(Aws::String&& value) { m_jobNameHasBeenSet = true; m_jobName = std::move(value); } /** * <p>The name of the job. The first character must be alphanumeric, and up to 128 * letters (uppercase and lowercase), numbers, hyphens, and underscores are * allowed. </p> */ inline void SetJobName(const char* value) { m_jobNameHasBeenSet = true; m_jobName.assign(value); } /** * <p>The name of the job. The first character must be alphanumeric, and up to 128 * letters (uppercase and lowercase), numbers, hyphens, and underscores are * allowed. </p> */ inline SubmitJobRequest& WithJobName(const Aws::String& value) { SetJobName(value); return *this;} /** * <p>The name of the job. The first character must be alphanumeric, and up to 128 * letters (uppercase and lowercase), numbers, hyphens, and underscores are * allowed. </p> */ inline SubmitJobRequest& WithJobName(Aws::String&& value) { SetJobName(std::move(value)); return *this;} /** * <p>The name of the job. The first character must be alphanumeric, and up to 128 * letters (uppercase and lowercase), numbers, hyphens, and underscores are * allowed. </p> */ inline SubmitJobRequest& WithJobName(const char* value) { SetJobName(value); return *this;} /** * <p>The job queue into which the job is submitted. You can specify either the * name or the Amazon Resource Name (ARN) of the queue. </p> */ inline const Aws::String& GetJobQueue() const{ return m_jobQueue; } /** * <p>The job queue into which the job is submitted. You can specify either the * name or the Amazon Resource Name (ARN) of the queue. </p> */ inline void SetJobQueue(const Aws::String& value) { m_jobQueueHasBeenSet = true; m_jobQueue = value; } /** * <p>The job queue into which the job is submitted. You can specify either the * name or the Amazon Resource Name (ARN) of the queue. </p> */ inline void SetJobQueue(Aws::String&& value) { m_jobQueueHasBeenSet = true; m_jobQueue = std::move(value); } /** * <p>The job queue into which the job is submitted. You can specify either the * name or the Amazon Resource Name (ARN) of the queue. </p> */ inline void SetJobQueue(const char* value) { m_jobQueueHasBeenSet = true; m_jobQueue.assign(value); } /** * <p>The job queue into which the job is submitted. You can specify either the * name or the Amazon Resource Name (ARN) of the queue. </p> */ inline SubmitJobRequest& WithJobQueue(const Aws::String& value) { SetJobQueue(value); return *this;} /** * <p>The job queue into which the job is submitted. You can specify either the * name or the Amazon Resource Name (ARN) of the queue. </p> */ inline SubmitJobRequest& WithJobQueue(Aws::String&& value) { SetJobQueue(std::move(value)); return *this;} /** * <p>The job queue into which the job is submitted. You can specify either the * name or the Amazon Resource Name (ARN) of the queue. </p> */ inline SubmitJobRequest& WithJobQueue(const char* value) { SetJobQueue(value); return *this;} /** * <p>The array properties for the submitted job, such as the size of the array. * The array size can be between 2 and 10,000. If you specify array properties for * a job, it becomes an array job. For more information, see <a * href="http://docs.aws.amazon.com/batch/latest/userguide/array_jobs.html">Array * Jobs</a> in the <i>AWS Batch User Guide</i>.</p> */ inline const ArrayProperties& GetArrayProperties() const{ return m_arrayProperties; } /** * <p>The array properties for the submitted job, such as the size of the array. * The array size can be between 2 and 10,000. If you specify array properties for * a job, it becomes an array job. For more information, see <a * href="http://docs.aws.amazon.com/batch/latest/userguide/array_jobs.html">Array * Jobs</a> in the <i>AWS Batch User Guide</i>.</p> */ inline void SetArrayProperties(const ArrayProperties& value) { m_arrayPropertiesHasBeenSet = true; m_arrayProperties = value; } /** * <p>The array properties for the submitted job, such as the size of the array. * The array size can be between 2 and 10,000. If you specify array properties for * a job, it becomes an array job. For more information, see <a * href="http://docs.aws.amazon.com/batch/latest/userguide/array_jobs.html">Array * Jobs</a> in the <i>AWS Batch User Guide</i>.</p> */ inline void SetArrayProperties(ArrayProperties&& value) { m_arrayPropertiesHasBeenSet = true; m_arrayProperties = std::move(value); } /** * <p>The array properties for the submitted job, such as the size of the array. * The array size can be between 2 and 10,000. If you specify array properties for * a job, it becomes an array job. For more information, see <a * href="http://docs.aws.amazon.com/batch/latest/userguide/array_jobs.html">Array * Jobs</a> in the <i>AWS Batch User Guide</i>.</p> */ inline SubmitJobRequest& WithArrayProperties(const ArrayProperties& value) { SetArrayProperties(value); return *this;} /** * <p>The array properties for the submitted job, such as the size of the array. * The array size can be between 2 and 10,000. If you specify array properties for * a job, it becomes an array job. For more information, see <a * href="http://docs.aws.amazon.com/batch/latest/userguide/array_jobs.html">Array * Jobs</a> in the <i>AWS Batch User Guide</i>.</p> */ inline SubmitJobRequest& WithArrayProperties(ArrayProperties&& value) { SetArrayProperties(std::move(value)); return *this;} /** * <p>A list of dependencies for the job. A job can depend upon a maximum of 20 * jobs. You can specify a <code>SEQUENTIAL</code> type dependency without * specifying a job ID for array jobs so that each child array job completes * sequentially, starting at index 0. You can also specify an <code>N_TO_N</code> * type dependency with a job ID for array jobs. In that case, each index child of * this job must wait for the corresponding index child of each dependency to * complete before it can begin.</p> */ inline const Aws::Vector<JobDependency>& GetDependsOn() const{ return m_dependsOn; } /** * <p>A list of dependencies for the job. A job can depend upon a maximum of 20 * jobs. You can specify a <code>SEQUENTIAL</code> type dependency without * specifying a job ID for array jobs so that each child array job completes * sequentially, starting at index 0. You can also specify an <code>N_TO_N</code> * type dependency with a job ID for array jobs. In that case, each index child of * this job must wait for the corresponding index child of each dependency to * complete before it can begin.</p> */ inline void SetDependsOn(const Aws::Vector<JobDependency>& value) { m_dependsOnHasBeenSet = true; m_dependsOn = value; } /** * <p>A list of dependencies for the job. A job can depend upon a maximum of 20 * jobs. You can specify a <code>SEQUENTIAL</code> type dependency without * specifying a job ID for array jobs so that each child array job completes * sequentially, starting at index 0. You can also specify an <code>N_TO_N</code> * type dependency with a job ID for array jobs. In that case, each index child of * this job must wait for the corresponding index child of each dependency to * complete before it can begin.</p> */ inline void SetDependsOn(Aws::Vector<JobDependency>&& value) { m_dependsOnHasBeenSet = true; m_dependsOn = std::move(value); } /** * <p>A list of dependencies for the job. A job can depend upon a maximum of 20 * jobs. You can specify a <code>SEQUENTIAL</code> type dependency without * specifying a job ID for array jobs so that each child array job completes * sequentially, starting at index 0. You can also specify an <code>N_TO_N</code> * type dependency with a job ID for array jobs. In that case, each index child of * this job must wait for the corresponding index child of each dependency to * complete before it can begin.</p> */ inline SubmitJobRequest& WithDependsOn(const Aws::Vector<JobDependency>& value) { SetDependsOn(value); return *this;} /** * <p>A list of dependencies for the job. A job can depend upon a maximum of 20 * jobs. You can specify a <code>SEQUENTIAL</code> type dependency without * specifying a job ID for array jobs so that each child array job completes * sequentially, starting at index 0. You can also specify an <code>N_TO_N</code> * type dependency with a job ID for array jobs. In that case, each index child of * this job must wait for the corresponding index child of each dependency to * complete before it can begin.</p> */ inline SubmitJobRequest& WithDependsOn(Aws::Vector<JobDependency>&& value) { SetDependsOn(std::move(value)); return *this;} /** * <p>A list of dependencies for the job. A job can depend upon a maximum of 20 * jobs. You can specify a <code>SEQUENTIAL</code> type dependency without * specifying a job ID for array jobs so that each child array job completes * sequentially, starting at index 0. You can also specify an <code>N_TO_N</code> * type dependency with a job ID for array jobs. In that case, each index child of * this job must wait for the corresponding index child of each dependency to * complete before it can begin.</p> */ inline SubmitJobRequest& AddDependsOn(const JobDependency& value) { m_dependsOnHasBeenSet = true; m_dependsOn.push_back(value); return *this; } /** * <p>A list of dependencies for the job. A job can depend upon a maximum of 20 * jobs. You can specify a <code>SEQUENTIAL</code> type dependency without * specifying a job ID for array jobs so that each child array job completes * sequentially, starting at index 0. You can also specify an <code>N_TO_N</code> * type dependency with a job ID for array jobs. In that case, each index child of * this job must wait for the corresponding index child of each dependency to * complete before it can begin.</p> */ inline SubmitJobRequest& AddDependsOn(JobDependency&& value) { m_dependsOnHasBeenSet = true; m_dependsOn.push_back(std::move(value)); return *this; } /** * <p>The job definition used by this job. This value can be either a * <code>name:revision</code> or the Amazon Resource Name (ARN) for the job * definition.</p> */ inline const Aws::String& GetJobDefinition() const{ return m_jobDefinition; } /** * <p>The job definition used by this job. This value can be either a * <code>name:revision</code> or the Amazon Resource Name (ARN) for the job * definition.</p> */ inline void SetJobDefinition(const Aws::String& value) { m_jobDefinitionHasBeenSet = true; m_jobDefinition = value; } /** * <p>The job definition used by this job. This value can be either a * <code>name:revision</code> or the Amazon Resource Name (ARN) for the job * definition.</p> */ inline void SetJobDefinition(Aws::String&& value) { m_jobDefinitionHasBeenSet = true; m_jobDefinition = std::move(value); } /** * <p>The job definition used by this job. This value can be either a * <code>name:revision</code> or the Amazon Resource Name (ARN) for the job * definition.</p> */ inline void SetJobDefinition(const char* value) { m_jobDefinitionHasBeenSet = true; m_jobDefinition.assign(value); } /** * <p>The job definition used by this job. This value can be either a * <code>name:revision</code> or the Amazon Resource Name (ARN) for the job * definition.</p> */ inline SubmitJobRequest& WithJobDefinition(const Aws::String& value) { SetJobDefinition(value); return *this;} /** * <p>The job definition used by this job. This value can be either a * <code>name:revision</code> or the Amazon Resource Name (ARN) for the job * definition.</p> */ inline SubmitJobRequest& WithJobDefinition(Aws::String&& value) { SetJobDefinition(std::move(value)); return *this;} /** * <p>The job definition used by this job. This value can be either a * <code>name:revision</code> or the Amazon Resource Name (ARN) for the job * definition.</p> */ inline SubmitJobRequest& WithJobDefinition(const char* value) { SetJobDefinition(value); return *this;} /** * <p>Additional parameters passed to the job that replace parameter substitution * placeholders that are set in the job definition. Parameters are specified as a * key and value pair mapping. Parameters in a <code>SubmitJob</code> request * override any corresponding parameter defaults from the job definition.</p> */ inline const Aws::Map<Aws::String, Aws::String>& GetParameters() const{ return m_parameters; } /** * <p>Additional parameters passed to the job that replace parameter substitution * placeholders that are set in the job definition. Parameters are specified as a * key and value pair mapping. Parameters in a <code>SubmitJob</code> request * override any corresponding parameter defaults from the job definition.</p> */ inline void SetParameters(const Aws::Map<Aws::String, Aws::String>& value) { m_parametersHasBeenSet = true; m_parameters = value; } /** * <p>Additional parameters passed to the job that replace parameter substitution * placeholders that are set in the job definition. Parameters are specified as a * key and value pair mapping. Parameters in a <code>SubmitJob</code> request * override any corresponding parameter defaults from the job definition.</p> */ inline void SetParameters(Aws::Map<Aws::String, Aws::String>&& value) { m_parametersHasBeenSet = true; m_parameters = std::move(value); } /** * <p>Additional parameters passed to the job that replace parameter substitution * placeholders that are set in the job definition. Parameters are specified as a * key and value pair mapping. Parameters in a <code>SubmitJob</code> request * override any corresponding parameter defaults from the job definition.</p> */ inline SubmitJobRequest& WithParameters(const Aws::Map<Aws::String, Aws::String>& value) { SetParameters(value); return *this;} /** * <p>Additional parameters passed to the job that replace parameter substitution * placeholders that are set in the job definition. Parameters are specified as a * key and value pair mapping. Parameters in a <code>SubmitJob</code> request * override any corresponding parameter defaults from the job definition.</p> */ inline SubmitJobRequest& WithParameters(Aws::Map<Aws::String, Aws::String>&& value) { SetParameters(std::move(value)); return *this;} /** * <p>Additional parameters passed to the job that replace parameter substitution * placeholders that are set in the job definition. Parameters are specified as a * key and value pair mapping. Parameters in a <code>SubmitJob</code> request * override any corresponding parameter defaults from the job definition.</p> */ inline SubmitJobRequest& AddParameters(const Aws::String& key, const Aws::String& value) { m_parametersHasBeenSet = true; m_parameters.emplace(key, value); return *this; } /** * <p>Additional parameters passed to the job that replace parameter substitution * placeholders that are set in the job definition. Parameters are specified as a * key and value pair mapping. Parameters in a <code>SubmitJob</code> request * override any corresponding parameter defaults from the job definition.</p> */ inline SubmitJobRequest& AddParameters(Aws::String&& key, const Aws::String& value) { m_parametersHasBeenSet = true; m_parameters.emplace(std::move(key), value); return *this; } /** * <p>Additional parameters passed to the job that replace parameter substitution * placeholders that are set in the job definition. Parameters are specified as a * key and value pair mapping. Parameters in a <code>SubmitJob</code> request * override any corresponding parameter defaults from the job definition.</p> */ inline SubmitJobRequest& AddParameters(const Aws::String& key, Aws::String&& value) { m_parametersHasBeenSet = true; m_parameters.emplace(key, std::move(value)); return *this; } /** * <p>Additional parameters passed to the job that replace parameter substitution * placeholders that are set in the job definition. Parameters are specified as a * key and value pair mapping. Parameters in a <code>SubmitJob</code> request * override any corresponding parameter defaults from the job definition.</p> */ inline SubmitJobRequest& AddParameters(Aws::String&& key, Aws::String&& value) { m_parametersHasBeenSet = true; m_parameters.emplace(std::move(key), std::move(value)); return *this; } /** * <p>Additional parameters passed to the job that replace parameter substitution * placeholders that are set in the job definition. Parameters are specified as a * key and value pair mapping. Parameters in a <code>SubmitJob</code> request * override any corresponding parameter defaults from the job definition.</p> */ inline SubmitJobRequest& AddParameters(const char* key, Aws::String&& value) { m_parametersHasBeenSet = true; m_parameters.emplace(key, std::move(value)); return *this; } /** * <p>Additional parameters passed to the job that replace parameter substitution * placeholders that are set in the job definition. Parameters are specified as a * key and value pair mapping. Parameters in a <code>SubmitJob</code> request * override any corresponding parameter defaults from the job definition.</p> */ inline SubmitJobRequest& AddParameters(Aws::String&& key, const char* value) { m_parametersHasBeenSet = true; m_parameters.emplace(std::move(key), value); return *this; } /** * <p>Additional parameters passed to the job that replace parameter substitution * placeholders that are set in the job definition. Parameters are specified as a * key and value pair mapping. Parameters in a <code>SubmitJob</code> request * override any corresponding parameter defaults from the job definition.</p> */ inline SubmitJobRequest& AddParameters(const char* key, const char* value) { m_parametersHasBeenSet = true; m_parameters.emplace(key, value); return *this; } /** * <p>A list of container overrides in JSON format that specify the name of a * container in the specified job definition and the overrides it should receive. * You can override the default command for a container (that is specified in the * job definition or the Docker image) with a <code>command</code> override. You * can also override existing environment variables (that are specified in the job * definition or Docker image) on a container or add new environment variables to * it with an <code>environment</code> override.</p> */ inline const ContainerOverrides& GetContainerOverrides() const{ return m_containerOverrides; } /** * <p>A list of container overrides in JSON format that specify the name of a * container in the specified job definition and the overrides it should receive. * You can override the default command for a container (that is specified in the * job definition or the Docker image) with a <code>command</code> override. You * can also override existing environment variables (that are specified in the job * definition or Docker image) on a container or add new environment variables to * it with an <code>environment</code> override.</p> */ inline void SetContainerOverrides(const ContainerOverrides& value) { m_containerOverridesHasBeenSet = true; m_containerOverrides = value; } /** * <p>A list of container overrides in JSON format that specify the name of a * container in the specified job definition and the overrides it should receive. * You can override the default command for a container (that is specified in the * job definition or the Docker image) with a <code>command</code> override. You * can also override existing environment variables (that are specified in the job * definition or Docker image) on a container or add new environment variables to * it with an <code>environment</code> override.</p> */ inline void SetContainerOverrides(ContainerOverrides&& value) { m_containerOverridesHasBeenSet = true; m_containerOverrides = std::move(value); } /** * <p>A list of container overrides in JSON format that specify the name of a * container in the specified job definition and the overrides it should receive. * You can override the default command for a container (that is specified in the * job definition or the Docker image) with a <code>command</code> override. You * can also override existing environment variables (that are specified in the job * definition or Docker image) on a container or add new environment variables to * it with an <code>environment</code> override.</p> */ inline SubmitJobRequest& WithContainerOverrides(const ContainerOverrides& value) { SetContainerOverrides(value); return *this;} /** * <p>A list of container overrides in JSON format that specify the name of a * container in the specified job definition and the overrides it should receive. * You can override the default command for a container (that is specified in the * job definition or the Docker image) with a <code>command</code> override. You * can also override existing environment variables (that are specified in the job * definition or Docker image) on a container or add new environment variables to * it with an <code>environment</code> override.</p> */ inline SubmitJobRequest& WithContainerOverrides(ContainerOverrides&& value) { SetContainerOverrides(std::move(value)); return *this;} /** * <p>A list of node overrides in JSON format that specify the node range to target * and the container overrides for that node range.</p> */ inline const NodeOverrides& GetNodeOverrides() const{ return m_nodeOverrides; } /** * <p>A list of node overrides in JSON format that specify the node range to target * and the container overrides for that node range.</p> */ inline void SetNodeOverrides(const NodeOverrides& value) { m_nodeOverridesHasBeenSet = true; m_nodeOverrides = value; } /** * <p>A list of node overrides in JSON format that specify the node range to target * and the container overrides for that node range.</p> */ inline void SetNodeOverrides(NodeOverrides&& value) { m_nodeOverridesHasBeenSet = true; m_nodeOverrides = std::move(value); } /** * <p>A list of node overrides in JSON format that specify the node range to target * and the container overrides for that node range.</p> */ inline SubmitJobRequest& WithNodeOverrides(const NodeOverrides& value) { SetNodeOverrides(value); return *this;} /** * <p>A list of node overrides in JSON format that specify the node range to target * and the container overrides for that node range.</p> */ inline SubmitJobRequest& WithNodeOverrides(NodeOverrides&& value) { SetNodeOverrides(std::move(value)); return *this;} /** * <p>The retry strategy to use for failed jobs from this <a>SubmitJob</a> * operation. When a retry strategy is specified here, it overrides the retry * strategy defined in the job definition.</p> */ inline const RetryStrategy& GetRetryStrategy() const{ return m_retryStrategy; } /** * <p>The retry strategy to use for failed jobs from this <a>SubmitJob</a> * operation. When a retry strategy is specified here, it overrides the retry * strategy defined in the job definition.</p> */ inline void SetRetryStrategy(const RetryStrategy& value) { m_retryStrategyHasBeenSet = true; m_retryStrategy = value; } /** * <p>The retry strategy to use for failed jobs from this <a>SubmitJob</a> * operation. When a retry strategy is specified here, it overrides the retry * strategy defined in the job definition.</p> */ inline void SetRetryStrategy(RetryStrategy&& value) { m_retryStrategyHasBeenSet = true; m_retryStrategy = std::move(value); } /** * <p>The retry strategy to use for failed jobs from this <a>SubmitJob</a> * operation. When a retry strategy is specified here, it overrides the retry * strategy defined in the job definition.</p> */ inline SubmitJobRequest& WithRetryStrategy(const RetryStrategy& value) { SetRetryStrategy(value); return *this;} /** * <p>The retry strategy to use for failed jobs from this <a>SubmitJob</a> * operation. When a retry strategy is specified here, it overrides the retry * strategy defined in the job definition.</p> */ inline SubmitJobRequest& WithRetryStrategy(RetryStrategy&& value) { SetRetryStrategy(std::move(value)); return *this;} /** * <p>The timeout configuration for this <a>SubmitJob</a> operation. You can * specify a timeout duration after which AWS Batch terminates your jobs if they * have not finished. If a job is terminated due to a timeout, it is not retried. * The minimum value for the timeout is 60 seconds. This configuration overrides * any timeout configuration specified in the job definition. For array jobs, child * jobs have the same timeout configuration as the parent job. For more * information, see <a * href="http://docs.aws.amazon.com/AmazonECS/latest/developerguide/job_timeouts.html">Job * Timeouts</a> in the <i>Amazon Elastic Container Service Developer Guide</i>.</p> */ inline const JobTimeout& GetTimeout() const{ return m_timeout; } /** * <p>The timeout configuration for this <a>SubmitJob</a> operation. You can * specify a timeout duration after which AWS Batch terminates your jobs if they * have not finished. If a job is terminated due to a timeout, it is not retried. * The minimum value for the timeout is 60 seconds. This configuration overrides * any timeout configuration specified in the job definition. For array jobs, child * jobs have the same timeout configuration as the parent job. For more * information, see <a * href="http://docs.aws.amazon.com/AmazonECS/latest/developerguide/job_timeouts.html">Job * Timeouts</a> in the <i>Amazon Elastic Container Service Developer Guide</i>.</p> */ inline void SetTimeout(const JobTimeout& value) { m_timeoutHasBeenSet = true; m_timeout = value; } /** * <p>The timeout configuration for this <a>SubmitJob</a> operation. You can * specify a timeout duration after which AWS Batch terminates your jobs if they * have not finished. If a job is terminated due to a timeout, it is not retried. * The minimum value for the timeout is 60 seconds. This configuration overrides * any timeout configuration specified in the job definition. For array jobs, child * jobs have the same timeout configuration as the parent job. For more * information, see <a * href="http://docs.aws.amazon.com/AmazonECS/latest/developerguide/job_timeouts.html">Job * Timeouts</a> in the <i>Amazon Elastic Container Service Developer Guide</i>.</p> */ inline void SetTimeout(JobTimeout&& value) { m_timeoutHasBeenSet = true; m_timeout = std::move(value); } /** * <p>The timeout configuration for this <a>SubmitJob</a> operation. You can * specify a timeout duration after which AWS Batch terminates your jobs if they * have not finished. If a job is terminated due to a timeout, it is not retried. * The minimum value for the timeout is 60 seconds. This configuration overrides * any timeout configuration specified in the job definition. For array jobs, child * jobs have the same timeout configuration as the parent job. For more * information, see <a * href="http://docs.aws.amazon.com/AmazonECS/latest/developerguide/job_timeouts.html">Job * Timeouts</a> in the <i>Amazon Elastic Container Service Developer Guide</i>.</p> */ inline SubmitJobRequest& WithTimeout(const JobTimeout& value) { SetTimeout(value); return *this;} /** * <p>The timeout configuration for this <a>SubmitJob</a> operation. You can * specify a timeout duration after which AWS Batch terminates your jobs if they * have not finished. If a job is terminated due to a timeout, it is not retried. * The minimum value for the timeout is 60 seconds. This configuration overrides * any timeout configuration specified in the job definition. For array jobs, child * jobs have the same timeout configuration as the parent job. For more * information, see <a * href="http://docs.aws.amazon.com/AmazonECS/latest/developerguide/job_timeouts.html">Job * Timeouts</a> in the <i>Amazon Elastic Container Service Developer Guide</i>.</p> */ inline SubmitJobRequest& WithTimeout(JobTimeout&& value) { SetTimeout(std::move(value)); return *this;} private: Aws::String m_jobName; bool m_jobNameHasBeenSet; Aws::String m_jobQueue; bool m_jobQueueHasBeenSet; ArrayProperties m_arrayProperties; bool m_arrayPropertiesHasBeenSet; Aws::Vector<JobDependency> m_dependsOn; bool m_dependsOnHasBeenSet; Aws::String m_jobDefinition; bool m_jobDefinitionHasBeenSet; Aws::Map<Aws::String, Aws::String> m_parameters; bool m_parametersHasBeenSet; ContainerOverrides m_containerOverrides; bool m_containerOverridesHasBeenSet; NodeOverrides m_nodeOverrides; bool m_nodeOverridesHasBeenSet; RetryStrategy m_retryStrategy; bool m_retryStrategyHasBeenSet; JobTimeout m_timeout; bool m_timeoutHasBeenSet; }; } // namespace Model } // namespace Batch } // namespace Aws
51.622465
187
0.704896
[ "vector", "model" ]
7f565d738dda2b902bd762eea1c958c2870a6121
3,616
h
C
src/flag.h
burbokop/wall_e
fae63d4c63e4e7728e62af72ede7b436d6222723
[ "Apache-2.0" ]
5
2021-01-09T18:51:26.000Z
2022-02-06T11:46:41.000Z
src/flag.h
burbokop/wall_e
fae63d4c63e4e7728e62af72ede7b436d6222723
[ "Apache-2.0" ]
null
null
null
src/flag.h
burbokop/wall_e
fae63d4c63e4e7728e62af72ede7b436d6222723
[ "Apache-2.0" ]
null
null
null
#ifndef FLAG_H #define FLAG_H #include <vector> #include <string> #include <sstream> #include <list> #include <map> namespace wall_e { class flag_provider; class flag { friend flag_provider; std::string m_data; std::string m_description; bool m_bool_data; public: typedef std::pair<char, std::string> full_name; enum flag_type { bool_flag, value_flag, undefined }; private: full_name m_name; flag_type m_type = undefined; static std::string name_to_string(const full_name& v); static flag make_value_flag(const full_name &name, const std::string& data, const std::string &description); static flag make_bool_flag(const full_name &name, bool data, const std::string &description); public: static full_name name_from_string(const std::string& name); flag() {} template<typename T> friend inline flag &operator >>(flag &f, T& value) { std::istringstream(f.m_data) >> value; return f; } friend inline flag &operator >>(flag &f, bool& value) { if(f.m_type == wall_e::flag::flag_type::bool_flag) { value = f.m_bool_data; } else { std::istringstream(f.m_data) >> value; } return f; } friend inline std::ostream& operator<<(std::ostream& stream, const flag& f) { if(f.m_type == flag::bool_flag) { stream << name_to_string(f.m_name) << ": " << (f.m_bool_data ? "<present>" : "<missing>"); } else if(f.m_type == flag::value_flag) { stream << name_to_string(f.m_name) << ": [" << f.m_data << "]"; } else { stream << "<undefined>"; } return stream; } full_name name() const; std::string complex_name() const { return std::string(1, m_name.first) + ":" + m_name.second; } std::string description() const; flag_type type() const; std::string data() const; bool bool_data() const; }; class flag_provider { std::vector<std::string> m_args; std::list<flag> m_flags; std::string m_preffix = "-"; std::string m_extended_preffix = "--"; flag m_help; public: flag_provider(int argc, char **argv); flag &bool_flag(const flag::full_name &flag_name, const std::string &description); flag &value_flag(const flag::full_name &flag_name, const std::string &description, const std::string &default_value = std::string()); inline flag &bool_flag(char flag_name, const std::string &description) { return bool_flag({ flag_name, std::string() }, description); } inline flag &value_flag(char flag_name, const std::string &description, const std::string &default_value = std::string()) { return value_flag({ flag_name, std::string() }, description, default_value); } std::string preffix() const; void set_preffix(const std::string &preffix); std::string extended_preffix() const; void set_extended_preffix(const std::string &extended_preffix); std::map<std::string, flag> to_map() const; template<typename T> inline T to_container() const { if constexpr(std::is_same<T, decltype (m_flags)>::value) { return m_flags; } else { return T(m_flags.begin(), m_flags.end()); } } inline decltype (m_flags) to_list() const { return to_container<decltype (m_flags)>(); } std::vector<std::string> args() const { return m_args; }; void finish(std::ostream &stream); void print_description(std::ostream &stream); }; std::ostream& operator << (std::ostream& stream, const wall_e::flag_provider& flag_provider); } #endif // FLAG_H
31.719298
206
0.639657
[ "vector" ]
7f566b0dac082354d4c7885de03af7012bbbafd5
8,680
h
C
EventFilter/Utilities/plugins/RawEventOutputModuleForBU.h
Hemida93/cmssw
75a37059fc69b625a5e985f4f2e684cdebeeb8b5
[ "Apache-2.0" ]
null
null
null
EventFilter/Utilities/plugins/RawEventOutputModuleForBU.h
Hemida93/cmssw
75a37059fc69b625a5e985f4f2e684cdebeeb8b5
[ "Apache-2.0" ]
null
null
null
EventFilter/Utilities/plugins/RawEventOutputModuleForBU.h
Hemida93/cmssw
75a37059fc69b625a5e985f4f2e684cdebeeb8b5
[ "Apache-2.0" ]
null
null
null
#ifndef IOPool_Streamer_RawEventOutputModuleForBU_h #define IOPool_Streamer_RawEventOutputModuleForBU_h #include "FWCore/Framework/interface/EventForOutput.h" #include "FWCore/Framework/interface/one/OutputModule.h" #include "FWCore/Framework/interface/LuminosityBlockForOutput.h" #include "FWCore/ServiceRegistry/interface/Service.h" #include "FWCore/ServiceRegistry/interface/ModuleCallingContext.h" #include "FWCore/Utilities/interface/EDGetToken.h" #include "DataFormats/Common/interface/Handle.h" #include "DataFormats/FEDRawData/interface/FEDRawDataCollection.h" #include "DataFormats/FEDRawData/interface/FEDRawData.h" #include "DataFormats/FEDRawData/interface/FEDNumbering.h" #include "EventFilter/Utilities/interface/EvFDaqDirector.h" #include "IOPool/Streamer/interface/FRDEventMessage.h" #include "EventFilter/Utilities/plugins/EvFBuildingThrottle.h" #include "FWCore/Utilities/interface/Adler32Calculator.h" #include "EventFilter/Utilities/interface/crc32c.h" #include <memory> #include <vector> template <class Consumer> class RawEventOutputModuleForBU : public edm::one::OutputModule<edm::one::WatchRuns, edm::one::WatchLuminosityBlocks> { typedef unsigned int uint32; /** * Consumers are suppose to provide: * void doOutputEvent(const FRDEventMsgView& msg) * void start() * void stop() */ public: explicit RawEventOutputModuleForBU(edm::ParameterSet const& ps); ~RawEventOutputModuleForBU() override; private: void write(edm::EventForOutput const& e) override; void beginRun(edm::RunForOutput const&) override; void endRun(edm::RunForOutput const&) override; void writeRun(const edm::RunForOutput&) override {} void writeLuminosityBlock(const edm::LuminosityBlockForOutput&) override {} void beginLuminosityBlock(edm::LuminosityBlockForOutput const&) override; void endLuminosityBlock(edm::LuminosityBlockForOutput const&) override; std::unique_ptr<Consumer> templateConsumer_; std::string label_; std::string instance_; edm::EDGetTokenT<FEDRawDataCollection> token_; unsigned int numEventsPerFile_; unsigned int frdVersion_; unsigned long long totsize; unsigned long long writtensize; unsigned long long writtenSizeLast; unsigned int totevents; unsigned int index_; timeval startOfLastLumi; bool firstLumi_; }; template <class Consumer> RawEventOutputModuleForBU<Consumer>::RawEventOutputModuleForBU(edm::ParameterSet const& ps) : edm::one::OutputModuleBase::OutputModuleBase(ps), edm::one::OutputModule<edm::one::WatchRuns, edm::one::WatchLuminosityBlocks>(ps), templateConsumer_(new Consumer(ps)), label_(ps.getUntrackedParameter<std::string>("ProductLabel", "source")), instance_(ps.getUntrackedParameter<std::string>("ProductInstance", "")), token_(consumes<FEDRawDataCollection>(edm::InputTag(label_, instance_))), numEventsPerFile_(ps.getUntrackedParameter<unsigned int>("numEventsPerFile", 100)), frdVersion_(ps.getUntrackedParameter<unsigned int>("frdVersion", 6)), totsize(0LL), writtensize(0LL), writtenSizeLast(0LL), totevents(0), index_(0), firstLumi_(true) {} template <class Consumer> RawEventOutputModuleForBU<Consumer>::~RawEventOutputModuleForBU() {} template <class Consumer> void RawEventOutputModuleForBU<Consumer>::write(edm::EventForOutput const& e) { unsigned int ls = e.luminosityBlock(); if (totevents > 0 && totevents % numEventsPerFile_ == 0) { index_++; std::string filename = edm::Service<evf::EvFDaqDirector>()->getOpenRawFilePath(ls, index_); std::string destinationDir = edm::Service<evf::EvFDaqDirector>()->buBaseRunDir(); templateConsumer_->initialize(destinationDir, filename, ls); } totevents++; // serialize the FEDRawDataCollection into the format that we expect for // FRDEventMsgView objects (may be better ways to do this) edm::Handle<FEDRawDataCollection> fedBuffers; e.getByToken(token_, fedBuffers); // determine the expected size of the FRDEvent IN BYTES !!!!! assert(frdVersion_ <= FRDHeaderMaxVersion); int headerSize = FRDHeaderVersionSize[frdVersion_]; int expectedSize = headerSize; int nFeds = frdVersion_ < 3 ? 1024 : FEDNumbering::lastFEDId() + 1; for (int idx = 0; idx < nFeds; ++idx) { FEDRawData singleFED = fedBuffers->FEDData(idx); expectedSize += singleFED.size(); } totsize += expectedSize; // build the FRDEvent into a temporary buffer std::unique_ptr<std::vector<unsigned char>> workBuffer( std::make_unique<std::vector<unsigned char>>(expectedSize + 256)); uint32* bufPtr = (uint32*)(workBuffer.get()->data()); if (frdVersion_ <= 5) { *bufPtr++ = (uint32)frdVersion_; // version number only } else { uint16 flags = 0; if (!e.eventAuxiliary().isRealData()) flags |= FRDEVENT_MASK_ISGENDATA; *(uint16*)bufPtr = (uint16)(frdVersion_ & 0xffff); *((uint16*)bufPtr + 1) = flags; bufPtr++; } *bufPtr++ = (uint32)e.id().run(); *bufPtr++ = (uint32)e.luminosityBlock(); *bufPtr++ = (uint32)e.id().event(); if (frdVersion_ == 4) *bufPtr++ = 0; //64-bit event id high part if (frdVersion_ < 3) { uint32 fedsize[1024]; for (int idx = 0; idx < 1024; ++idx) { FEDRawData singleFED = fedBuffers->FEDData(idx); fedsize[idx] = singleFED.size(); //std::cout << "fed size " << singleFED.size()<< std::endl; } memcpy(bufPtr, fedsize, 1024 * sizeof(uint32)); bufPtr += 1024; } else { *bufPtr++ = expectedSize - headerSize; *bufPtr++ = 0; if (frdVersion_ <= 4) *bufPtr++ = 0; } uint32* payloadPtr = bufPtr; for (int idx = 0; idx < nFeds; ++idx) { FEDRawData singleFED = fedBuffers->FEDData(idx); if (singleFED.size() > 0) { memcpy(bufPtr, singleFED.data(), singleFED.size()); bufPtr += singleFED.size() / 4; } } if (frdVersion_ > 4) { //crc32c checksum uint32_t crc = 0; *(payloadPtr - 1) = crc32c(crc, (const unsigned char*)payloadPtr, expectedSize - headerSize); } else if (frdVersion_ >= 3) { //adler32 checksum uint32 adlera = 1; uint32 adlerb = 0; cms::Adler32((const char*)payloadPtr, expectedSize - headerSize, adlera, adlerb); *(payloadPtr - 1) = (adlerb << 16) | adlera; } // create the FRDEventMsgView and use the template consumer to write it out FRDEventMsgView msg(workBuffer.get()->data()); writtensize += msg.size(); if (!templateConsumer_->sharedMode()) templateConsumer_->doOutputEvent(msg); } template <class Consumer> void RawEventOutputModuleForBU<Consumer>::beginRun(edm::RunForOutput const&) { // edm::Service<evf::EvFDaqDirector>()->updateBuLock(1); templateConsumer_->start(); } template <class Consumer> void RawEventOutputModuleForBU<Consumer>::endRun(edm::RunForOutput const&) { templateConsumer_->stop(); } template <class Consumer> void RawEventOutputModuleForBU<Consumer>::beginLuminosityBlock(edm::LuminosityBlockForOutput const& ls) { index_ = 0; std::string filename = edm::Service<evf::EvFDaqDirector>()->getOpenRawFilePath(ls.id().luminosityBlock(), index_); std::string destinationDir = edm::Service<evf::EvFDaqDirector>()->buBaseRunDir(); std::cout << " writing to destination dir " << destinationDir << " name: " << filename << std::endl; templateConsumer_->initialize(destinationDir, filename, ls.id().luminosityBlock()); //edm::Service<evf::EvFDaqDirector>()->updateBuLock(ls.id().luminosityBlock()+1); if (!firstLumi_) { timeval now; ::gettimeofday(&now, nullptr); //long long elapsedusec = (now.tv_sec - startOfLastLumi.tv_sec)*1000000+now.tv_usec-startOfLastLumi.tv_usec; /* std::cout << "(now.tv_sec - startOfLastLumi.tv_sec) " << now.tv_sec <<"-" << startOfLastLumi.tv_sec */ /* <<" (now.tv_usec-startOfLastLumi.tv_usec) " << now.tv_usec << "-" << startOfLastLumi.tv_usec << std::endl; */ /* std::cout << "elapsedusec " << elapsedusec << " totevents " << totevents << " size (GB)" << writtensize */ /* << " rate " << (writtensize-writtenSizeLast)/elapsedusec << " MB/s" <<std::endl; */ writtenSizeLast = writtensize; ::gettimeofday(&startOfLastLumi, nullptr); //edm::Service<evf::EvFDaqDirector>()->writeLsStatisticsBU(ls.id().luminosityBlock(), totevents, totsize, elapsedusec); } else ::gettimeofday(&startOfLastLumi, nullptr); totevents = 0; totsize = 0LL; firstLumi_ = false; } template <class Consumer> void RawEventOutputModuleForBU<Consumer>::endLuminosityBlock(edm::LuminosityBlockForOutput const& ls) { // templateConsumer_->touchlock(ls.id().luminosityBlock(),basedir); templateConsumer_->endOfLS(ls.id().luminosityBlock()); } #endif
40.372093
123
0.711866
[ "vector" ]
7f5708e9043c8e1cf02550b9b66a7152fa734094
21,160
h
C
include/polarphp/utils/RawOutStream.h
PHP-OPEN-HUB/polarphp
70ff4046e280fd99d718d4761686168fa8012aa5
[ "PHP-3.01" ]
null
null
null
include/polarphp/utils/RawOutStream.h
PHP-OPEN-HUB/polarphp
70ff4046e280fd99d718d4761686168fa8012aa5
[ "PHP-3.01" ]
null
null
null
include/polarphp/utils/RawOutStream.h
PHP-OPEN-HUB/polarphp
70ff4046e280fd99d718d4761686168fa8012aa5
[ "PHP-3.01" ]
null
null
null
//===--- raw_ostream.h - Raw output stream ----------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // This source file is part of the polarphp.org open source project // // Copyright (c) 2017 - 2019 polarphp software foundation // Copyright (c) 2017 - 2019 zzu_softboy <zzu_softboy@163.com> // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://polarphp.org/LICENSE.txt for license information // See https://polarphp.org/CONTRIBUTORS.txt for the list of polarphp project authors // // Created by polarboy on 2018/05/30. #ifndef POLARPHP_UTILS_RAW_OUT_STREAM_H #define POLARPHP_UTILS_RAW_OUT_STREAM_H #include "polarphp/basic/adt/SmallVector.h" #include "polarphp/basic/adt/StringRef.h" #include <cassert> #include <cstddef> #include <cstdint> #include <cstring> #include <string> #include <system_error> namespace polar::fs { enum OpenFlags : unsigned; enum FileAccess : unsigned; enum OpenFlags : unsigned; enum CreationDisposition : unsigned; } // polar:;fs namespace polar::utils { class FormatvObjectBase; class FormatObjectBase; class FormattedString; class FormattedNumber; class FormattedBytes; using polar::basic::SmallVectorImpl; using polar::basic::SmallVector; using polar::basic::StringRef; using polar::fs::OpenFlags; /// This class implements an extremely fast bulk output stream that can *only* /// output to a stream. It does not support seeking, reopening, rewinding, line /// buffered disciplines etc. It is a simple buffer that outputs /// a chunk at a time. class RawOutStream { private: /// The buffer is handled in such a way that the buffer is /// uninitialized, unbuffered, or out of space when m_outBufCur >= /// m_outBufEnd. Thus a single comparison suffices to determine if we /// need to take the slow path to write a single character. /// /// The buffer is in one of three states: /// 1. Unbuffered (m_bufferMode == Unbuffered) /// 1. Uninitialized (m_bufferMode != Unbuffered && m_outBufStart == 0). /// 2. Buffered (m_bufferMode != Unbuffered && m_outBufStart != 0 && /// m_outBufEnd - m_outBufStart >= 1). /// /// If buffered, then the RawOutStream owns the buffer if (m_bufferMode == /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is /// managed by the subclass. /// /// If a subclass installs an external buffer using SetBuffer then it can wait /// for a \see write_impl() call to handle the data which has been put into /// this buffer. char *m_outBufStart; char *m_outBufEnd; char *m_outBufCur; enum class BufferKind { Unbuffered = 0, InternalBuffer, ExternalBuffer } m_bufferMode; public: // color order matches ANSI escape sequence, don't change enum class Colors { BLACK = 0, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, SAVEDCOLOR }; explicit RawOutStream(bool unbuffered = false) : m_bufferMode(unbuffered ? BufferKind::Unbuffered : BufferKind::InternalBuffer) { // Start out ready to flush. m_outBufStart = m_outBufEnd = m_outBufCur = nullptr; } RawOutStream(const RawOutStream &) = delete; void operator=(const RawOutStream &) = delete; virtual ~RawOutStream(); /// tell - Return the current offset with the file. uint64_t tell() const { return getCurrentPos() + getNumBytesInBuffer(); } //===--------------------------------------------------------------------===// // Configuration Interface //===--------------------------------------------------------------------===// /// Set the stream to be buffered, with an automatically determined buffer /// size. void setBuffered(); /// Set the stream to be buffered, using the specified buffer size. void setBufferSize(size_t Size) { flush(); setBufferAndMode(new char[Size], Size, BufferKind::InternalBuffer); } size_t getBufferSize() const { // If we're supposed to be buffered but haven't actually gotten around // to allocating the buffer yet, return the value that would be used. if (m_bufferMode != BufferKind::Unbuffered && m_outBufStart == nullptr) { return getPreferredBufferSize(); } // Otherwise just return the size of the allocated buffer. return m_outBufEnd - m_outBufStart; } /// Set the stream to be unbuffered. When unbuffered, the stream will flush /// after every write. This routine will also flush the buffer immediately /// when the stream is being set to unbuffered. void setUnbuffered() { flush(); setBufferAndMode(nullptr, 0, BufferKind::Unbuffered); } size_t getNumBytesInBuffer() const { return m_outBufCur - m_outBufStart; } //===--------------------------------------------------------------------===// // Data Output Interface //===--------------------------------------------------------------------===// void flush() { if (m_outBufCur != m_outBufStart) { flushNonEmpty(); } } RawOutStream &operator<<(char character) { if (m_outBufCur >= m_outBufEnd) { return write(character); } *m_outBufCur++ = character; return *this; } RawOutStream &operator<<(unsigned char character) { if (m_outBufCur >= m_outBufEnd) { return write(character); } *m_outBufCur++ = character; return *this; } RawOutStream &operator<<(signed char character) { if (m_outBufCur >= m_outBufEnd) { return write(character); } *m_outBufCur++ = character; return *this; } RawOutStream &operator<<(StringRef str) { // Inline fast path, particularly for strings with a known length. size_t size = str.getSize(); // Make sure we can use the fast path. if (size > (size_t)(m_outBufEnd - m_outBufCur)) { return write(str.getData(), size); } if (size) { memcpy(m_outBufCur, str.getData(), size); m_outBufCur += size; } return *this; } RawOutStream &operator<<(const char *str) { // Inline fast path, particularly for constant strings where a sufficiently // smart compiler will simplify strlen. return this->operator<<(StringRef(str)); } RawOutStream &operator<<(const std::string &str) { // Avoid the fast path, it would only increase code size for a marginal win. return write(str.data(), str.length()); } RawOutStream &operator<<(const SmallVectorImpl<char> &str) { return write(str.getData(), str.getSize()); } RawOutStream &operator<<(unsigned long num); RawOutStream &operator<<(long num); RawOutStream &operator<<(unsigned long long num); RawOutStream &operator<<(long long num); RawOutStream &operator<<(const void *ptr); RawOutStream &operator<<(unsigned int num) { return this->operator<<(static_cast<unsigned long>(num)); } RawOutStream &operator<<(int num) { return this->operator<<(static_cast<long>(num)); } RawOutStream &operator<<(double num); /// Output \p N in hexadecimal, without any prefix or padding. RawOutStream &writeHex(unsigned long long num); /// Output a formatted UUID with dash separators. using uuid_t = uint8_t[16]; RawOutStream &writeUuid(const uuid_t uuid); /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't /// satisfy std::isprint into an escape sequence. RawOutStream &writeEscaped(StringRef str, bool useHexEscapes = false); RawOutStream &write(unsigned char character); RawOutStream &write(const char *ptr, size_t size); // Formatted output, see the format() function in Support/Format.h. RawOutStream &operator<<(const FormatObjectBase &Fmt); // Formatted output, see the leftJustify() function in Support/Format.h. RawOutStream &operator<<(const FormattedString &); // Formatted output, see the formatHex() function in Support/Format.h. RawOutStream &operator<<(const FormattedNumber &); // Formatted output, see the formatv() function in Support/FormatVariadic.h. RawOutStream &operator<<(const FormatvObjectBase &); // Formatted output, see the format_bytes() function in Support/Format.h. RawOutStream &operator<<(const FormattedBytes &); /// indent - Insert 'numSpaces' spaces. RawOutStream &indent(unsigned numSpaces); /// write_zeros - Insert 'NumZeros' nulls. RawOutStream &writeZeros(unsigned numZeros); /// Changes the foreground color of text that will be output from this point /// forward. /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to /// change only the bold attribute, and keep colors untouched /// @param Bold bold/brighter text, default false /// @param BG if true change the background, default: change foreground /// @returns itself so it can be used within << invocations virtual RawOutStream &changeColor(enum Colors color, bool bold = false, bool bg = false) { (void)color; (void)bold; (void)bg; return *this; } /// Resets the colors to terminal defaults. Call this when you are done /// outputting colored text, or before program exit. virtual RawOutStream &resetColor() { return *this; } /// Reverses the foreground and background colors. virtual RawOutStream &reverseColor() { return *this; } /// This function determines if this stream is connected to a "tty" or /// "console" window. That is, the output would be displayed to the user /// rather than being put on a pipe or stored in a file. virtual bool isDisplayed() const { return false; } /// This function determines if this stream is displayed and supports colors. virtual bool hasColors() const { return isDisplayed(); } //===--------------------------------------------------------------------===// // Subclass Interface //===--------------------------------------------------------------------===// private: /// The is the piece of the class that is implemented by subclasses. This /// writes the \p Size bytes starting at /// \p Ptr to the underlying stream. /// /// This function is guaranteed to only be called at a point at which it is /// safe for the subclass to install a new buffer via SetBuffer. /// /// \param Ptr The start of the data to be written. For buffered streams this /// is guaranteed to be the start of the buffer. /// /// \param Size The number of bytes to be written. /// /// \invariant { Size > 0 } virtual void writeImpl(const char *ptr, size_t size) = 0; /// Return the current position within the stream, not counting the bytes /// currently in the buffer. virtual uint64_t getCurrentPos() const = 0; protected: /// Use the provided buffer as the RawOutStream buffer. This is intended for /// use only by subclasses which can arrange for the output to go directly /// into the desired output buffer, instead of being copied on each flush. void setBuffer(char *bufferStart, size_t size) { setBufferAndMode(bufferStart, size, BufferKind::ExternalBuffer); } /// Return an efficient buffer size for the underlying output mechanism. virtual size_t getPreferredBufferSize() const; /// Return the beginning of the current stream buffer, or 0 if the stream is /// unbuffered. const char *getBufferStart() const { return m_outBufStart; } //===--------------------------------------------------------------------===// // Private Interface //===--------------------------------------------------------------------===// private: /// Install the given buffer and mode. void setBufferAndMode(char *bufferStart, size_t size, BufferKind mode); /// Flush the current buffer, which is known to be non-empty. This outputs the /// currently buffered data and resets the buffer to empty. void flushNonEmpty(); /// Copy data into the buffer. Size must not be greater than the number of /// unused bytes in the buffer. void copyToBuffer(const char *ptr, size_t size); virtual void anchor(); }; /// An abstract base class for streams implementations that also support a /// pwrite operation. This is useful for code that can mostly stream out data, /// but needs to patch in a header that needs to know the output size. class RawPwriteStream : public RawOutStream { virtual void pwriteImpl(const char *ptr, size_t size, uint64_t offset) = 0; void anchor() override; public: explicit RawPwriteStream(bool unbuffered = false) : RawOutStream(unbuffered) {} void pwrite(const char *ptr, size_t size, uint64_t offset) { #ifndef NDBEBUG uint64_t pos = tell(); // /dev/null always reports a pos of 0, so we cannot perform this check // in that case. if (pos) { assert(size + offset <= pos && "We don't support extending the stream"); } #endif pwriteImpl(ptr, size, offset); } }; //===----------------------------------------------------------------------===// // File Output Streams //===----------------------------------------------------------------------===// /// A RawOutStream that writes to a file descriptor. /// class RawFdOutStream : public RawPwriteStream { int m_fd; bool m_shouldClose; bool m_supportsSeeking; #ifdef _WIN32 /// True if this fd refers to a Windows console device. Mintty and other /// terminal emulators are TTYs, but they are not consoles. bool m_isWindowsConsole = false; #endif std::error_code m_errorCode; uint64_t m_pos; /// See RawOutStream::write_impl. void writeImpl(const char *ptr, size_t size) override; void pwriteImpl(const char *Ptr, size_t Size, uint64_t offset) override; /// Return the current position within the stream, not counting the bytes /// currently in the buffer. uint64_t getCurrentPos() const override { return m_pos; } /// Determine an efficient buffer size. size_t getPreferredBufferSize() const override; /// Set the flag indicating that an output error has been encountered. void errorDetected(std::error_code errorCode) { m_errorCode = errorCode; } void anchor() override; public: /// Open the specified file for writing. If an error occurs, information /// about the error is put into EC, and the stream should be immediately /// destroyed; /// \p Flags allows optional flags to control how the file will be opened. /// /// As a special case, if Filename is "-", then the stream will use /// STDOUT_FILENO instead of opening a file. This will not close the stdout /// descriptor. RawFdOutStream(StringRef filename, std::error_code &errorCode); RawFdOutStream(StringRef filename, std::error_code &errorCode, fs::CreationDisposition disp); RawFdOutStream(StringRef filename, std::error_code &errorCode, fs::FileAccess access); RawFdOutStream(StringRef filename, std::error_code &errorCode, OpenFlags flags); RawFdOutStream(StringRef filename, std::error_code &errorCode, fs::CreationDisposition disp, fs::FileAccess access, fs::OpenFlags flags); /// FD is the file descriptor that this writes to. If ShouldClose is true, /// this closes the file when the stream is destroyed. If FD is for stdout or /// stderr, it will not be closed. RawFdOutStream(int fd, bool shouldClose, bool unbuffered = false); ~RawFdOutStream() override; /// Manually flush the stream and close the file. Note that this does not call /// fsync. void close(); bool supportsSeeking() { return m_supportsSeeking; } /// Flushes the stream and repositions the underlying file descriptor position /// to the offset specified from the beginning of the file. uint64_t seek(uint64_t off); RawOutStream &changeColor(enum Colors colors, bool bold=false, bool bg=false) override; RawOutStream &resetColor() override; RawOutStream &reverseColor() override; bool isDisplayed() const override; bool hasColors() const override; std::error_code getErrorCode() const { return m_errorCode; } /// Return the value of the flag in this RawFdOutStream indicating whether an /// output error has been encountered. /// This doesn't implicitly flush any pending output. Also, it doesn't /// guarantee to detect all errors unless the stream has been closed. bool hasError() const { return bool(m_errorCode); } /// Set the flag read by has_error() to false. If the error flag is set at the /// time when this RawOutStream's destructor is called, report_fatal_error is /// called to report the error. Use clear_error() after handling the error to /// avoid this behavior. /// /// "Errors should never pass silently. /// Unless explicitly silenced." /// - from The Zen of Python, by Tim Peters /// void clearError() { m_errorCode = std::error_code(); } }; /// This returns a reference to a RawOutStream for standard output. Use it like: /// outs() << "foo" << "bar"; RawOutStream &out_stream(); /// This returns a reference to a RawOutStream for standard error. Use it like: /// errs() << "foo" << "bar"; RawOutStream &error_stream(); /// This returns a reference to a RawOutStream which simply discards output. RawOutStream &null_stream(); //===----------------------------------------------------------------------===// // Output Stream Adaptors //===----------------------------------------------------------------------===// /// A RawOutStream that writes to an std::string. This is a simple adaptor /// class. This class does not encounter output errors. class RawStringOutStream : public RawOutStream { std::string &m_outStream; /// See RawOutStream::write_impl. void writeImpl(const char *ptr, size_t size) override; /// Return the current position within the stream, not counting the bytes /// currently in the buffer. uint64_t getCurrentPos() const override { return m_outStream.size(); } public: explicit RawStringOutStream(std::string &out) : m_outStream(out) {} ~RawStringOutStream() override; /// Flushes the stream contents to the target string and returns the string's /// reference. std::string& getStr() { flush(); return m_outStream; } }; /// A RawOutStream that writes to an SmallVector or SmallString. This is a /// simple adaptor class. This class does not encounter output errors. /// RawSvectorOutStream operates without a buffer, delegating all memory /// management to the SmallString. Thus the SmallString is always up-to-date, /// may be used directly and there is no need to call flush(). class RawSvectorOutStream : public RawPwriteStream { SmallVectorImpl<char> &m_outStream; /// See RawOutStream::write_impl. void writeImpl(const char *ptr, size_t size) override; void pwriteImpl(const char *ptr, size_t size, uint64_t offset) override; /// Return the current position within the stream. uint64_t getCurrentPos() const override; public: /// Construct a new RawSvectorOutStream. /// /// \param O The vector to write to; this should generally have at least 128 /// bytes free to avoid any extraneous memory overhead. explicit RawSvectorOutStream(SmallVectorImpl<char> &outStream) : m_outStream(outStream) { setUnbuffered(); } ~RawSvectorOutStream() override = default; void flush() = delete; /// Return a StringRef for the vector contents. StringRef getStr() { return StringRef(m_outStream.getData(), m_outStream.getSize()); } }; /// A RawOutStream that discards all output. class RawNullOutStream : public RawPwriteStream { /// See RawOutStream::write_impl. void writeImpl(const char *ptr, size_t size) override; void pwriteImpl(const char *ptr, size_t size, uint64_t offset) override; /// Return the current position within the stream, not counting the bytes /// currently in the buffer. uint64_t getCurrentPos() const override; public: explicit RawNullOutStream() = default; ~RawNullOutStream() override; }; class BufferOstream : public RawSvectorOutStream { RawOutStream &m_outStream; SmallVector<char, 0> m_buffer; virtual void anchor() override; public: BufferOstream(RawOutStream &outStream) : RawSvectorOutStream(m_buffer), m_outStream(outStream) {} ~BufferOstream() override { m_outStream << getStr(); } }; } // polar::utils #endif // POLARPHP_UTILS_RAW_OUT_STREAM_H
32.060606
86
0.646645
[ "vector" ]
7f671b3dd8728d9db5fb80df71215e7a53470fb5
7,762
c
C
gpdb/contrib/postgis/liblwgeom/cunit/cu_out_kml.c
vitessedata/gpdb.4.3.99.x
9462aad5df1bf120a2a87456b1f9574712227da4
[ "PostgreSQL", "Apache-2.0" ]
3
2017-12-10T16:41:21.000Z
2020-07-08T12:59:12.000Z
gpdb/contrib/postgis/liblwgeom/cunit/cu_out_kml.c
vitessedata/gpdb.4.3.99.x
9462aad5df1bf120a2a87456b1f9574712227da4
[ "PostgreSQL", "Apache-2.0" ]
null
null
null
gpdb/contrib/postgis/liblwgeom/cunit/cu_out_kml.c
vitessedata/gpdb.4.3.99.x
9462aad5df1bf120a2a87456b1f9574712227da4
[ "PostgreSQL", "Apache-2.0" ]
4
2017-12-10T16:41:35.000Z
2020-11-28T12:20:30.000Z
/********************************************************************** * $Id: cu_out_kml.c 9485 2012-03-13 16:23:38Z pramsey $ * * PostGIS - Spatial Types for PostgreSQL * http://postgis.refractions.net * Copyright 2010 Olivier Courtin <olivier.courtin@oslandia.com> * * This is free software; you can redistribute and/or modify it under * the terms of the GNU General Public Licence. See the COPYING file. * **********************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "CUnit/Basic.h" #include "liblwgeom_internal.h" #include "cu_tester.h" static void do_kml_test(char * in, char * out, int precision) { LWGEOM *g; char * h; g = lwgeom_from_wkt(in, LW_PARSER_CHECK_NONE); h = lwgeom_to_kml2(g, precision, ""); if (strcmp(h, out)) fprintf(stderr, "\nIn: %s\nOut: %s\nTheo: %s\n", in, h, out); CU_ASSERT_STRING_EQUAL(h, out); lwgeom_free(g); lwfree(h); } static void do_kml_unsupported(char * in, char * out) { LWGEOM *g; char *h; g = lwgeom_from_wkt(in, LW_PARSER_CHECK_NONE); h = lwgeom_to_kml2(g, 0, ""); if (strcmp(cu_error_msg, out)) fprintf(stderr, "\nIn: %s\nOut: %s\nTheo: %s\n", in, cu_error_msg, out); CU_ASSERT_STRING_EQUAL(out, cu_error_msg); cu_error_msg_reset(); lwfree(h); lwgeom_free(g); } static void do_kml_test_prefix(char * in, char * out, int precision, const char *prefix) { LWGEOM *g; char * h; g = lwgeom_from_wkt(in, LW_PARSER_CHECK_NONE); h = lwgeom_to_kml2(g, precision, prefix); if (strcmp(h, out)) fprintf(stderr, "\nPrefix: %s\nIn: %s\nOut: %s\nTheo: %s\n", prefix, in, h, out); CU_ASSERT_STRING_EQUAL(h, out); lwgeom_free(g); lwfree(h); } static void out_kml_test_precision(void) { /* 0 precision, i.e a round */ do_kml_test( "POINT(1.1111111111111 1.1111111111111)", "<Point><coordinates>1,1</coordinates></Point>", 0); /* 3 digits precision */ do_kml_test( "POINT(1.1111111111111 1.1111111111111)", "<Point><coordinates>1.111,1.111</coordinates></Point>", 3); /* 9 digits precision */ do_kml_test( "POINT(1.2345678901234 1.2345678901234)", "<Point><coordinates>1.23456789,1.23456789</coordinates></Point>", 8); /* huge data */ do_kml_test( "POINT(1E300 -1E300)", "<Point><coordinates>1e+300,-1e+300</coordinates></Point>", 0); } static void out_kml_test_dims(void) { /* 3D */ do_kml_test( "POINT(0 1 2)", "<Point><coordinates>0,1,2</coordinates></Point>", 0); /* 3DM */ do_kml_test( "POINTM(0 1 2)", "<Point><coordinates>0,1</coordinates></Point>", 0); /* 4D */ do_kml_test( "POINT(0 1 2 3)", "<Point><coordinates>0,1,2</coordinates></Point>", 0); } static void out_kml_test_geoms(void) { /* Linestring */ do_kml_test( "LINESTRING(0 1,2 3,4 5)", "<LineString><coordinates>0,1 2,3 4,5</coordinates></LineString>", 0); /* Polygon */ do_kml_test( "POLYGON((0 1,2 3,4 5,0 1))", "<Polygon><outerBoundaryIs><LinearRing><coordinates>0,1 2,3 4,5 0,1</coordinates></LinearRing></outerBoundaryIs></Polygon>", 0); /* Polygon - with internal ring */ do_kml_test( "POLYGON((0 1,2 3,4 5,0 1),(6 7,8 9,10 11,6 7))", "<Polygon><outerBoundaryIs><LinearRing><coordinates>0,1 2,3 4,5 0,1</coordinates></LinearRing></outerBoundaryIs><innerBoundaryIs><LinearRing><coordinates>6,7 8,9 10,11 6,7</coordinates></LinearRing></innerBoundaryIs></Polygon>", 0); /* MultiPoint */ do_kml_test( "MULTIPOINT(0 1,2 3)", "<MultiGeometry><Point><coordinates>0,1</coordinates></Point><Point><coordinates>2,3</coordinates></Point></MultiGeometry>", 0); /* MultiLine */ do_kml_test( "MULTILINESTRING((0 1,2 3,4 5),(6 7,8 9,10 11))", "<MultiGeometry><LineString><coordinates>0,1 2,3 4,5</coordinates></LineString><LineString><coordinates>6,7 8,9 10,11</coordinates></LineString></MultiGeometry>", 0); /* MultiPolygon */ do_kml_test( "MULTIPOLYGON(((0 1,2 3,4 5,0 1)),((6 7,8 9,10 11,6 7)))", "<MultiGeometry><Polygon><outerBoundaryIs><LinearRing><coordinates>0,1 2,3 4,5 0,1</coordinates></LinearRing></outerBoundaryIs></Polygon><Polygon><outerBoundaryIs><LinearRing><coordinates>6,7 8,9 10,11 6,7</coordinates></LinearRing></outerBoundaryIs></Polygon></MultiGeometry>", 0); /* GeometryCollection */ do_kml_unsupported( "GEOMETRYCOLLECTION(POINT(0 1))", "lwgeom_to_kml2: 'GeometryCollection' geometry type not supported"); /* CircularString */ do_kml_unsupported( "CIRCULARSTRING(-2 0,0 2,2 0,0 2,2 4)", "lwgeom_to_kml2: 'CircularString' geometry type not supported"); /* CompoundCurve */ do_kml_unsupported( "COMPOUNDCURVE(CIRCULARSTRING(0 0,1 1,1 0),(1 0,0 1))", "lwgeom_to_kml2: 'CompoundCurve' geometry type not supported"); /* CurvePolygon */ do_kml_unsupported( "CURVEPOLYGON(CIRCULARSTRING(-2 0,-1 -1,0 0,1 -1,2 0,0 2,-2 0),(-1 0,0 0.5,1 0,0 1,-1 0))", "lwgeom_to_kml2: 'CurvePolygon' geometry type not supported"); /* MultiCurve */ do_kml_unsupported( "MULTICURVE((5 5,3 5,3 3,0 3),CIRCULARSTRING(0 0,2 1,2 2))", "lwgeom_to_kml2: 'MultiCurve' geometry type not supported"); /* MultiSurface */ do_kml_unsupported( "MULTISURFACE(CURVEPOLYGON(CIRCULARSTRING(-2 0,-1 -1,0 0,1 -1,2 0,0 2,-2 0),(-1 0,0 0.5,1 0,0 1,-1 0)),((7 8,10 10,6 14,4 11,7 8)))", "lwgeom_to_kml2: 'MultiSurface' geometry type not supported"); } static void out_kml_test_prefix(void) { /* Linestring */ do_kml_test_prefix( "LINESTRING(0 1,2 3,4 5)", "<kml:LineString><kml:coordinates>0,1 2,3 4,5</kml:coordinates></kml:LineString>", 0, "kml:"); /* Polygon */ do_kml_test_prefix( "POLYGON((0 1,2 3,4 5,0 1))", "<kml:Polygon><kml:outerBoundaryIs><kml:LinearRing><kml:coordinates>0,1 2,3 4,5 0,1</kml:coordinates></kml:LinearRing></kml:outerBoundaryIs></kml:Polygon>", 0, "kml:"); /* Polygon - with internal ring */ do_kml_test_prefix( "POLYGON((0 1,2 3,4 5,0 1),(6 7,8 9,10 11,6 7))", "<kml:Polygon><kml:outerBoundaryIs><kml:LinearRing><kml:coordinates>0,1 2,3 4,5 0,1</kml:coordinates></kml:LinearRing></kml:outerBoundaryIs><kml:innerBoundaryIs><kml:LinearRing><kml:coordinates>6,7 8,9 10,11 6,7</kml:coordinates></kml:LinearRing></kml:innerBoundaryIs></kml:Polygon>", 0, "kml:"); /* MultiPoint */ do_kml_test_prefix( "MULTIPOINT(0 1,2 3)", "<kml:MultiGeometry><kml:Point><kml:coordinates>0,1</kml:coordinates></kml:Point><kml:Point><kml:coordinates>2,3</kml:coordinates></kml:Point></kml:MultiGeometry>", 0, "kml:"); /* MultiLine */ do_kml_test_prefix( "MULTILINESTRING((0 1,2 3,4 5),(6 7,8 9,10 11))", "<kml:MultiGeometry><kml:LineString><kml:coordinates>0,1 2,3 4,5</kml:coordinates></kml:LineString><kml:LineString><kml:coordinates>6,7 8,9 10,11</kml:coordinates></kml:LineString></kml:MultiGeometry>", 0, "kml:"); /* MultiPolygon */ do_kml_test_prefix( "MULTIPOLYGON(((0 1,2 3,4 5,0 1)),((6 7,8 9,10 11,6 7)))", "<kml:MultiGeometry><kml:Polygon><kml:outerBoundaryIs><kml:LinearRing><kml:coordinates>0,1 2,3 4,5 0,1</kml:coordinates></kml:LinearRing></kml:outerBoundaryIs></kml:Polygon><kml:Polygon><kml:outerBoundaryIs><kml:LinearRing><kml:coordinates>6,7 8,9 10,11 6,7</kml:coordinates></kml:LinearRing></kml:outerBoundaryIs></kml:Polygon></kml:MultiGeometry>", 0, "kml:"); } /* ** Used by test harness to register the tests in this file. */ CU_TestInfo out_kml_tests[] = { PG_TEST(out_kml_test_precision), PG_TEST(out_kml_test_dims), PG_TEST(out_kml_test_geoms), PG_TEST(out_kml_test_prefix), CU_TEST_INFO_NULL }; CU_SuiteInfo out_kml_suite = {"KML Out Suite", NULL, NULL, out_kml_tests};
31.298387
355
0.651894
[ "geometry", "3d" ]
7f6fff64d757587ff0cd049f271035b76f4dc513
2,657
h
C
libs/QRealFourier/headers/qfouriertransformer.h
mfkiwl/Serial-Studio
f669d7b7e5f9a6d22f9d4bc26a4500c3feb08c3a
[ "MIT" ]
2,496
2020-11-12T01:17:00.000Z
2022-03-30T06:03:58.000Z
libs/QRealFourier/headers/qfouriertransformer.h
mfkiwl/Serial-Studio
f669d7b7e5f9a6d22f9d4bc26a4500c3feb08c3a
[ "MIT" ]
75
2021-01-14T16:21:21.000Z
2022-03-14T23:16:09.000Z
libs/QRealFourier/headers/qfouriertransformer.h
mfkiwl/Serial-Studio
f669d7b7e5f9a6d22f9d4bc26a4500c3feb08c3a
[ "MIT" ]
287
2021-01-13T20:32:12.000Z
2022-03-30T09:39:31.000Z
/*********************************************************************** qfouriertransformer.h - Header file for QFourierTransformer Facade class for calculating FFTs from a set of samples. ************************************************************************ This file is part of QRealFourier. QRealFourier is free software: you can redistribute it and/or modify it under the terms of the Lesser GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Foobar 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 Lesser GNU General Public License for more details. You should have received a copy of the Lesser GNU General Public License along with Foobar. If not, see <http://www.gnu.org/licenses/>. ************************************************************************ Copyright © 2012 - 2013 Christoph Stallmann, University of Pretoria Developer: Christoph Stallmann University of Pretoria Department of Computer Science http://www.visore.org http://sourceforge.net/projects/qrealfourier http://github.com/visore/QRealFourier qrealfourier@visore.org qrealfourier@gmail.com ***********************************************************************/ #ifndef QFOURIERTRANSFORMER_H #define QFOURIERTRANSFORMER_H #include "qfouriercalculator.h" #include "qwindowfunction.h" #include "qcomplexnumber.h" #include <QMap> typedef QVector<QComplexFloat> QComplexVector; class QFourierTransformer { public: enum Direction { Forward = 0, Inverse = 1 }; enum Initialization { VariableSize = 0, FixedSize = 1, InvalidSize = 2 }; public: QFourierTransformer(int size = 0, QString functionName = ""); ~QFourierTransformer(); Initialization setSize(int size); bool setWindowFunction(QString functionName); QStringList windowFunctions(); void transform(float input[], float output[], Direction direction = QFourierTransformer::Forward); void forwardTransform(float *input, float *output); void inverseTransform(float input[], float output[]); void rescale(float input[]); void conjugate(float input[]); QComplexVector toComplex(float input[]); protected: void initialize(); int sizeToKey(int size); bool isValidSize(int value); private: int mSize; QMap<int, QFourierCalculator*> mFixedCalculators; QFourierCalculator* mVariableCalculator; QFourierCalculator *mCalculator; QStringList mWindowFunctions; QWindowFunction<float> *mWindowFunction; }; #endif
25.548077
100
0.685736
[ "transform" ]
7f727c53e300255665cbaa6af3f174802abe3c4e
10,729
c
C
LCube/Src/Neural_Network/dct.c
Diject/Ledokall
41ec70ed0879f5d2bd699f5f3a2d6a5ebe924814
[ "Apache-2.0" ]
2
2021-03-24T13:58:37.000Z
2021-03-25T17:01:36.000Z
LCube/Src/Neural_Network/dct.c
Diject/Ledokall
41ec70ed0879f5d2bd699f5f3a2d6a5ebe924814
[ "Apache-2.0" ]
null
null
null
LCube/Src/Neural_Network/dct.c
Diject/Ledokall
41ec70ed0879f5d2bd699f5f3a2d6a5ebe924814
[ "Apache-2.0" ]
null
null
null
/** ****************************************************************************** * @file dct.c * @author MCD Application Team * @brief Generation and processing functions of the Discrete Cosine Transform ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Software License Agreement * SLA0055, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/resource/en/license_agreement/dm00251784.pdf * ****************************************************************************** */ #include "dct.h" #ifndef M_PI #define M_PI 3.14159265358979323846264338327950288 /*!< pi */ #endif /** * @defgroup groupDCT Discrete Cosine Transform * @brief Generation and processing functions of the Discrete Cosine Transform * * Implementation based on SciPy's scipy.fftpack.dct. * - https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.fftpack.dct.html * - https://en.wikipedia.org/wiki/Discrete_cosine_transform * - https://github.com/ARM-software/ML-KWS-for-MCU/blob/master/Deployment/Source/MFCC/mfcc.cpp * - https://github.com/tensorflow/tensorflow/blob/r1.13/tensorflow/python/ops/signal/mfcc_ops.py * * \par Example * \code * float32_t pDCTCoefsBuffer[13 * 128]; * float32_t pOutBuffer[13]; * DCT_InstanceTypeDef S_DCT; * * S_DCT.NumFilters = 13; * S_DCT.NumInputs = 128; * S_DCT.Type = DCT_TYPE_III; * S_DCT.RemoveDCTZero = 1; * S_DCT.pDCTCoefs = pDCTCoefsBuffer; * * if (DCT_Init(&S_DCT) != 0) * { * Error_Handler(); * } * * DCT(&S_DCT, pInBuffer, pOutBuffer); * * \endcode * * \par DCT type-II * <pre> * y = scipy.fftpack.dct(x, type=2)[:n_filters] * N-1 * y[k] = 2.0 * sum cos(pi / N * (n + 0.5) * k), 0 <= k < N. * n=0 * </pre> * *\par DCT type-II normalized * <pre> * y = scipy.fftpack.dct(x, type=2, norm='ortho')[:n_filters] * N-1 * y[k] = 2 * sum x[n] * cos(pi / N * k * (n + 0.5)), 0 <= k < N. * n=0 * If norm='ortho', y[k] is multiplied by a scaling factor f: * f = sqrt(1/(4*N)) if k = 0, * f = sqrt(1/(2*N)) otherwise. * </pre> * * \par DCT type-II scaled * * All bins are scaled to match the DCT operation used in TensorFlow's MFCC. * <pre> * N-1 * y[k] = sqrt(1/(2*N)) * sum x[n] * cos(pi / N * k * (n + 0.5)), 0 <= k < N. * n=0 * </pre> * * \par DCT type-III * <pre> * y = scipy.fftpack.dct(x, type=3)[:n_filters] * N-1 * y[k] = x[0] + 2 * sum x[n]*cos(pi*(k+0.5)*n/N), 0 <= k < N. * n=1 * </pre> * * \par DCT type-III normalized * <pre> * y = librosa.filters.dct(n_filters, n_inputs) * = scipy.fftpack.dct(x, type=3, norm='ortho')[:n_filters] * N-1 * y[k] = x[0] / sqrt(N) + sqrt(2/N) * sum x[n]*cos(pi*(k+0.5)*n/N) * n=1 * </pre> * @{ */ /* Uncomment out to use naive DCT implementations instead of cos tables */ // #define USE_NAIVE_DCT /** * @brief Initialization function for the floating-point DCT operation. * * @param *S points to an instance of the floating-point DCT structure. * @return 0 if successful or -1 if there is an error. */ int32_t DCT_Init(DCT_InstanceTypeDef *S) { int32_t status; uint32_t n_filters = S->NumFilters; uint32_t n_inputs = S->NumInputs; float32_t *M = S->pDCTCoefs; float64_t sample; float64_t normalizer; uint32_t shift; /* RemoveDCTZero only implemented for DCT Type-III non-normalized with COS tables */ if (S->RemoveDCTZero != 0) { if (S->Type != DCT_TYPE_III) { status = -1; return status; } shift = 1; } else { shift = 0; } /* Compute DCT matrix coefficients */ switch (S->Type) { case DCT_TYPE_II: for (uint32_t i = 0; i < n_filters; i++) { for (uint32_t j = 0; j < n_inputs; j++) { sample = M_PI * (j + 0.5) / n_inputs; M[i * n_inputs + j] = 2.0 * cos(sample * i); } } status = 0; break; case DCT_TYPE_II_ORTHO: normalizer = 2.0 * sqrt(1.0 / (4 * n_inputs)); for (uint32_t i = 0; i < n_inputs; i++) { M[i] = normalizer; } normalizer = 2.0 / sqrt(2 * n_inputs); for (uint32_t i = 0; i < n_filters; i++) { for (uint32_t j = 1; j < n_inputs; j++) { sample = M_PI * (j + 0.5) / n_inputs; M[i * n_inputs + j] = normalizer * cos(sample * i); } } status = 0; break; case DCT_TYPE_II_SCALED: normalizer = 2.0 / sqrt(2 * n_inputs); for (uint32_t i = 0; i < n_filters; i++) { for (uint32_t j = 0; j < n_inputs; j++) { sample = M_PI * (j + 0.5) / n_inputs; M[i * n_inputs + j] = normalizer * cos(sample * i); } } status = 0; break; case DCT_TYPE_III: for (uint32_t i = 0; i < n_filters; i++) { sample = M_PI * (i + shift + 0.5) / n_inputs; for (uint32_t j = 0; j < n_inputs; j++) { M[i * n_inputs + j] = 2.0 * cos(sample * j); } } status = 0; break; case DCT_TYPE_III_ORTHO: normalizer = 1.0 / sqrt(n_inputs); for (uint32_t i = 0; i < n_inputs; i++) { M[i] = normalizer; } normalizer = sqrt(2.0 / n_inputs); for (uint32_t i = 0; i < n_filters; i++) { for (uint32_t j = 1; j < n_inputs; j++) { sample = M_PI * (i + 0.5) / n_inputs; M[i * n_inputs + j] = cos(sample * j) * normalizer; } } status = 0; break; default: /* Other DCT types not implemented or unsupported */ status = -1; break; } return status; } /** * @brief Processing function for the floating-point DCT. * * @param *S points to an instance of the floating-point DCT structure. * @param *pIn points to state buffer. * @param *pOut points to the output buffer. * @return none. */ void DCT(DCT_InstanceTypeDef *S, float32_t *pIn, float32_t *pOut) { float32_t sum; uint32_t n_inputs = S->NumInputs; uint32_t n_filters = S->NumFilters; #ifndef USE_NAIVE_DCT float32_t *cosFact = S->pDCTCoefs; uint32_t row; #else float32_t normalizer; #endif /* USE_NAIVE_DCT */ /* Compute DCT matrix coefficients */ switch (S->Type) { case DCT_TYPE_II: #ifdef USE_NAIVE_DCT for (uint32_t k = 0; k < n_filters; k++) { sum = 0.0f; for (uint32_t n = 0; n < n_inputs; n++) { sum += pIn[n] * cos(M_PI * k * (n + 0.5) / n_inputs); } pOut[k] = 2.0f * sum; } #else for (uint32_t k = 0; k < n_filters; k++) { pOut[k] = 0.0f; row = k * n_inputs; for (uint32_t n = 0; n < n_inputs; n++) { // pOut[k] += pIn[n] * 2.0f * cos(M_PI * k * (n + 0.5) / n_inputs); pOut[k] += pIn[n] * cosFact[row + n]; } } #endif /* USE_NAIVE_DCT */ break; case DCT_TYPE_II_ORTHO: #ifdef USE_NAIVE_DCT normalizer = sqrtf(1.0f / (4 * n_inputs)); sum = 0.0f; for (uint32_t n = 0; n < n_inputs; n++) { sum += pIn[n]; } pOut[0] = normalizer * 2.0f * sum; normalizer = sqrtf(1.0f / (2 * n_inputs)); for (uint32_t k = 1; k < n_filters; k++) { sum = 0.0f; for (uint32_t n = 0; n < n_inputs; n++) { sum += pIn[n] * cos(M_PI * k * (n + 0.5) / n_inputs); } pOut[k] = normalizer * 2.0f * sum; } #else sum = 0.0f; for (uint32_t n = 0; n < n_inputs; n++) { sum += pIn[n]; } pOut[0] = cosFact[0] * sum; for (uint32_t k = 1; k < n_filters; k++) { pOut[k] = 0.0f; row = k * n_inputs; for (uint32_t n = 0; n < n_inputs; n++) { // pOut[k] += 2.0f / sqrtf(2 * n_inputs) * pIn[n] * cosf(M_PI * k * (n + 0.5) / n_inputs); pOut[k] += pIn[n] * cosFact[row + n]; } } #endif /* USE_NAIVE_DCT */ break; case DCT_TYPE_II_SCALED: #ifdef USE_NAIVE_DCT normalizer = 2.0f / sqrt(2 * n_inputs); for (uint32_t k = 0; k < n_filters; k++) { sum = 0.0f; for (uint32_t n = 0; n < n_inputs; n++) { sum += pIn[n] * cos(M_PI * k * (n + 0.5) / n_inputs); } pOut[k] = normalizer * sum; } #else for (uint32_t k = 0; k < n_filters; k++) { pOut[k] = 0.0f; row = k * n_inputs; for (uint32_t n = 0; n < n_inputs; n++) { // pOut[k] += pIn[n] * 2.0f * cos(M_PI * k * (n + 0.5) / n_inputs); pOut[k] += pIn[n] * cosFact[row + n]; } } #endif /* USE_NAIVE_DCT */ break; case DCT_TYPE_III: #ifdef USE_NAIVE_DCT for (uint32_t k = 0; k < n_filters; k++) { sum = 0.0f; for (uint32_t n = 1; n < n_inputs; n++) { sum += pIn[n] * cos(M_PI * (k + 0.5) * n / n_inputs); } pOut[k] = pIn[0] + 2.0f * sum; } #else for (uint32_t k = 0; k < n_filters; k++) { sum = 0.0f; row = k * n_inputs; for (uint32_t n = 1; n < n_inputs; n++) { // sum += pIn[n] * cos(M_PI * (k + 0.5) * n / n_inputs); sum += pIn[n] * cosFact[row + n]; } pOut[k] = pIn[0] + sum; } #endif /* USE_NAIVE_DCT */ break; case DCT_TYPE_III_ORTHO: #ifdef USE_NAIVE_DCT for (uint32_t k = 0; k < n_filters; k++) { sum = 0.0f; for (uint32_t n = 1; n < n_inputs; n++) { sum += pIn[n] * cos(M_PI * (k + 0.5) * n / n_inputs); } pOut[k] = pIn[0] / sqrtf(n_inputs) + sqrtf(2.0 / n_inputs) * sum; } #else sum = pIn[0] * cosFact[0]; for (uint32_t k = 0; k < n_filters; k++) { pOut[k] = sum; row = k * n_inputs; for (uint32_t n = 1; n < n_inputs; n++) { // pOut[k] += pIn[n] * sqrtf(2.0 / n_inputs) * cos(M_PI * (k + 0.5) * n / n_inputs); pOut[k] += pIn[n] * cosFact[row + n]; } } #endif /* USE_NAIVE_DCT */ break; default: break; } } /** * @} end of groupDCT */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
26.689055
100
0.493802
[ "transform" ]
7f7397e579e1c5d7e50a409ca6e0a00af46904e7
2,221
h
C
oobe_config/save_oobe_config_usb.h
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
5
2019-01-19T15:38:48.000Z
2021-10-06T03:59:46.000Z
oobe_config/save_oobe_config_usb.h
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
null
null
null
oobe_config/save_oobe_config_usb.h
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2019-02-15T23:05:30.000Z
2019-02-15T23:05:30.000Z
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef OOBE_CONFIG_SAVE_OOBE_CONFIG_USB_H_ #define OOBE_CONFIG_SAVE_OOBE_CONFIG_USB_H_ #include <string> #include <base/files/file_path.h> namespace oobe_config { // An object of this class has these responsibilities: // // - Sign the oobe config file and write it into // unencrypted/oobe_auto_config/config.json.sig on the device. // - Sign the enrollment domain file if there is any and write it into // unencrypted/oobe_auto_config/enrollment_domain.sig on the device. // - Sign the path to the stateful partition block device in /dev/disk/by-id and // write it into unencrypted/oobe_auto_config/usb_device_path.sig. // - Copy the public key to the device's stateful at // unencrypted/oobe_auto_config/validation_key.pub class SaveOobeConfigUsb { public: SaveOobeConfigUsb(const base::FilePath& device_stateful_dir, const base::FilePath& usb_stateful_dir, const base::FilePath& device_ids_dir, const base::FilePath& usb_device, const base::FilePath& private_key_file, const base::FilePath& public_key_file); virtual ~SaveOobeConfigUsb() = default; // Does the main job of signing config and enrollment domain, and copying the // public key to the device's stateful partition. virtual bool Save() const; protected: virtual bool SaveInternal() const; // Enumerates /dev/disk/by-id/ to find which persistent disk identifier // |usb_device_| corresponds to. virtual bool FindPersistentMountDevice(base::FilePath* device) const; // Clean up whatever file we created on the device's stateful partition. virtual void Cleanup() const; private: friend class SaveOobeConfigUsbTest; base::FilePath device_stateful_; base::FilePath usb_stateful_; base::FilePath device_ids_dir_; base::FilePath usb_device_; base::FilePath private_key_file_; base::FilePath public_key_file_; DISALLOW_COPY_AND_ASSIGN(SaveOobeConfigUsb); }; } // namespace oobe_config #endif // OOBE_CONFIG_SAVE_OOBE_CONFIG_USB_H_
34.703125
80
0.742458
[ "object" ]
7f75d0d68c49b53248a950a837ec291c30f206d9
9,486
h
C
aws-cpp-sdk-lambda/include/aws/lambda/model/FunctionEventInvokeConfig.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-lambda/include/aws/lambda/model/FunctionEventInvokeConfig.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-lambda/include/aws/lambda/model/FunctionEventInvokeConfig.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/lambda/Lambda_EXPORTS.h> #include <aws/core/utils/DateTime.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/lambda/model/DestinationConfig.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace Lambda { namespace Model { class AWS_LAMBDA_API FunctionEventInvokeConfig { public: FunctionEventInvokeConfig(); FunctionEventInvokeConfig(Aws::Utils::Json::JsonView jsonValue); FunctionEventInvokeConfig& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The date and time that the configuration was last updated.</p> */ inline const Aws::Utils::DateTime& GetLastModified() const{ return m_lastModified; } /** * <p>The date and time that the configuration was last updated.</p> */ inline bool LastModifiedHasBeenSet() const { return m_lastModifiedHasBeenSet; } /** * <p>The date and time that the configuration was last updated.</p> */ inline void SetLastModified(const Aws::Utils::DateTime& value) { m_lastModifiedHasBeenSet = true; m_lastModified = value; } /** * <p>The date and time that the configuration was last updated.</p> */ inline void SetLastModified(Aws::Utils::DateTime&& value) { m_lastModifiedHasBeenSet = true; m_lastModified = std::move(value); } /** * <p>The date and time that the configuration was last updated.</p> */ inline FunctionEventInvokeConfig& WithLastModified(const Aws::Utils::DateTime& value) { SetLastModified(value); return *this;} /** * <p>The date and time that the configuration was last updated.</p> */ inline FunctionEventInvokeConfig& WithLastModified(Aws::Utils::DateTime&& value) { SetLastModified(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the function.</p> */ inline const Aws::String& GetFunctionArn() const{ return m_functionArn; } /** * <p>The Amazon Resource Name (ARN) of the function.</p> */ inline bool FunctionArnHasBeenSet() const { return m_functionArnHasBeenSet; } /** * <p>The Amazon Resource Name (ARN) of the function.</p> */ inline void SetFunctionArn(const Aws::String& value) { m_functionArnHasBeenSet = true; m_functionArn = value; } /** * <p>The Amazon Resource Name (ARN) of the function.</p> */ inline void SetFunctionArn(Aws::String&& value) { m_functionArnHasBeenSet = true; m_functionArn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of the function.</p> */ inline void SetFunctionArn(const char* value) { m_functionArnHasBeenSet = true; m_functionArn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of the function.</p> */ inline FunctionEventInvokeConfig& WithFunctionArn(const Aws::String& value) { SetFunctionArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the function.</p> */ inline FunctionEventInvokeConfig& WithFunctionArn(Aws::String&& value) { SetFunctionArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the function.</p> */ inline FunctionEventInvokeConfig& WithFunctionArn(const char* value) { SetFunctionArn(value); return *this;} /** * <p>The maximum number of times to retry when the function returns an error.</p> */ inline int GetMaximumRetryAttempts() const{ return m_maximumRetryAttempts; } /** * <p>The maximum number of times to retry when the function returns an error.</p> */ inline bool MaximumRetryAttemptsHasBeenSet() const { return m_maximumRetryAttemptsHasBeenSet; } /** * <p>The maximum number of times to retry when the function returns an error.</p> */ inline void SetMaximumRetryAttempts(int value) { m_maximumRetryAttemptsHasBeenSet = true; m_maximumRetryAttempts = value; } /** * <p>The maximum number of times to retry when the function returns an error.</p> */ inline FunctionEventInvokeConfig& WithMaximumRetryAttempts(int value) { SetMaximumRetryAttempts(value); return *this;} /** * <p>The maximum age of a request that Lambda sends to a function for * processing.</p> */ inline int GetMaximumEventAgeInSeconds() const{ return m_maximumEventAgeInSeconds; } /** * <p>The maximum age of a request that Lambda sends to a function for * processing.</p> */ inline bool MaximumEventAgeInSecondsHasBeenSet() const { return m_maximumEventAgeInSecondsHasBeenSet; } /** * <p>The maximum age of a request that Lambda sends to a function for * processing.</p> */ inline void SetMaximumEventAgeInSeconds(int value) { m_maximumEventAgeInSecondsHasBeenSet = true; m_maximumEventAgeInSeconds = value; } /** * <p>The maximum age of a request that Lambda sends to a function for * processing.</p> */ inline FunctionEventInvokeConfig& WithMaximumEventAgeInSeconds(int value) { SetMaximumEventAgeInSeconds(value); return *this;} /** * <p>A destination for events after they have been sent to a function for * processing.</p> <p class="title"> <b>Destinations</b> </p> <ul> <li> <p> * <b>Function</b> - The Amazon Resource Name (ARN) of a Lambda function.</p> </li> * <li> <p> <b>Queue</b> - The ARN of an SQS queue.</p> </li> <li> <p> <b>Topic</b> * - The ARN of an SNS topic.</p> </li> <li> <p> <b>Event Bus</b> - The ARN of an * Amazon EventBridge event bus.</p> </li> </ul> */ inline const DestinationConfig& GetDestinationConfig() const{ return m_destinationConfig; } /** * <p>A destination for events after they have been sent to a function for * processing.</p> <p class="title"> <b>Destinations</b> </p> <ul> <li> <p> * <b>Function</b> - The Amazon Resource Name (ARN) of a Lambda function.</p> </li> * <li> <p> <b>Queue</b> - The ARN of an SQS queue.</p> </li> <li> <p> <b>Topic</b> * - The ARN of an SNS topic.</p> </li> <li> <p> <b>Event Bus</b> - The ARN of an * Amazon EventBridge event bus.</p> </li> </ul> */ inline bool DestinationConfigHasBeenSet() const { return m_destinationConfigHasBeenSet; } /** * <p>A destination for events after they have been sent to a function for * processing.</p> <p class="title"> <b>Destinations</b> </p> <ul> <li> <p> * <b>Function</b> - The Amazon Resource Name (ARN) of a Lambda function.</p> </li> * <li> <p> <b>Queue</b> - The ARN of an SQS queue.</p> </li> <li> <p> <b>Topic</b> * - The ARN of an SNS topic.</p> </li> <li> <p> <b>Event Bus</b> - The ARN of an * Amazon EventBridge event bus.</p> </li> </ul> */ inline void SetDestinationConfig(const DestinationConfig& value) { m_destinationConfigHasBeenSet = true; m_destinationConfig = value; } /** * <p>A destination for events after they have been sent to a function for * processing.</p> <p class="title"> <b>Destinations</b> </p> <ul> <li> <p> * <b>Function</b> - The Amazon Resource Name (ARN) of a Lambda function.</p> </li> * <li> <p> <b>Queue</b> - The ARN of an SQS queue.</p> </li> <li> <p> <b>Topic</b> * - The ARN of an SNS topic.</p> </li> <li> <p> <b>Event Bus</b> - The ARN of an * Amazon EventBridge event bus.</p> </li> </ul> */ inline void SetDestinationConfig(DestinationConfig&& value) { m_destinationConfigHasBeenSet = true; m_destinationConfig = std::move(value); } /** * <p>A destination for events after they have been sent to a function for * processing.</p> <p class="title"> <b>Destinations</b> </p> <ul> <li> <p> * <b>Function</b> - The Amazon Resource Name (ARN) of a Lambda function.</p> </li> * <li> <p> <b>Queue</b> - The ARN of an SQS queue.</p> </li> <li> <p> <b>Topic</b> * - The ARN of an SNS topic.</p> </li> <li> <p> <b>Event Bus</b> - The ARN of an * Amazon EventBridge event bus.</p> </li> </ul> */ inline FunctionEventInvokeConfig& WithDestinationConfig(const DestinationConfig& value) { SetDestinationConfig(value); return *this;} /** * <p>A destination for events after they have been sent to a function for * processing.</p> <p class="title"> <b>Destinations</b> </p> <ul> <li> <p> * <b>Function</b> - The Amazon Resource Name (ARN) of a Lambda function.</p> </li> * <li> <p> <b>Queue</b> - The ARN of an SQS queue.</p> </li> <li> <p> <b>Topic</b> * - The ARN of an SNS topic.</p> </li> <li> <p> <b>Event Bus</b> - The ARN of an * Amazon EventBridge event bus.</p> </li> </ul> */ inline FunctionEventInvokeConfig& WithDestinationConfig(DestinationConfig&& value) { SetDestinationConfig(std::move(value)); return *this;} private: Aws::Utils::DateTime m_lastModified; bool m_lastModifiedHasBeenSet; Aws::String m_functionArn; bool m_functionArnHasBeenSet; int m_maximumRetryAttempts; bool m_maximumRetryAttemptsHasBeenSet; int m_maximumEventAgeInSeconds; bool m_maximumEventAgeInSecondsHasBeenSet; DestinationConfig m_destinationConfig; bool m_destinationConfigHasBeenSet; }; } // namespace Model } // namespace Lambda } // namespace Aws
40.194915
145
0.656546
[ "model" ]
7f7a009ec7f2bc2432ff1cedd954ca32299d1c5f
21,429
h
C
kernel/huawei/hwp7/drivers/hisi/keymaster/include/crys_aes.h
NightOfTwelve/android_device_huawei_hwp7
a0a1c28e44210ce485a4177ac53d3fd580008a1e
[ "Apache-2.0" ]
1
2020-04-03T14:00:34.000Z
2020-04-03T14:00:34.000Z
kernel/huawei/hwp7/drivers/hisi/keymaster/include/crys_aes.h
NightOfTwelve/android_device_huawei_hwp7
a0a1c28e44210ce485a4177ac53d3fd580008a1e
[ "Apache-2.0" ]
null
null
null
kernel/huawei/hwp7/drivers/hisi/keymaster/include/crys_aes.h
NightOfTwelve/android_device_huawei_hwp7
a0a1c28e44210ce485a4177ac53d3fd580008a1e
[ "Apache-2.0" ]
1
2020-04-03T14:00:39.000Z
2020-04-03T14:00:39.000Z
/******************************************************************* * (c) Copyright 2011-2012 Discretix Technologies Ltd. * * This software is protected by copyright, international * * treaties and patents. * * Use of this Software as part of or with the Discretix CryptoCell * * or Packet Engine products is governed by the products' * * commercial end user license agreement ("EULA"). * * It is possible that copies of this Software might be distributed * * under some type of GNU General Public License ("GPL"). * * Notwithstanding any such distribution under the terms of GPL, * * GPL does not govern the use of this Software as part of or with * * the Discretix CryptoCell or Packet Engine products, for which a * * EULA is required. * * If the product's EULA allows any copy or reproduction of this * * Software, then such copy or reproduction must include this * * Copyright Notice as well as any other notices provided * * thereunder. * ********************************************************************/ /** @file * \brief This file contains all of the enums and definitions that are used for the * CRYS AES APIs, as well as the APIs themselves. * */ #ifndef CRYS_AES_H #define CRYS_AES_H /* * All the includes that are needed for code using this module to * compile correctly should be #included here. */ #include "dx_pal_types.h" #include "crys_error.h" #include "crys_defs.h" #ifdef __cplusplus extern "C" { #endif /************************ Defines ******************************/ /** @brief - a definition describing the low level Engine type ( SW , Hardware , Etc ) */ #if defined(DX_CC_SEP) #define CRYS_AES_USER_CTX_SIZE_IN_WORDS 32 #elif defined(DX_CC_TEE) /*Inorder to allow contiguous context the user context is doubled + 3 words for managment */ #define CRYS_AES_USER_CTX_SIZE_IN_WORDS 131 #else #define CRYS_AES_USER_CTX_SIZE_IN_WORDS 312 #endif /* The AES block size in words and in bytes */ #define CRYS_AES_BLOCK_SIZE_IN_WORDS 4 #define CRYS_AES_BLOCK_SIZE_IN_BYTES (CRYS_AES_BLOCK_SIZE_IN_WORDS * sizeof(DxUint32_t)) /* The size of the IV or counter buffer */ #define CRYS_AES_IV_COUNTER_SIZE_IN_WORDS CRYS_AES_BLOCK_SIZE_IN_WORDS #define CRYS_AES_IV_COUNTER_SIZE_IN_BYTES (CRYS_AES_IV_COUNTER_SIZE_IN_WORDS * sizeof(DxUint32_t)) /* The maximum size of the AES KEY in words and bytes */ #define CRYS_AES_KEY_MAX_SIZE_IN_WORDS 16 #define CRYS_AES_KEY_MAX_SIZE_IN_BYTES (CRYS_AES_KEY_MAX_SIZE_IN_WORDS * sizeof(DxUint32_t)) /* The AES_WRAP minimum data size in bytes (one 64-bits block) */ #define CRYS_AES_WRAP_DATA_MIN_SIZE_IN_BYTES 8 /* The AES_WRAP maximum data size in bytes: */ #define CRYS_AES_WRAP_DATA_MAX_SIZE_IN_BYTES 512 /* The CRYS_AES_WRAP block size in bytes and in words */ #define CRYS_AES_WRAP_BLOCK_SIZE_IN_BYTES 8 #define CRYS_AES_WRAP_BLOCK_SIZE_IN_WORDS (CRYS_AES_WRAP_BLOCK_SIZE_IN_BYTES / sizeof(DxUint32_t)) #define CRYS_AES_WRAP_STEPS 6 //according to rfc3394 /************************ Enums ********************************/ /* Enum defining the user's key size argument */ typedef enum { CRYS_AES_Key128BitSize = 0, CRYS_AES_Key192BitSize = 1, CRYS_AES_Key256BitSize = 2, CRYS_AES_Key512BitSize = 3, CRYS_AES_KeySizeNumOfOptions, CRYS_AES_KeySizeLast = 0x7FFFFFFF, }CRYS_AES_KeySize_t; /* Enum defining the Encrypt or Decrypt operation mode */ typedef enum { CRYS_AES_Encrypt = 0, CRYS_AES_Decrypt = 1, CRYS_AES_EncryptNumOfOptions, CRYS_AES_EncryptModeLast= 0x7FFFFFFF, }CRYS_AES_EncryptMode_t; /* Enum defining the AES operation mode */ typedef enum { CRYS_AES_ECB_mode = 0, CRYS_AES_CBC_mode = 1, CRYS_AES_MAC_mode = 2, CRYS_AES_CTR_mode = 3, CRYS_AES_XCBC_MAC_mode = 4, CRYS_AES_CMAC_mode = 5, CRYS_AES_XTS_mode = 6, CRYS_AES_CBC_CTS_mode = 7, CRYS_AES_OFB_mode = 8, CRYS_AES_CCM_mode = 9, CRYS_AES_NumOfModes, CRYS_AES_OperationModeLast= 0x7FFFFFFF, }CRYS_AES_OperationMode_t; /************************ Typedefs ****************************/ /* Defines the IV counter buffer - 16 bytes array */ typedef DxUint8_t CRYS_AES_IvCounter_t[CRYS_AES_IV_COUNTER_SIZE_IN_BYTES]; /* Define the XTS Tweak value type - 16 bytes array */ typedef CRYS_AES_IvCounter_t CRYS_AES_XTS_Tweak_t; /* Defines the AES key buffer */ typedef DxUint8_t CRYS_AES_Key_t[CRYS_AES_KEY_MAX_SIZE_IN_BYTES]; /* Defines the AES MAC result maximum size buffer */ typedef DxUint8_t CRYS_AES_MAX_MAC_RESULT_t[CRYS_AES_IV_COUNTER_SIZE_IN_BYTES]; #define CRYS_AES_SYS_WriteRegistersBlock( addr , buffer , size_in_words ) \ do \ { \ DxUint32_t im0,km0; \ for ( im0 = 0 , km0=(DX_CC_REG_ADDR(CRY_KERNEL, DIN_BUFFER)) ; im0 < (size_in_words) ; km0+=sizeof(DxUint32_t) , im0++ ) \ { \ WRITE_REGISTER( km0, buffer[im0]);\ } \ }while(0) /************************ context Structs ******************************/ /* The user's context prototype - the argument type that will be passed by the user to the APIs called by him */ typedef struct CRYS_AESUserContext_t { /* Allocated buffer must be double the size of actual context * + 1 word for offset management */ DxUint32_t buff[CRYS_AES_USER_CTX_SIZE_IN_WORDS]; }CRYS_AESUserContext_t; /************************ Public Variables **********************/ /************************ Public Functions **********************/ /****************************************************************************************************/ /** * @brief This function is used to initialize the AES machine or SW structures. * To perform the AES operations this should be the first function called. * * * @param[in] ContextID_ptr - A pointer to the AES context buffer that is allocated by the user * and is used for the AES machine operation. * @param[in] IVCounter_ptr - A buffer containing an initial value: IV, Counter or Tweak according * to operation mode: * - on ECB, XCBC, CMAC mode this parameter is not used and may be NULL, * - on CBC and MAC modes it contains the IV value, * - on CTR and OFB modes it contains the init counter, * - on XTS mode it contains the initial tweak value - 128-bit consecutive number * of data unit (in little endian). * @param[in] Key_ptr - A pointer to the user's key buffer. * @param[in] KeySize - An enum parameter, defines size of used key (128, 192, 256, 512 bits): * On XCBC mode allowed 128 bit size only, on XTS - 256 or 512 bit, on other modes <= 256 bit. * @param[in] EncryptDecryptFlag - A flag specifying whether the AES should perform an Encrypt operation (0) * or a Decrypt operation (1). In XCBC and CMAC modes it must be Encrypt. * @param[in] OperationMode - The operation mode: ECB, CBC, MAC, CTR, OFB, XCBC (PRF and 96), CMAC, XTS and CBC-CTS. * * @return CRYSError_t - On success the value CRYS_OK is returned, and on failure - a value from crys_aes_error.h */ CIMPORT_C CRYSError_t CRYS_AES_Init( CRYS_AESUserContext_t *ContextID_ptr, CRYS_AES_IvCounter_t IVCounter_ptr, CRYS_AES_Key_t Key_ptr, CRYS_AES_KeySize_t KeySizeID, CRYS_AES_EncryptMode_t EncryptDecryptFlag, CRYS_AES_OperationMode_t OperationMode); /****************************************************************************************************/ /** * @brief This function is used to operate a block of data on the SW or on AES machine. * This function should be called after the appropriate CRYS AES init function * (according to used AES operation mode). * * @param[in] ContextID_ptr - A pointer to the AES context buffer allocated by the user that * is used for the AES machine operation. This should be the same context that was * used on the previous call of this session. * * @param[in] DataIn_ptr - A pointer to the buffer of the input data to the AES. The pointer does * not need to be aligned. * * @param[in] DataInSize - A size of the input data must be multiple of 16 bytes, * on all modes. Note last chunk (block) of data must be processed by * CRYS_AES_Finish function but not by CRYS_AES_Block function; * * @param[out] DataOut_ptr - A pointer to the buffer of the output data from the AES. The pointer does not * need to be aligned. In case of MAC modes it can be NULL * * @return CRYSError_t - On success CRYS_OK is returned, on failure a * value MODULE_* CRYS_AES_error.h * */ CIMPORT_C CRYSError_t CRYS_AES_Block( CRYS_AESUserContext_t *ContextID_ptr, DxUint8_t *DataIn_ptr, DxUint32_t DataInSize, DxUint8_t *DataOut_ptr ); /****************************************************************************************************/ /** * @brief This function is used as finish operation on all AES modes. * * The function must be called after AES_Block operations (or instead) for last chunck * of data with size > 0. * * The function performs all operations, including specific operations for last blocks of * data on some modes (XCBC, CMAC, MAC) and puts out the result. After all operations * the function cleans the secure sensitive data from context. * * * @param[in] ContextID_ptr - A pointer to the AES context buffer allocated by the user that * should be the same context that was used on the previous call * of this session. * * @param[in] DataIn_ptr - A pointer to the buffer of the input data to the AES. The pointer does * not need to be aligned. * * @param[in] DataInSize - A size of the input data must be: DataInSize >= minimalSize, where: * minimalSize = * - 1 byte for CTR, OFB, XCBC, CMAC mode; * - 16 bytes for ECB CBC MAC XTS modes. * - >16 bytes for CBC-CTS modes. * * @param[out] DataOut_ptr - A pointer to the output buffer. The pointer does not need to be aligned. * The size of the output buffer must be not less than: * - 16 bytes for MAC, XCBC, CMAC modes; * - DataInSize for ECB,CBC,CTR,XTS,OFB modes. * * @return CRYSError_t - On success CRYS_OK is returned, on failure - a value defined in crys_aes_error.h. * */ CIMPORT_C CRYSError_t CRYS_AES_Finish( CRYS_AESUserContext_t *ContextID_ptr, DxUint8_t *DataIn_ptr, DxUint32_t DataInSize, DxUint8_t *DataOut_ptr ); /****************************************************************************************************/ /** * @brief This function is used to perform the AES operation in one integrated process. * * * The input-output parameters of the function are the following: * * @param[in] ContextID_ptr - A pointer to the AES context buffer that is allocated by the user * and is used for the AES machine operation. * @param[in] IVCounter_ptr - A buffer containing an initial value: IV, Counter or Tweak according * to operation mode: * - on ECB, XCBC, CMAC mode this parameter is not used and may be NULL, * - on CBC ,CBC-CTS and MAC modes it contains the IV value, * - on CTR and OFB modes it contains the init counter, * - on XTS mode it contains the initial tweak value - 128-bit consecutive number * of data unit (in little endian). * @param[in] Key_ptr - A pointer to the user's key buffer (set to NULL for secret key). * @param[in] KeySize - An enum parameter, defines size of used key (128, 192, 256 bits). * @param[in] EncryptDecryptFlag - A flag specifying whether the AES should perform an Encrypt operation * or a Decrypt operation . In MAC modes it must be 0. * @param[in] OperationMode - The operation mode: ECB, CBC, MAC, CTR, XCBC (PRF and 96), CMAC, XTS, OFB, CBC-CTS. * @param[in] DataIn_ptr - A pointer to the buffer of the input data to the AES. The pointer does * not need to be aligned. * * @param[in] DataInSize - The size of the input data, it must be: * - on ECB,CBC,MAC modes must be not 0 and must be a multiple of 16 bytes, * - on CTR, XCBC, CMAC, OFB and CBS-CTS modes must be not 0, * - on XTS mode must be or multiple of 16 bytes (not 0), or not less than 17 bytes. * @param[out] DataOut_ptr - A pointer to the buffer of the output data from the AES. The pointer does not * need to be aligned. * * @return CRYSError_t - On success CRYS_OK is returned, on failure a value defined in crys_aes_error.h * * NOTES: 1. Temporarily it is not allowed, that both the Input and the Output simultaneously * were on CSI mode. * 2. Temporarily the CSI input or output are not allowed on XCBC, CMAC and XTS modes. * */ CIMPORT_C CRYSError_t CRYS_AES( CRYS_AES_IvCounter_t IVCounter_ptr, CRYS_AES_Key_t Key_ptr, CRYS_AES_KeySize_t KeySize, CRYS_AES_EncryptMode_t EncryptDecryptFlag, CRYS_AES_OperationMode_t OperationMode , DxUint8_t *DataIn_ptr, DxUint32_t DataInSize, DxUint8_t *DataOut_ptr ); /************************************************************************** * CRYS_AES_Wrap function * **************************************************************************/ /** @brief The CRYS_AES_Wrap function implements the following algorithm (rfc3394, Sept. 2002): Inputs: Plaintext DataIn, n 64-bit values {P1, P2, ..., Pn}, KeyData, K (the KEK). Outputs: Ciphertext, WrapDataOut (n+1) 64-bit values {C0, C1, ..., Cn}. @param[in] DataIn_ptr - A pointer to plain text data to be wrapped NOTE: Overlapping between the data input and data output buffer is not allowed, except the inplace case that is legal . @param[in] DataInLen - Length of data in bytes. DataLen must be multiple of 8 bytes and must be in range [8, 512]. @param[in] KeyData - A pointer to key data (key encryption key - KEK). @param[in] KeySize - Enumerator variable, defines length of key. @param[in] Reserved - Reserved param, should not be used. @param[out] WrapDataOut_ptr - A pointer to buffer for output of wrapped data. @param[in/out] WrapDataLen_ptr - A pointer to a buffer for input of size of user passed buffer and for output actual size of unwrapped data in bytes. Buffer size must be not less than DataLen+CRYS_AES_WRAP_BLOCK_SIZE_IN_BYTES. @return CRYSError_t - CRYS_OK, or error message CRYS_AES_WRAP_ILLEGAL_DATA_PTR_ERROR CRYS_AES_WRAP_DATA_LENGTH_ERROR CRYS_AES_WRAP_ILLEGAL_KEY_PTR_ERROR CRYS_AES_WRAP_KEY_LENGTH_ERROR CRYS_AES_WRAP_ILLEGAL_WRAP_DATA_PTR_ERROR CRYS_AES_WRAP_ILLEGAL_WRAP_DATA_LEN_PTR_ERROR CRYS_AES_WRAP_ILLEGAL_WRAP_DATA_LENGTH_ERROR CRYS_AES_WRAP_DATA_OUT_DATA_IN_OVERLAP_ERROR CRYS_AES_WRAP_IS_SECRET_KEY_FLAG_ILLEGAL_ERROR NOTE: On error exiting from function the output buffer may be zeroed by the function. */ CIMPORT_C CRYSError_t CRYS_AES_Wrap ( DxUint8_t *DataIn_ptr, /*in*/ DxUint32_t DataInLen, /*in*/ CRYS_AES_Key_t KeyData, /*in*/ CRYS_AES_KeySize_t KeySize, /*in*/ DxInt8_t Reserved, /*in*/ DxUint8_t *WrapDataOut_ptr, /*out*/ DxUint32_t *WrapDataLen_ptr /*in/out*/ ); /************************************************************************** * CRYS_AES_Uwnrap function * **************************************************************************/ /** @brief The CRYS_AES_Unwrap function performs inverse AES_Wrap transformation and implements the following algorithm (rfc3394, Sept. 2002): Inputs: Ciphertext, (n+1) 64-bit values {C0, C1, ..., Cn}, and K - key (the KEK). Outputs: Plaintext, n 64-bit values {P1, P2, ..., Pn}. @param[in] WrapDataIn_ptr - A pointer to wrapped data to be unwrapped NOTE: Overlapping between the data input and data output buffer is not allowed, except the inplace case that is legal . @param[in] WrapDataInLen - Length of wrapped data in bytes. DataLen must be multiple of 8 bytes and must be in range [16, 512+8]. @param[in] KeyData - A pointer to key data (key encryption key - KEK). @param[in] KeySize - Enumerator variable, defines length of key. @param[in] Reserved - Reserved param, should not be used. @param[out] DataOut_ptr - A pointer to buffer for output of unwrapped data. @param[in/out] DataOutLen_ptr - A pointer to a buffer for input of size of user passed buffer and for output of actual size of unwrapped data in bytes. DataOutLen must be multiple of 8 bytes and must be not less than WrapDataInLen - CRYS_AES_WRAP_BLOCK_SIZE_IN_BYTES. @return CRYSError_t - CRYS_OK, or error message CRYS_AES_UNWRAP_WRAP_DATA_LENGTH_ERROR CRYS_AES_UNWRAP_ILLEGAL_KEY_PTR_ERROR CRYS_AES_UNWRAP_KEY_LEN_ERROR CRYS_AES_UNWRAP_ILLEGAL_DATA_PTR_ERROR CRYS_AES_UNWRAP_ILLEGAL_DATA_LEN_PTR_ERROR CRYS_AES_UNWRAP_ILLEGAL_DATA_LENGTH_ERROR CRYS_AES_UNWRAP_FUNCTION_FAILED_ERROR CRYS_AES_UNWRAP_DATA_OUT_DATA_IN_OVERLAP_ERROR CRYS_AES_UNWRAP_IS_SECRET_KEY_FLAG_ILLEGAL_ERROR NOTE: On error exiting from function the output buffer may be zeroed by the function. */ CIMPORT_C CRYSError_t CRYS_AES_Unwrap( DxUint8_t *WrapDataIn_ptr, /*in*/ DxUint32_t WrapDataInLen, /*in*/ CRYS_AES_Key_t KeyData, /*in*/ CRYS_AES_KeySize_t KeySize, /*in*/ DxInt8_t Reserved, /*in*/ DxUint8_t *DataOut_ptr, /*out*/ DxUint32_t *DataOutLen_ptr /*in/out*/ ); /************************************************************************** * CRYS_AES_SetIv function * **************************************************************************/ /** @brief The CRYS_AES_SetIv function puts a new initial vector into an existing context. Inputs: New IV vector Outputs: Result @param[in/out] ContextID_ptr - A pointer to the AES context buffer that is allocated by the user and is used for the AES machine operation. @return CRYSError_t - CRYS_OK, or error message CRYS_AES_INVALID_USER_CONTEXT_POINTER_ERROR */ CIMPORT_C CRYSError_t CRYS_AES_SetIv(CRYS_AESUserContext_t *ContextID_ptr, DxUint8_t *iv_ptr); /************************************************************************** * CRYS_AES_GetIv function * **************************************************************************/ /** @brief The CRYS_AES_GetIv function retrieves the initial vector from the context. Inputs: IV vector buffer Outputs: Result @param[in/out] ContextID_ptr - A pointer to the AES context buffer that is allocated by the user and is used for the AES machine operation. @return CRYSError_t - CRYS_OK, or error message CRYS_AES_INVALID_USER_CONTEXT_POINTER_ERROR */ CIMPORT_C CRYSError_t CRYS_AES_GetIv(CRYS_AESUserContext_t *ContextID_ptr, DxUint8_t *iv_ptr); /***********************************************************************************/ #ifdef __cplusplus } #endif #endif /* #ifndef CRYS_AES_H */
45.496815
124
0.585842
[ "vector" ]
7f7d722d2f242133ce93e1f09a113277501e5c46
64,133
c
C
arch/arm/src/kinetis/kinetis_enet.c
mickey-happygolucky/incubator-nuttx
e7f48f9773ce956bed429fdc70a357e7ba8eae2c
[ "MIT" ]
1
2020-02-11T13:37:31.000Z
2020-02-11T13:37:31.000Z
arch/arm/src/kinetis/kinetis_enet.c
mickey-happygolucky/incubator-nuttx
e7f48f9773ce956bed429fdc70a357e7ba8eae2c
[ "MIT" ]
null
null
null
arch/arm/src/kinetis/kinetis_enet.c
mickey-happygolucky/incubator-nuttx
e7f48f9773ce956bed429fdc70a357e7ba8eae2c
[ "MIT" ]
1
2020-02-11T11:13:20.000Z
2020-02-11T11:13:20.000Z
/**************************************************************************** * arch/arm/src/kinetis/kinetis_enet.c * * Copyright (C) 2011-2012, 2014-2018 Gregory Nutt. All rights reserved. * Authors: Gregory Nutt <gnutt@nuttx.org> * David Sidrane <david_s5@nscdg.com> * * 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_KINETIS_ENET) #include <stdint.h> #include <stdbool.h> #include <unistd.h> #include <time.h> #include <string.h> #include <debug.h> #include <errno.h> #include <arpa/inet.h> #include <nuttx/wdog.h> #include <nuttx/irq.h> #include <nuttx/arch.h> #include <nuttx/wqueue.h> #include <nuttx/signal.h> #include <nuttx/net/mii.h> #include <nuttx/net/arp.h> #include <nuttx/net/netdev.h> #ifdef CONFIG_NET_PKT # include <nuttx/net/pkt.h> #endif #include "up_arch.h" #include "chip.h" #include "kinetis.h" #include "kinetis_config.h" #include "hardware/kinetis_pinmux.h" #include "hardware/kinetis_sim.h" #include "hardware/kinetis_mpu.h" #include "hardware/kinetis_enet.h" #if defined(KINETIS_NENET) && KINETIS_NENET > 0 /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* If processing is not done at the interrupt level, then work queue support * is required. */ #if !defined(CONFIG_SCHED_WORKQUEUE) # error Work queue support is required #endif /* The low priority work queue is preferred. If it is not enabled, LPWORK * will be the same as HPWORK. * * NOTE: However, the network should NEVER run on the high priority work * queue! That queue is intended only to service short back end interrupt * processing that never suspends. Suspending the high priority work queue * may bring the system to its knees! */ #define ETHWORK LPWORK /* CONFIG_KINETIS_ENETNETHIFS determines the number of physical interfaces * that will be supported. */ #if CONFIG_KINETIS_ENETNETHIFS != 1 # error "CONFIG_KINETIS_ENETNETHIFS must be one for now" #endif #if CONFIG_KINETIS_ENETNTXBUFFERS < 1 # error "Need at least one TX buffer" #endif #if CONFIG_KINETIS_ENETNRXBUFFERS < 1 # error "Need at least one RX buffer" #endif #define NENET_NBUFFERS \ (CONFIG_KINETIS_ENETNTXBUFFERS+CONFIG_KINETIS_ENETNRXBUFFERS) /* TX poll delay = 1 seconds. CLK_TCK is the number of clock ticks per * second. */ #define KINETIS_WDDELAY (1*CLK_TCK) /* TX timeout = 1 minute */ #define KINETIS_TXTIMEOUT (60*CLK_TCK) #define MII_MAXPOLLS (0x1ffff) #define LINK_WAITUS (500*1000) #define LINK_NLOOPS (10) /* PHY definitions. * * The selected PHY must be selected from the drivers/net/Kconfig PHY menu. * A description of the PHY must be provided here. That description must * include: * * 1. BOARD_PHY_NAME: A PHY name string (for debug output), * 2. BOARD_PHYID1 and BOARD_PHYID2: The PHYID1 and PHYID2 values (from * include/nuttx/net/mii.h) * 3. BOARD_PHY_STATUS: The address of the status register to use when * querying link status (from include/nuttx/net/mii.h) * 4. BOARD_PHY_ISDUPLEX: A macro that can convert the status register * value into a boolean: true=duplex mode, false=half-duplex mode * 5. BOARD_PHY_10BASET: A macro that can convert the status register * value into a boolean: true=10Base-T, false=Not 10Base-T * 6. BOARD_PHY_100BASET: A macro that can convert the status register * value into a boolean: true=100Base-T, false=Not 100Base-T * * The Tower SER board uses a KSZ8041 PHY. * The Freedom K64F board uses a KSZ8081 PHY * The Freedom K66F board uses a KSZ8081 PHY */ #if defined(CONFIG_ETH0_PHY_KSZ8041) # define BOARD_PHY_NAME "KSZ8041" # define BOARD_PHYID1 MII_PHYID1_KSZ8041 # define BOARD_PHYID2 MII_PHYID2_KSZ8041 # define BOARD_PHY_STATUS MII_KSZ8041_PHYCTRL2 # define BOARD_PHY_10BASET(s) (((s) & MII_PHYCTRL2_MODE_10HDX) != 0) # define BOARD_PHY_100BASET(s) (((s) & MII_PHYCTRL2_MODE_100HDX) != 0) # define BOARD_PHY_ISDUPLEX(s) (((s) & MII_PHYCTRL2_MODE_DUPLEX) != 0) #elif defined(CONFIG_ETH0_PHY_KSZ8081) # define BOARD_PHY_NAME "KSZ8081" # define BOARD_PHYID1 MII_PHYID1_KSZ8081 # define BOARD_PHYID2 MII_PHYID2_KSZ8081 # define BOARD_PHY_STATUS MII_KSZ8081_PHYCTRL1 # define BOARD_PHY_10BASET(s) (((s) & MII_PHYCTRL1_MODE_10HDX) != 0) # define BOARD_PHY_100BASET(s) (((s) & MII_PHYCTRL1_MODE_100HDX) != 0) # define BOARD_PHY_ISDUPLEX(s) (((s) & MII_PHYCTRL1_MODE_DUPLEX) != 0) #elif defined(CONFIG_ETH0_PHY_TJA1100) # define BOARD_PHY_NAME "TJA1100" # define BOARD_PHYID1 MII_PHYID1_TJA1100 # define BOARD_PHYID2 MII_PHYID2_TJA1100 # define BOARD_PHY_STATUS MII_TJA1100_BSR # define BOARD_PHY_10BASET(s) 0 /* PHY only supports 100BASE-T1 */ # define BOARD_PHY_100BASET(s) 1 /* PHY only supports 100BASE-T1 */ # define BOARD_PHY_ISDUPLEX(s) 1 /* PHY only supports fullduplex */ #else # error "Unrecognized or missing PHY selection" #endif /* Estimate the MII_SPEED in order to get an MDC close to 2.5MHz, * based on the internal module (ENET) clock: * * MII_SPEED = ENET_FREQ/5000000 -1 * * For example, if ENET_FREQ_MHZ=120 (MHz): * * MII_SPEED = 120000000/5000000 -1 * = 23 */ #define KINETIS_MII_SPEED (BOARD_CORECLK_FREQ/5000000 - 1) #if KINETIS_MII_SPEED > 63 # error "KINETIS_MII_SPEED is out-of-range" #endif /* Interrupt groups */ #define RX_INTERRUPTS (ENET_INT_RXF | ENET_INT_RXB) #define TX_INTERRUPTS ENET_INT_TXF #define ERROR_INTERRUPTS (ENET_INT_UN | ENET_INT_RL | ENET_INT_LC | \ ENET_INT_EBERR | ENET_INT_BABT | ENET_INT_BABR) /* This is a helper pointer for accessing the contents of the Ethernet header */ #define BUF ((struct eth_hdr_s *)priv->dev.d_buf) #define KINETIS_BUF_SIZE ((CONFIG_NET_ETH_PKTSIZE & 0xfffffff0) + 0x10) /* If this SoC has the RMII Clock Source selection configure it */ #if defined(CONFIG_KINETIS_EMAC_RMIICLKEXTAL) # define SIM_SOPT2_RMIISRC SIM_SOPT2_RMIISRC_EXTAL #endif #if defined(CONFIG_KINETIS_EMAC_RMIICLK1588CLKIN) # define SIM_SOPT2_RMIISRC SIM_SOPT2_RMIISRC_EXTBYP #endif /**************************************************************************** * Private Types ****************************************************************************/ /* The kinetis_driver_s encapsulates all state information for a single hardware * interface */ struct kinetis_driver_s { bool bifup; /* true:ifup false:ifdown */ uint8_t txtail; /* The oldest busy TX descriptor */ uint8_t txhead; /* The next TX descriptor to use */ uint8_t rxtail; /* The next RX descriptor to use */ uint8_t phyaddr; /* Selected PHY address */ WDOG_ID txpoll; /* TX poll timer */ WDOG_ID txtimeout; /* TX timeout timer */ struct work_s irqwork; /* For deferring interrupt work to the work queue */ struct work_s pollwork; /* For deferring poll work to the work queue */ struct enet_desc_s *txdesc; /* A pointer to the list of TX descriptor */ struct enet_desc_s *rxdesc; /* A pointer to the list of RX descriptors */ /* This holds the information visible to the NuttX network */ struct net_driver_s dev; /* Interface understood by the network */ /* The DMA descriptors. A unaligned uint8_t is used to allocate the * memory; 16 is added to assure that we can meet the descriptor alignment * requirements. */ uint8_t desc[NENET_NBUFFERS * sizeof(struct enet_desc_s) + 16]; /* The DMA buffers. Again, A unaligned uint8_t is used to allocate the * memory; 16 is added to assure that we can meet the descriptor alignment * requirements. */ uint8_t buffers[NENET_NBUFFERS * KINETIS_BUF_SIZE + 16]; }; /**************************************************************************** * Private Data ****************************************************************************/ static struct kinetis_driver_s g_enet[CONFIG_KINETIS_ENETNETHIFS]; /**************************************************************************** * Private Function Prototypes ****************************************************************************/ /* Utility functions */ #ifndef KINETIS_BUFFERS_SWAP # define kinesis_swap32(value) (value) # define kinesis_swap16(value) (value) #else #if 0 /* Use builtins if the compiler supports them */ static inline uint32_t kinesis_swap32(uint32_t value); static inline uint16_t kinesis_swap16(uint16_t value); #else # define kinesis_swap32 __builtin_bswap32 # define kinesis_swap16 __builtin_bswap16 #endif #endif /* Common TX logic */ static bool kinetis_txringfull(FAR struct kinetis_driver_s *priv); static int kinetis_transmit(FAR struct kinetis_driver_s *priv); static int kinetis_txpoll(struct net_driver_s *dev); /* Interrupt handling */ static void kinetis_receive(FAR struct kinetis_driver_s *priv); static void kinetis_txdone(FAR struct kinetis_driver_s *priv); static void kinetis_interrupt_work(FAR void *arg); static int kinetis_interrupt(int irq, FAR void *context, FAR void *arg); /* Watchdog timer expirations */ static void kinetis_txtimeout_work(FAR void *arg); static void kinetis_txtimeout_expiry(int argc, uint32_t arg, ...); static void kinetis_poll_work(FAR void *arg); static void kinetis_polltimer_expiry(int argc, uint32_t arg, ...); /* NuttX callback functions */ static int kinetis_ifup(struct net_driver_s *dev); static int kinetis_ifdown(struct net_driver_s *dev); static void kinetis_txavail_work(FAR void *arg); static int kinetis_txavail(struct net_driver_s *dev); #ifdef CONFIG_NET_MCASTGROUP static int kinetis_addmac(struct net_driver_s *dev, FAR const uint8_t *mac); static int kinetis_rmmac(struct net_driver_s *dev, FAR const uint8_t *mac); #endif #ifdef CONFIG_NETDEV_IOCTL static int kinetis_ioctl(struct net_driver_s *dev, int cmd, unsigned long arg); #endif /* PHY/MII support */ static inline void kinetis_initmii(struct kinetis_driver_s *priv); static int kinetis_writemii(struct kinetis_driver_s *priv, uint8_t phyaddr, uint8_t regaddr, uint16_t data); static int kinetis_readmii(struct kinetis_driver_s *priv, uint8_t phyaddr, uint8_t regaddr, uint16_t *data); static inline int kinetis_initphy(struct kinetis_driver_s *priv); /* Initialization */ static void kinetis_initbuffers(struct kinetis_driver_s *priv); static void kinetis_reset(struct kinetis_driver_s *priv); /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Function: kinetis_swap16/32 * * Description: * The descriptors are represented by structures Unfortunately, when the * structures are overlayed on the data, the bytes are reversed because * the underlying hardware writes the data in big-endian byte order. * * Input Parameters: * value - The value to be byte swapped * * Returned Value: * The byte swapped value * ****************************************************************************/ #if 0 /* Use builtins if the compiler supports them */ #ifndef CONFIG_ENDIAN_BIG static inline uint32_t kinesis_swap32(uint32_t value) { uint32_t result = 0; __asm__ __volatile__ ( "rev %0, %1" :"=r" (result) : "r"(value) ); return result; } static inline uint16_t kinesis_swap16(uint16_t value) { uint16_t result = 0; __asm__ __volatile__ ( "revsh %0, %1" :"=r" (result) : "r"(value) ); return result; } #endif #endif /**************************************************************************** * Function: kinetis_txringfull * * Description: * Check if all of the TX descriptors are in use. * * Input Parameters: * priv - Reference to the driver state structure * * Returned Value: * true is the TX ring is full; false if there are free slots at the * head index. * ****************************************************************************/ static bool kinetis_txringfull(FAR struct kinetis_driver_s *priv) { uint8_t txnext; /* Check if there is room in the hardware to hold another outgoing * packet. The ring is full if incrementing the head pointer would * collide with the tail pointer. */ txnext = priv->txhead + 1; if (txnext >= CONFIG_KINETIS_ENETNTXBUFFERS) { txnext = 0; } return priv->txtail == txnext; } /**************************************************************************** * Function: kinetis_transmit * * Description: * Start hardware transmission. Called either from the txdone interrupt * handling or from watchdog based polling. * * Input Parameters: * priv - Reference to the driver state structure * * Returned Value: * OK on success; a negated errno on failure * * Assumptions: * May or may not be called from an interrupt handler. In either case, * global interrupts are disabled, either explicitly or indirectly through * interrupt handling logic. * ****************************************************************************/ static int kinetis_transmit(FAR struct kinetis_driver_s *priv) { struct enet_desc_s *txdesc; uint32_t regval; uint8_t *buf; /* Since this can be called from kinetis_receive, it is possible that * the transmit queue is full, so check for that now. If this is the * case, the outgoing packet will be dropped (e.g. an ARP reply) */ if (kinetis_txringfull(priv)) { return -EBUSY; } /* When we get here the TX descriptor should show that the previous * transfer has completed. If we get here, then we are committed to * sending a packet; Higher level logic must have assured that there is * no transmission in progress. */ txdesc = &priv->txdesc[priv->txhead]; priv->txhead++; if (priv->txhead >= CONFIG_KINETIS_ENETNTXBUFFERS) { priv->txhead = 0; } DEBUGASSERT(priv->txtail != priv->txhead && (txdesc->status1 & TXDESC_R) == 0); /* Increment statistics */ NETDEV_TXPACKETS(&priv->dev); /* Setup the buffer descriptor for transmission: address=priv->dev.d_buf, * length=priv->dev.d_len */ txdesc->length = kinesis_swap16(priv->dev.d_len); #ifdef CONFIG_KINETIS_ENETENHANCEDBD txdesc->bdu = 0x00000000; txdesc->status2 = TXDESC_INT | TXDESC_TS; /* | TXDESC_IINS | TXDESC_PINS; */ #endif txdesc->status1 |= (TXDESC_R | TXDESC_L | TXDESC_TC); buf = (uint8_t *)kinesis_swap32((uint32_t) priv->dev.d_buf); if (priv->rxdesc[priv->rxtail].data == buf) { struct enet_desc_s *rxdesc = &priv->rxdesc[priv->rxtail]; /* Data was written into the RX buffer, so swap the TX and RX buffers */ DEBUGASSERT((rxdesc->status1 & RXDESC_E) == 0); rxdesc->data = txdesc->data; txdesc->data = buf; } else { DEBUGASSERT(txdesc->data == buf); } /* Start the TX transfer (if it was not already waiting for buffers) */ putreg32(ENET_TDAR, KINETIS_ENET_TDAR); /* Enable TX interrupts */ regval = getreg32(KINETIS_ENET_EIMR); regval |= TX_INTERRUPTS; putreg32(regval, KINETIS_ENET_EIMR); /* Setup the TX timeout watchdog (perhaps restarting the timer) */ wd_start(priv->txtimeout, KINETIS_TXTIMEOUT, kinetis_txtimeout_expiry, 1, (wdparm_t)priv); return OK; } /**************************************************************************** * Function: kinetis_txpoll * * Description: * The transmitter is available, check if the network has any outgoing * packets ready to send. This is a callback from devif_poll(). * devif_poll() may be called: * * 1. When the preceding TX packet send is complete, * 2. When the preceding TX packet send timesout and the interface is reset * 3. During normal TX polling * * Input Parameters: * dev - Reference to the NuttX driver state structure * * Returned Value: * OK on success; a negated errno on failure * * Assumptions: * May or may not be called from an interrupt handler. In either case, * global interrupts are disabled, either explicitly or indirectly through * interrupt handling logic. * ****************************************************************************/ static int kinetis_txpoll(struct net_driver_s *dev) { FAR struct kinetis_driver_s *priv = (FAR struct kinetis_driver_s *)dev->d_private; /* If the polling resulted in data that should be sent out on the network, * the field d_len is set to a value > 0. */ if (priv->dev.d_len > 0) { /* Look up the destination MAC address and add it to the Ethernet * header. */ #ifdef CONFIG_NET_IPv4 #ifdef CONFIG_NET_IPv6 if (IFF_IS_IPv4(priv->dev.d_flags)) #endif { arp_out(&priv->dev); } #endif /* CONFIG_NET_IPv4 */ #ifdef CONFIG_NET_IPv6 #ifdef CONFIG_NET_IPv4 else #endif { neighbor_out(&priv->dev); } #endif /* CONFIG_NET_IPv6 */ if (!devif_loopback(&priv->dev)) { /* Send the packet */ kinetis_transmit(priv); priv->dev.d_buf = (uint8_t *) kinesis_swap32((uint32_t)priv->txdesc[priv->txhead].data); /* Check if there is room in the device to hold another packet. * If not, return a non-zero value to terminate the poll. */ if (kinetis_txringfull(priv)) { return -EBUSY; } } } /* If zero is returned, the polling will continue until all connections have * been examined. */ return 0; } /**************************************************************************** * Function: kinetis_receive * * Description: * An interrupt was received indicating the availability of a new RX packet * * Input Parameters: * priv - Reference to the driver state structure * * Returned Value: * None * * Assumptions: * Global interrupts are disabled by interrupt handling logic. * ****************************************************************************/ static void kinetis_receive(FAR struct kinetis_driver_s *priv) { /* Loop while there are received packets to be processed */ while ((priv->rxdesc[priv->rxtail].status1 & RXDESC_E) == 0) { /* Update statistics */ NETDEV_RXPACKETS(&priv->dev); /* Copy the buffer pointer to priv->dev.d_buf. Set amount of data in * priv->dev.d_len */ priv->dev.d_len = kinesis_swap16(priv->rxdesc[priv->rxtail].length); priv->dev.d_buf = (uint8_t *)kinesis_swap32((uint32_t)priv->rxdesc[priv->rxtail].data); #ifdef CONFIG_NET_PKT /* When packet sockets are enabled, feed the frame into the packet tap */ pkt_input(&priv->dev); #endif /* We only accept IP packets of the configured type and ARP packets */ #ifdef CONFIG_NET_IPv4 if (BUF->type == HTONS(ETHTYPE_IP)) { ninfo("IPv4 frame\n"); NETDEV_RXIPV4(&priv->dev); /* Handle ARP on input then give the IPv4 packet to the network * layer */ arp_ipin(&priv->dev); ipv4_input(&priv->dev); /* If the above function invocation resulted in data that should be * sent out on the network, the field d_len will set to a value > 0. */ if (priv->dev.d_len > 0) { /* Update the Ethernet header with the correct MAC address */ #ifdef CONFIG_NET_IPv6 if (IFF_IS_IPv4(priv->dev.d_flags)) #endif { arp_out(&priv->dev); } #ifdef CONFIG_NET_IPv6 else { neighbor_out(&priv->dev); } #endif /* And send the packet */ kinetis_transmit(priv); } } else #endif #ifdef CONFIG_NET_IPv6 if (BUF->type == HTONS(ETHTYPE_IP6)) { ninfo("Iv6 frame\n"); NETDEV_RXIPV6(&priv->dev); /* Give the IPv6 packet to the network layer */ ipv6_input(&priv->dev); /* If the above function invocation resulted in data that should be * sent out on the network, the field d_len will set to a value > 0. */ if (priv->dev.d_len > 0) { /* Update the Ethernet header with the correct MAC address */ #ifdef CONFIG_NET_IPv4 if (IFF_IS_IPv4(priv->dev.d_flags)) { arp_out(&priv->dev); } else #endif #ifdef CONFIG_NET_IPv6 { neighbor_out(&priv->dev); } #endif /* And send the packet */ kinetis_transmit(priv); } } else #endif #ifdef CONFIG_NET_ARP if (BUF->type == htons(ETHTYPE_ARP)) { NETDEV_RXARP(&priv->dev); arp_arpin(&priv->dev); /* If the above function invocation resulted in data that should * be sent out on the network, the field d_len will set to a * value > 0. */ if (priv->dev.d_len > 0) { kinetis_transmit(priv); } } #endif else { NETDEV_RXDROPPED(&priv->dev); } /* Point the packet buffer back to the next TX buffer, which will be used * during the next write. If the write queue is full, then this will * point at an active buffer, which must not be written to. This is OK * because devif_poll won't be called unless the queue is not full. */ priv->dev.d_buf = (uint8_t *)kinesis_swap32((uint32_t)priv->txdesc[priv->txhead].data); priv->rxdesc[priv->rxtail].status1 |= RXDESC_E; /* Update the index to the next descriptor */ priv->rxtail++; if (priv->rxtail >= CONFIG_KINETIS_ENETNRXBUFFERS) { priv->rxtail = 0; } /* Indicate that there have been empty receive buffers produced */ putreg32(ENET_RDAR, KINETIS_ENET_RDAR); } } /**************************************************************************** * Function: kinetis_txdone * * Description: * An interrupt was received indicating that the last TX packet(s) is done * * Input Parameters: * priv - Reference to the driver state structure * * Returned Value: * None * * Assumptions: * Global interrupts are disabled by the watchdog logic. * ****************************************************************************/ static void kinetis_txdone(FAR struct kinetis_driver_s *priv) { uint32_t regval; /* Verify that the oldest descriptor descriptor completed */ while (((priv->txdesc[priv->txtail].status1 & TXDESC_R) == 0) && (priv->txtail != priv->txhead)) { /* Yes.. bump up the tail pointer, making space for a new TX descriptor */ priv->txtail++; if (priv->txtail >= CONFIG_KINETIS_ENETNTXBUFFERS) { priv->txtail = 0; } /* Update statistics */ NETDEV_TXDONE(&priv->dev); } /* Are there other transmissions queued? */ if (priv->txtail == priv->txhead) { /* No.. Cancel the TX timeout and disable further Tx interrupts. */ wd_cancel(priv->txtimeout); regval = getreg32(KINETIS_ENET_EIMR); regval &= ~TX_INTERRUPTS; putreg32(regval, KINETIS_ENET_EIMR); } /* There should be space for a new TX in any event. Poll the network for * new XMIT data */ devif_poll(&priv->dev, kinetis_txpoll); } /**************************************************************************** * Function: kinetis_interrupt_work * * Description: * Perform interrupt related work from the worker thread * * Input Parameters: * arg - The argument passed when work_queue() was called. * * Returned Value: * OK on success * * Assumptions: * The network is locked. * ****************************************************************************/ static void kinetis_interrupt_work(FAR void *arg) { FAR struct kinetis_driver_s *priv = (FAR struct kinetis_driver_s *)arg; uint32_t pending; /* Process pending Ethernet interrupts */ net_lock(); /* Get the set of unmasked, pending interrupt. */ pending = getreg32(KINETIS_ENET_EIR) & getreg32(KINETIS_ENET_EIMR); /* Clear the pending interrupts */ putreg32(pending, KINETIS_ENET_EIR); /* Check for the receipt of a packet */ if ((pending & ENET_INT_RXF) != 0) { /* A packet has been received, call kinetis_receive() to handle the * packet. */ kinetis_receive(priv); } /* Check if a packet transmission has completed */ if ((pending & ENET_INT_TXF) != 0) { /* Call kinetis_txdone to handle the end of transfer even. NOTE that * this may disable further Tx interrupts if there are no pending * tansmissions. */ kinetis_txdone(priv); } /* Check for errors */ if (pending & ERROR_INTERRUPTS) { /* An error has occurred, update statistics */ NETDEV_ERRORS(&priv->dev); /* Reinitialize all buffers. */ kinetis_initbuffers(priv); /* Indicate that there have been empty receive buffers produced */ putreg32(ENET_RDAR, KINETIS_ENET_RDAR); } net_unlock(); /* Re-enable Ethernet interrupts */ #if 0 up_enable_irq(KINETIS_IRQ_EMACTMR); #endif up_enable_irq(KINETIS_IRQ_EMACTX); up_enable_irq(KINETIS_IRQ_EMACRX); up_enable_irq(KINETIS_IRQ_EMACMISC); } /**************************************************************************** * Function: kinetis_interrupt * * Description: * Three interrupt sources will vector this this function: * 1. Ethernet MAC transmit interrupt handler * 2. Ethernet MAC receive interrupt handler * 3. * * Input Parameters: * irq - Number of the IRQ that generated the interrupt * context - Interrupt register state save info (architecture-specific) * * Returned Value: * OK on success * * Assumptions: * ****************************************************************************/ static int kinetis_interrupt(int irq, FAR void *context, FAR void *arg) { register FAR struct kinetis_driver_s *priv = &g_enet[0]; /* Disable further Ethernet interrupts. Because Ethernet interrupts are * also disabled if the TX timeout event occurs, there can be no race * condition here. */ up_disable_irq(KINETIS_IRQ_EMACTMR); up_disable_irq(KINETIS_IRQ_EMACTX); up_disable_irq(KINETIS_IRQ_EMACRX); up_disable_irq(KINETIS_IRQ_EMACMISC); /* TODO: Determine if a TX transfer just completed */ { /* If a TX transfer just completed, then cancel the TX timeout so * there will be do race condition between any subsequent timeout * expiration and the deferred interrupt processing. */ wd_cancel(priv->txtimeout); } /* Schedule to perform the interrupt processing on the worker thread. */ work_queue(ETHWORK, &priv->irqwork, kinetis_interrupt_work, priv, 0); return OK; } /**************************************************************************** * Function: kinetis_txtimeout_work * * Description: * Perform TX timeout related work from the worker thread * * Input Parameters: * arg - The argument passed when work_queue() as called. * * Returned Value: * OK on success * * Assumptions: * The network is locked. * ****************************************************************************/ static void kinetis_txtimeout_work(FAR void *arg) { FAR struct kinetis_driver_s *priv = (FAR struct kinetis_driver_s *)arg; /* Increment statistics and dump debug info */ net_lock(); NETDEV_TXTIMEOUTS(&priv->dev); /* Take the interface down and bring it back up. The is the most agressive * hardware reset. */ kinetis_ifdown(&priv->dev); kinetis_ifup(&priv->dev); /* Then poll the network for new XMIT data */ devif_poll(&priv->dev, kinetis_txpoll); net_unlock(); } /**************************************************************************** * Function: kinetis_txtimeout_expiry * * Description: * Our TX watchdog timed out. Called from the timer interrupt handler. * The last TX never completed. Reset the hardware and start again. * * Input Parameters: * argc - The number of available arguments * arg - The first argument * * Returned Value: * None * * Assumptions: * Global interrupts are disabled by the watchdog logic. * ****************************************************************************/ static void kinetis_txtimeout_expiry(int argc, uint32_t arg, ...) { FAR struct kinetis_driver_s *priv = (FAR struct kinetis_driver_s *)arg; /* Disable further Ethernet interrupts. This will prevent some race * conditions with interrupt work. There is still a potential race * condition with interrupt work that is already queued and in progress. */ up_disable_irq(KINETIS_IRQ_EMACTMR); up_disable_irq(KINETIS_IRQ_EMACTX); up_disable_irq(KINETIS_IRQ_EMACRX); up_disable_irq(KINETIS_IRQ_EMACMISC); /* Schedule to perform the TX timeout processing on the worker thread, * canceling any pending interrupt work. */ work_queue(ETHWORK, &priv->irqwork, kinetis_txtimeout_work, priv, 0); } /**************************************************************************** * Function: kinetis_poll_work * * Description: * Perform periodic polling from the worker thread * * Input Parameters: * arg - The argument passed when work_queue() as called. * * Returned Value: * OK on success * * Assumptions: * The network is locked. * ****************************************************************************/ static void kinetis_poll_work(FAR void *arg) { FAR struct kinetis_driver_s *priv = (FAR struct kinetis_driver_s *)arg; /* Check if there is there is a transmission in progress. We cannot perform * the TX poll if he are unable to accept another packet for transmission. */ net_lock(); if (!kinetis_txringfull(priv)) { /* If so, update TCP timing states and poll the network for new XMIT * data. Hmmm..might be bug here. Does this mean if there is a transmit * in progress, we will missing TCP time state updates? */ devif_timer(&priv->dev, KINETIS_WDDELAY, kinetis_txpoll); } /* Setup the watchdog poll timer again in any case */ wd_start(priv->txpoll, KINETIS_WDDELAY, kinetis_polltimer_expiry, 1, (wdparm_t)priv); net_unlock(); } /**************************************************************************** * Function: kinetis_polltimer_expiry * * Description: * Periodic timer handler. Called from the timer interrupt handler. * * Input Parameters: * argc - The number of available arguments * arg - The first argument * * Returned Value: * None * * Assumptions: * Global interrupts are disabled by the watchdog logic. * ****************************************************************************/ static void kinetis_polltimer_expiry(int argc, uint32_t arg, ...) { FAR struct kinetis_driver_s *priv = (FAR struct kinetis_driver_s *)arg; /* Schedule to perform the poll processing on the worker thread. */ work_queue(ETHWORK, &priv->pollwork, kinetis_poll_work, priv, 0); } /**************************************************************************** * Function: kinetis_ifup * * Description: * NuttX Callback: Bring up the Ethernet interface when an IP address is * provided * * Input Parameters: * dev - Reference to the NuttX driver state structure * * Returned Value: * None * * Assumptions: * ****************************************************************************/ static int kinetis_ifup(struct net_driver_s *dev) { FAR struct kinetis_driver_s *priv = (FAR struct kinetis_driver_s *)dev->d_private; uint8_t *mac = dev->d_mac.ether.ether_addr_octet; uint32_t regval; int ret; ninfo("Bringing up: %d.%d.%d.%d\n", dev->d_ipaddr & 0xff, (dev->d_ipaddr >> 8) & 0xff, (dev->d_ipaddr >> 16) & 0xff, dev->d_ipaddr >> 24); #if defined(PIN_ENET_PHY_EN) kinetis_gpiowrite(PIN_ENET_PHY_EN, true); #endif /* Initialize ENET buffers */ kinetis_initbuffers(priv); /* Reset and disable the interface */ kinetis_reset(priv); /* Configure the MII interface */ kinetis_initmii(priv); /* Set the MAC address */ putreg32((mac[0] << 24) | (mac[1] << 16) | (mac[2] << 8) | mac[3], KINETIS_ENET_PALR); putreg32((mac[4] << 24) | (mac[5] << 16), KINETIS_ENET_PAUR); /* Clear the Individual and Group Address Hash registers */ putreg32(0, KINETIS_ENET_IALR); putreg32(0, KINETIS_ENET_IAUR); putreg32(0, KINETIS_ENET_GALR); putreg32(0, KINETIS_ENET_GAUR); /* Configure the PHY */ ret = kinetis_initphy(priv); if (ret < 0) { nerr("ERROR: Failed to configure the PHY: %d\n", ret); return ret; } /* Handle promiscuous mode */ #ifdef CONFIG_NET_PROMISCUOUS regval = getreg32(KINETIS_ENET_RCR); regval |= ENET_RCR_PROM; putreg32(regval, KINETIS_ENET_RCR); #endif /* Select legacy of enhanced buffer descriptor format */ #ifdef CONFIG_KINETIS_ENETENHANCEDBD putreg32(ENET_ECR_EN1588, KINETIS_ENET_ECR); #else putreg32(0, KINETIS_ENET_ECR); #endif /* Set the RX buffer size */ putreg32(KINETIS_BUF_SIZE, KINETIS_ENET_MRBR); /* Point to the start of the circular RX buffer descriptor queue */ putreg32((uint32_t)priv->rxdesc, KINETIS_ENET_RDSR); /* Point to the start of the circular TX buffer descriptor queue */ putreg32((uint32_t)priv->txdesc, KINETIS_ENET_TDSR); /* And enable the MAC itself */ regval = getreg32(KINETIS_ENET_ECR); regval |= ENET_ECR_ETHEREN #ifdef KINETIS_USE_DBSWAP | ENET_ECR_DBSWP #endif ; putreg32(regval, KINETIS_ENET_ECR); /* Indicate that there have been empty receive buffers produced */ putreg32(ENET_RDAR, KINETIS_ENET_RDAR); /* Set and activate a timer process */ wd_start(priv->txpoll, KINETIS_WDDELAY, kinetis_polltimer_expiry, 1, (wdparm_t)priv); /* Clear all pending ENET interrupt */ putreg32(0xffffffff, KINETIS_ENET_EIR); /* Enable RX and error interrupts at the controller (TX interrupts are * still disabled). */ putreg32(RX_INTERRUPTS | ERROR_INTERRUPTS, KINETIS_ENET_EIMR); /* Mark the interrupt "up" and enable interrupts at the NVIC */ priv->bifup = true; #if 0 up_enable_irq(KINETIS_IRQ_EMACTMR); #endif up_enable_irq(KINETIS_IRQ_EMACTX); up_enable_irq(KINETIS_IRQ_EMACRX); up_enable_irq(KINETIS_IRQ_EMACMISC); return OK; } /**************************************************************************** * Function: kinetis_ifdown * * Description: * NuttX Callback: Stop the interface. * * Input Parameters: * dev - Reference to the NuttX driver state structure * * Returned Value: * None * * Assumptions: * ****************************************************************************/ static int kinetis_ifdown(struct net_driver_s *dev) { FAR struct kinetis_driver_s *priv = (FAR struct kinetis_driver_s *)dev->d_private; irqstate_t flags; /* Disable the Ethernet interrupts at the NVIC */ flags = enter_critical_section(); up_disable_irq(KINETIS_IRQ_EMACTMR); up_disable_irq(KINETIS_IRQ_EMACTX); up_disable_irq(KINETIS_IRQ_EMACRX); up_disable_irq(KINETIS_IRQ_EMACMISC); putreg32(0, KINETIS_ENET_EIMR); /* Cancel the TX poll timer and TX timeout timers */ wd_cancel(priv->txpoll); wd_cancel(priv->txtimeout); /* Put the EMAC in its reset, non-operational state. This should be * a known configuration that will guarantee the kinetis_ifup() always * successfully brings the interface back up. */ kinetis_reset(priv); #if defined(PIN_ENET_PHY_EN) kinetis_gpiowrite(PIN_ENET_PHY_EN, false); #endif /* Mark the device "down" */ priv->bifup = false; leave_critical_section(flags); return OK; } /**************************************************************************** * Function: kinetis_txavail_work * * Description: * Perform an out-of-cycle poll on the worker thread. * * Input Parameters: * arg - Reference to the NuttX driver state structure (cast to void*) * * Returned Value: * None * * Assumptions: * Called on the higher priority worker thread. * ****************************************************************************/ static void kinetis_txavail_work(FAR void *arg) { FAR struct kinetis_driver_s *priv = (FAR struct kinetis_driver_s *)arg; /* Ignore the notification if the interface is not yet up */ net_lock(); if (priv->bifup) { /* Check if there is room in the hardware to hold another outgoing * packet. */ if (!kinetis_txringfull(priv)) { /* No, there is space for another transfer. Poll the network for new * XMIT data. */ devif_poll(&priv->dev, kinetis_txpoll); } } net_unlock(); } /**************************************************************************** * Function: kinetis_txavail * * Description: * Driver callback invoked when new TX data is available. This is a * stimulus perform an out-of-cycle poll and, thereby, reduce the TX * latency. * * Input Parameters: * dev - Reference to the NuttX driver state structure * * Returned Value: * None * * Assumptions: * Called in normal user mode * ****************************************************************************/ static int kinetis_txavail(struct net_driver_s *dev) { FAR struct kinetis_driver_s *priv = (FAR struct kinetis_driver_s *)dev->d_private; /* Is our single work structure available? It may not be if there are * pending interrupt actions and we will have to ignore the Tx * availability action. */ if (work_available(&priv->pollwork)) { /* Schedule to serialize the poll on the worker thread. */ work_queue(ETHWORK, &priv->pollwork, kinetis_txavail_work, priv, 0); } return OK; } /**************************************************************************** * Function: kinetis_addmac * * Description: * NuttX Callback: Add the specified MAC address to the hardware multicast * address filtering * * Input Parameters: * dev - Reference to the NuttX driver state structure * mac - The MAC address to be added * * Returned Value: * None * * Assumptions: * ****************************************************************************/ #ifdef CONFIG_NET_MCASTGROUP static int kinetis_addmac(struct net_driver_s *dev, FAR const uint8_t *mac) { FAR struct kinetis_driver_s *priv = (FAR struct kinetis_driver_s *)dev->d_private; /* Add the MAC address to the hardware multicast routing table */ return OK; } #endif /**************************************************************************** * Function: kinetis_rmmac * * Description: * NuttX Callback: Remove the specified MAC address from the hardware * multicast address filtering * * Input Parameters: * dev - Reference to the NuttX driver state structure * mac - The MAC address to be removed * * Returned Value: * None * * Assumptions: * ****************************************************************************/ #ifdef CONFIG_NET_MCASTGROUP static int kinetis_rmmac(struct net_driver_s *dev, FAR const uint8_t *mac) { FAR struct kinetis_driver_s *priv = (FAR struct kinetis_driver_s *)dev->d_private; /* Add the MAC address to the hardware multicast routing table */ UNUSED(priv); return OK; } #endif /**************************************************************************** * Function: kinetis_ioctl * * Description: * PHY ioctl command handler * * Input Parameters: * dev - Reference to the NuttX driver state structure * cmd - ioctl command * arg - Argument accompanying the command * * Returned Value: * Zero (OK) on success; a negated errno value on failure. * * Assumptions: * ****************************************************************************/ #ifdef CONFIG_NETDEV_IOCTL static int kinetis_ioctl(struct net_driver_s *dev, int cmd, unsigned long arg) { #ifdef CONFIG_NETDEV_PHY_IOCTL FAR struct kinetis_driver_s *priv = (FAR struct kinetis_driver_s *)dev->d_private; #endif int ret; switch (cmd) { #ifdef CONFIG_NETDEV_PHY_IOCTL case SIOCGMIIPHY: /* Get MII PHY address */ { struct mii_ioctl_data_s *req = (struct mii_ioctl_data_s *)((uintptr_t)arg); req->phy_id = priv->phyaddr; ret = OK; } break; case SIOCGMIIREG: /* Get register from MII PHY */ { struct mii_ioctl_data_s *req = (struct mii_ioctl_data_s *)((uintptr_t)arg); ret = kinetis_readmii(priv, req->phy_id, req->reg_num, &req->val_out); } break; case SIOCSMIIREG: /* Set register in MII PHY */ { struct mii_ioctl_data_s *req = (struct mii_ioctl_data_s *)((uintptr_t)arg); ret = kinetis_writemii(priv, req->phy_id, req->reg_num, req->val_in); } break; #endif /* ifdef CONFIG_NETDEV_PHY_IOCTL */ default: ret = -ENOTTY; break; } return ret; } #endif /* CONFIG_NETDEV_IOCTL */ /**************************************************************************** * Function: kinetis_initmii * * Description: * Configure the MII interface * * Input Parameters: * priv - Reference to the private ENET driver state structure * * Returned Value: * None * * Assumptions: * ****************************************************************************/ static void kinetis_initmii(struct kinetis_driver_s *priv) { /* Speed is based on the peripheral (bus) clock; hold time is 1 module * clock. This hold time value may need to be increased on some platforms */ putreg32(ENET_MSCR_HOLDTIME_1CYCLE | KINETIS_MII_SPEED << ENET_MSCR_MII_SPEED_SHIFT, KINETIS_ENET_MSCR); } /**************************************************************************** * Function: kinetis_writemii * * Description: * Write a 16-bit value to a PHY register. * * Input Parameters: * priv - Reference to the private ENET driver state structure * phyaddr - The PHY address * regaddr - The PHY register address * data - The data to write to the PHY register * * Returned Value: * Zero on success, a negated errno value on failure. * ****************************************************************************/ static int kinetis_writemii(struct kinetis_driver_s *priv, uint8_t phyaddr, uint8_t regaddr, uint16_t data) { int timeout; /* Clear the MII interrupt bit */ putreg32(ENET_INT_MII, KINETIS_ENET_EIR); /* Initiatate the MII Management write */ putreg32(data | 2 << ENET_MMFR_TA_SHIFT | (uint32_t)regaddr << ENET_MMFR_RA_SHIFT | (uint32_t)phyaddr << ENET_MMFR_PA_SHIFT | ENET_MMFR_OP_WRMII | 1 << ENET_MMFR_ST_SHIFT, KINETIS_ENET_MMFR); /* Wait for the transfer to complete */ for (timeout = 0; timeout < MII_MAXPOLLS; timeout++) { if ((getreg32(KINETIS_ENET_EIR) & ENET_INT_MII) != 0) { break; } } /* Check for a timeout */ if (timeout == MII_MAXPOLLS) { return -ETIMEDOUT; } /* Clear the MII interrupt bit */ putreg32(ENET_INT_MII, KINETIS_ENET_EIR); return OK; } /**************************************************************************** * Function: kinetis_reademii * * Description: * Read a 16-bit value from a PHY register. * * Input Parameters: * priv - Reference to the private ENET driver state structure * phyaddr - The PHY address * regaddr - The PHY register address * data - A pointer to the location to return the data * * Returned Value: * Zero on success, a negated errno value on failure. * ****************************************************************************/ static int kinetis_readmii(struct kinetis_driver_s *priv, uint8_t phyaddr, uint8_t regaddr, uint16_t *data) { int timeout; /* Clear the MII interrupt bit */ putreg32(ENET_INT_MII, KINETIS_ENET_EIR); /* Initiatate the MII Management read */ putreg32(2 << ENET_MMFR_TA_SHIFT | (uint32_t)regaddr << ENET_MMFR_RA_SHIFT | (uint32_t)phyaddr << ENET_MMFR_PA_SHIFT | ENET_MMFR_OP_RDMII | 1 << ENET_MMFR_ST_SHIFT, KINETIS_ENET_MMFR); /* Wait for the transfer to complete */ for (timeout = 0; timeout < MII_MAXPOLLS; timeout++) { if ((getreg32(KINETIS_ENET_EIR) & ENET_INT_MII) != 0) { break; } } /* Check for a timeout */ if (timeout >= MII_MAXPOLLS) { nerr("ERROR: Timed out waiting for transfer to complete\n"); return -ETIMEDOUT; } /* Clear the MII interrupt bit */ putreg32(ENET_INT_MII, KINETIS_ENET_EIR); /* And return the MII data */ *data = (uint16_t)(getreg32(KINETIS_ENET_MMFR) & ENET_MMFR_DATA_MASK); return OK; } /**************************************************************************** * Function: kinetis_initphy * * Description: * Configure the PHY * * Input Parameters: * priv - Reference to the private ENET driver state structure * * Returned Value: * Zero (OK) returned on success; a negated errno value is returned on any * failure; * * Assumptions: * ****************************************************************************/ static inline int kinetis_initphy(struct kinetis_driver_s *priv) { uint32_t rcr; uint32_t tcr; uint16_t phydata; uint8_t phyaddr; int retries; int ret; /* Loop (potentially infinitely?) until we successfully communicate with * the PHY. */ for (phyaddr = 0; phyaddr < 32; phyaddr++) { ninfo("%s: Try phyaddr: %u\n", BOARD_PHY_NAME, phyaddr); /* Try to read PHYID1 few times using this address */ retries = 0; do { nxsig_usleep(LINK_WAITUS); ninfo("%s: Read PHYID1, retries=%d\n", BOARD_PHY_NAME, retries + 1); phydata = 0xffff; ret = kinetis_readmii(priv, phyaddr, MII_PHYID1, &phydata); } while ((ret < 0 || phydata == 0xffff) && ++retries < 3); /* If we successfully read anything then break out, using this PHY address */ if (retries < 3) { break; } } if (phyaddr >= 32) { nerr("ERROR: Failed to read %s PHYID1 at any address\n"); return -ENOENT; } ninfo("%s: Using PHY address %u\n", BOARD_PHY_NAME, phyaddr); priv->phyaddr = phyaddr; /* Verify PHYID1. Compare OUI bits 3-18 */ ninfo("%s: PHYID1: %04x\n", BOARD_PHY_NAME, phydata); if (phydata != BOARD_PHYID1) { nerr("ERROR: PHYID1=%04x incorrect for %s. Expected %04x\n", phydata, BOARD_PHY_NAME, BOARD_PHYID1); return -ENXIO; } /* Read PHYID2 */ ret = kinetis_readmii(priv, phyaddr, MII_PHYID2, &phydata); if (ret < 0) { nerr("ERROR: Failed to read %s PHYID2: %d\n", BOARD_PHY_NAME, ret); return ret; } ninfo("%s: PHYID2: %04x\n", BOARD_PHY_NAME, phydata); /* Verify PHYID2: Compare OUI bits 19-24 and the 6-bit model number * (ignoring the 4-bit revision number). */ if ((phydata & 0xfff0) != (BOARD_PHYID2 & 0xfff0)) { nerr("ERROR: PHYID2=%04x incorrect for %s. Expected %04x\n", (phydata & 0xfff0), BOARD_PHY_NAME, (BOARD_PHYID2 & 0xfff0)); return -ENXIO; } /* Start auto negotiation */ ninfo("%s: Start Autonegotiation...\n", BOARD_PHY_NAME); kinetis_writemii(priv, phyaddr, MII_MCR, (MII_MCR_ANRESTART | MII_MCR_ANENABLE)); /* Wait for auto negotiation to complete */ for (retries = 0; retries < LINK_NLOOPS; retries++) { ret = kinetis_readmii(priv, phyaddr, MII_MSR, &phydata); if (ret < 0) { nerr("ERROR: Failed to read %s MII_MSR: %d\n", BOARD_PHY_NAME, ret); return ret; } if (phydata & MII_MSR_ANEGCOMPLETE) { break; } nxsig_usleep(LINK_WAITUS); } if (phydata & MII_MSR_ANEGCOMPLETE) { ninfo("%s: Autonegotiation complete\n", BOARD_PHY_NAME); ninfo("%s: MII_MSR: %04x\n", BOARD_PHY_NAME, phydata); } else { /* TODO: Autonegotitation has right now failed. Maybe the Eth cable is * not connected. PHY chip have mechanisms to configure link OK. * We should leave autconf on, and find a way to re-configure the * MCU whenever the link is ready. */ ninfo("%s: Autonegotiation failed [%d] (is cable plugged-in ?), default to 10Mbs mode\n", \ BOARD_PHY_NAME, retries); /* Stop auto negotiation */ kinetis_writemii(priv, phyaddr, MII_MCR, 0); } /* When we get here we have a (negotiated) speed and duplex. */ phydata = 0; ret = kinetis_readmii(priv, phyaddr, BOARD_PHY_STATUS, &phydata); if (ret < 0) { nerr("ERROR: Failed to read %s BOARD_PHY_STATUS[%02x]: %d\n", BOARD_PHY_NAME, BOARD_PHY_STATUS, ret); return ret; } ninfo("%s: BOARD_PHY_STATUS: %04x\n", BOARD_PHY_NAME, phydata); /* Set up the transmit and receive control registers based on the * configuration and the auto negotiation results. */ #ifdef CONFIG_KINETIS_ENETUSEMII rcr = ENET_RCR_CRCFWD | CONFIG_NET_ETH_PKTSIZE << ENET_RCR_MAX_FL_SHIFT | ENET_RCR_MII_MODE; #else rcr = ENET_RCR_RMII_MODE | ENET_RCR_CRCFWD | CONFIG_NET_ETH_PKTSIZE << ENET_RCR_MAX_FL_SHIFT | ENET_RCR_MII_MODE; #endif tcr = 0; putreg32(rcr, KINETIS_ENET_RCR); putreg32(tcr, KINETIS_ENET_TCR); /* Setup half or full duplex */ if (BOARD_PHY_ISDUPLEX(phydata)) { /* Full duplex */ ninfo("%s: Full duplex\n", BOARD_PHY_NAME); tcr |= ENET_TCR_FDEN; } else { /* Half duplex */ ninfo("%s: Half duplex\n", BOARD_PHY_NAME); rcr |= ENET_RCR_DRT; } if (BOARD_PHY_10BASET(phydata)) { /* 10 Mbps */ ninfo("%s: 10 Base-T\n", BOARD_PHY_NAME); rcr |= ENET_RCR_RMII_10T; } else if (BOARD_PHY_100BASET(phydata)) { /* 100 Mbps */ ninfo("%s: 100 Base-T\n", BOARD_PHY_NAME); } else { /* This might happen if Autonegotiation did not complete(?) */ nerr("ERROR: Neither 10- nor 100-BaseT reported: PHY STATUS=%04x\n", phydata); return -EIO; } #if defined(CONFIG_ETH0_PHY_TJA1100) /* The NXP TJA1100 PHY is an automotive 100BASE-T1 PHY * Which requires additional initialization */ /* select mode TJA1100 */ kinetis_writemii(priv, phyaddr, MII_TJA1100_EXT_CNTRL, (MII_EXT_CNTRL_NORMAL | MII_EXT_CNTRL_CONFIG_EN | MII_EXT_CNTRL_CONFIG_INH)); # if defined(CONFIG_PHY_100BASE_T1_MASTER) /* Set TJA1100 in master mode */ kinetis_writemii(priv, phyaddr, MII_TJA1100_CONFIG1, (MII_CONFIG1_MASTER | MII_CONFIG1_TX_1250MV | MII_CONFIG1_RMII_25MHZ | MII_CONFIG1_LED_EN)); # else /* Set TJA1100 in slave mode */ kinetis_writemii(priv, phyaddr, MII_TJA1100_CONFIG1, (MII_CONFIG1_TX_1250MV | MII_CONFIG1_RMII_25MHZ | MII_CONFIG1_LED_EN)); # endif kinetis_writemii(priv, phyaddr, MII_TJA1100_CONFIG2, (MII_CONFIG2_SNR_AV64 | MII_CONFIG2_WLIM_D | MII_CONFIG2_SNR_F_NL | MII_CONFIG2_SLP_T_1)); /* Select normal mode TJA1100 */ kinetis_writemii(priv, phyaddr, MII_TJA1100_EXT_CNTRL, (MII_EXT_CNTRL_NORMAL | MII_EXT_CNTRL_CONFIG_INH)); kinetis_writemii(priv, phyaddr, MII_TJA1100_EXT_CNTRL, (MII_EXT_CNTRL_LINK_CNTRL | MII_EXT_CNTRL_NORMAL | MII_EXT_CNTRL_CONFIG_INH)); #endif putreg32(rcr, KINETIS_ENET_RCR); putreg32(tcr, KINETIS_ENET_TCR); return OK; } /**************************************************************************** * Function: kinetis_initbuffers * * Description: * Initialize ENET buffers and descriptors * * Input Parameters: * priv - Reference to the private ENET driver state structure * * Returned Value: * None * * Assumptions: * ****************************************************************************/ static void kinetis_initbuffers(struct kinetis_driver_s *priv) { uintptr_t addr; int i; /* Get an aligned TX descriptor (array)address */ addr = ((uintptr_t)priv->desc + 0x0f) & ~0x0f; priv->txdesc = (struct enet_desc_s *)addr; /* Get an aligned RX descriptor (array) address */ addr += CONFIG_KINETIS_ENETNTXBUFFERS * sizeof(struct enet_desc_s); priv->rxdesc = (struct enet_desc_s *)addr; /* Get the beginning of the first aligned buffer */ addr = ((uintptr_t)priv->buffers + 0x0f) & ~0x0f; /* Then fill in the TX descriptors */ for (i = 0; i < CONFIG_KINETIS_ENETNTXBUFFERS; i++) { priv->txdesc[i].status1 = 0; priv->txdesc[i].length = 0; priv->txdesc[i].data = (uint8_t *)kinesis_swap32((uint32_t)addr); #ifdef CONFIG_KINETIS_ENETENHANCEDBD priv->txdesc[i].status2 = TXDESC_IINS | TXDESC_PINS; #endif addr += KINETIS_BUF_SIZE; } /* Then fill in the RX descriptors */ for (i = 0; i < CONFIG_KINETIS_ENETNRXBUFFERS; i++) { priv->rxdesc[i].status1 = RXDESC_E; priv->rxdesc[i].length = 0; priv->rxdesc[i].data = (uint8_t *)kinesis_swap32((uint32_t)addr); #ifdef CONFIG_KINETIS_ENETENHANCEDBD priv->rxdesc[i].bdu = 0; priv->rxdesc[i].status2 = RXDESC_INT; #endif addr += KINETIS_BUF_SIZE; } /* Set the wrap bit in the last descriptors to form a ring */ priv->txdesc[CONFIG_KINETIS_ENETNTXBUFFERS - 1].status1 |= TXDESC_W; priv->rxdesc[CONFIG_KINETIS_ENETNRXBUFFERS - 1].status1 |= RXDESC_W; /* We start with RX descriptor 0 and with no TX descriptors in use */ priv->txtail = 0; priv->txhead = 0; priv->rxtail = 0; /* Initialize the packet buffer, which is used when sending */ priv->dev.d_buf = (uint8_t *)kinesis_swap32((uint32_t)priv->txdesc[priv->txhead].data); } /**************************************************************************** * Function: kinetis_reset * * Description: * Put the EMAC in the non-operational, reset state * * Input Parameters: * priv - Reference to the private ENET driver state structure * * Returned Value: * None * * Assumptions: * ****************************************************************************/ static void kinetis_reset(struct kinetis_driver_s *priv) { unsigned int i; /* Set the reset bit and clear the enable bit */ putreg32(ENET_ECR_RESET, KINETIS_ENET_ECR); #ifdef PIN_ENET_PHY_RST kinetis_gpiowrite(PIN_ENET_PHY_RST, false); #endif /* Wait at least 8 clock cycles */ for (i = 0; i < 10; i++) { asm volatile ("nop"); } #ifdef PIN_ENET_PHY_RST /* Wait at least 20us */ up_udelay(21); kinetis_gpiowrite(PIN_ENET_PHY_RST, true); #endif } /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Function: kinetis_netinitialize * * Description: * Initialize the Ethernet controller and driver * * Input Parameters: * intf - In the case where there are multiple EMACs, this value * identifies which EMAC is to be initialized. * * Returned Value: * OK on success; Negated errno on failure. * * Assumptions: * ****************************************************************************/ int kinetis_netinitialize(int intf) { struct kinetis_driver_s *priv; #ifdef CONFIG_NET_ETHERNET uint32_t uidl; uint32_t uidml; uint8_t *mac; #endif uint32_t regval; /* Get the interface structure associated with this interface number. */ DEBUGASSERT(intf < CONFIG_KINETIS_ENETNETHIFS); priv = &g_enet[intf]; #if defined(SIM_SOPT2_RMIISRC) /* If this Soc has RMII clock select then select the RMII clock source. * First if the source is ENET_1588_CLKIN - configure the pin to apply the * clock to the block. Then select it as the source. */ # if SIM_SOPT2_RMIISRC == SIM_SOPT2_RMIISRC_EXTBYP kinetis_pinconfig(PIN_ENET_1588_CLKIN); # endif regval = getreg32(KINETIS_SIM_SOPT2); regval |= SIM_SOPT2_RMIISRC; putreg32(regval, KINETIS_SIM_SOPT2); #endif /* Enable the ENET clock */ regval = getreg32(KINETIS_SIM_SCGC2); regval |= SIM_SCGC2_ENET; putreg32(regval, KINETIS_SIM_SCGC2); /* Allow concurrent access to MPU controller. Example: ENET uDMA to SRAM, * otherwise a bus error will result. */ putreg32(0, KINETIS_MPU_CESR); #ifdef CONFIG_KINETIS_ENETUSEMII /* Configure all ENET/MII pins */ kinetis_pinconfig(PIN_MII0_MDIO); kinetis_pinconfig(PIN_MII0_MDC); kinetis_pinconfig(PIN_MII0_RXDV); kinetis_pinconfig(PIN_MII0_RXER); kinetis_pinconfig(PIN_MII0_TXER); kinetis_pinconfig(PIN_MII0_RXD0); kinetis_pinconfig(PIN_MII0_RXD1); kinetis_pinconfig(PIN_MII0_RXD2); kinetis_pinconfig(PIN_MII0_RXD3); kinetis_pinconfig(PIN_MII0_TXD0); kinetis_pinconfig(PIN_MII0_TXD1); kinetis_pinconfig(PIN_MII0_TXD3); kinetis_pinconfig(PIN_MII0_TXD2); kinetis_pinconfig(PIN_MII0_TXEN); kinetis_pinconfig(PIN_MII0_RXCLK); kinetis_pinconfig(PIN_MII0_TXCLK); kinetis_pinconfig(PIN_MII0_CRS); kinetis_pinconfig(PIN_MII0_COL); #else /* Use RMII subset */ kinetis_pinconfig(PIN_RMII0_MDIO); kinetis_pinconfig(PIN_RMII0_MDC); kinetis_pinconfig(PIN_RMII0_CRS_DV); kinetis_pinconfig(PIN_RMII0_RXER); kinetis_pinconfig(PIN_RMII0_RXD0); kinetis_pinconfig(PIN_RMII0_RXD1); kinetis_pinconfig(PIN_RMII0_TXD0); kinetis_pinconfig(PIN_RMII0_TXD1); kinetis_pinconfig(PIN_RMII0_TXEN); #endif #ifdef PIN_ENET_PHY_EN kinetis_pinconfig(PIN_ENET_PHY_EN); #endif #ifdef PIN_ENET_PHY_RST kinetis_pinconfig(PIN_ENET_PHY_RST); #endif /* Attach the Ethernet MAC IEEE 1588 timer interrupt handler */ #if 0 if (irq_attach(KINETIS_IRQ_EMACTMR, kinetis_tmrinterrupt, NULL)) { /* We could not attach the ISR to the interrupt */ nerr("ERROR: Failed to attach EMACTMR IRQ\n"); return -EAGAIN; } #endif /* Attach the Ethernet MAC transmit interrupt handler */ if (irq_attach(KINETIS_IRQ_EMACTX, kinetis_interrupt, NULL)) { /* We could not attach the ISR to the interrupt */ nerr("ERROR: Failed to attach EMACTX IRQ\n"); return -EAGAIN; } /* Attach the Ethernet MAC receive interrupt handler */ if (irq_attach(KINETIS_IRQ_EMACRX, kinetis_interrupt, NULL)) { /* We could not attach the ISR to the interrupt */ nerr("ERROR: Failed to attach EMACRX IRQ\n"); return -EAGAIN; } /* Attach the Ethernet MAC error and misc interrupt handler */ if (irq_attach(KINETIS_IRQ_EMACMISC, kinetis_interrupt, NULL)) { /* We could not attach the ISR to the interrupt */ nerr("ERROR: Failed to attach EMACMISC IRQ\n"); return -EAGAIN; } /* Initialize the driver structure */ memset(priv, 0, sizeof(struct kinetis_driver_s)); priv->dev.d_ifup = kinetis_ifup; /* I/F up (new IP address) callback */ priv->dev.d_ifdown = kinetis_ifdown; /* I/F down callback */ priv->dev.d_txavail = kinetis_txavail; /* New TX data callback */ #ifdef CONFIG_NET_MCASTGROUP priv->dev.d_addmac = kinetis_addmac; /* Add multicast MAC address */ priv->dev.d_rmmac = kinetis_rmmac; /* Remove multicast MAC address */ #endif #ifdef CONFIG_NETDEV_IOCTL priv->dev.d_ioctl = kinetis_ioctl; /* Support PHY ioctl() calls */ #endif priv->dev.d_private = (void *)g_enet; /* Used to recover private state from dev */ /* Create a watchdog for timing polling for and timing of transmissions */ priv->txpoll = wd_create(); /* Create periodic poll timer */ priv->txtimeout = wd_create(); /* Create TX timeout timer */ #ifdef CONFIG_NET_ETHERNET /* Determine a semi-unique MAC address from MCU UID * We use UID Low and Mid Low registers to get 64 bits, from which we keep * 48 bits. We then force unicast and locally administered bits (b0 and b1, * 1st octet) */ uidl = getreg32(KINETIS_SIM_UIDL); uidml = getreg32(KINETIS_SIM_UIDML); mac = priv->dev.d_mac.ether.ether_addr_octet; uidml |= 0x00000200; uidml &= 0x0000feff; mac[0] = (uidml & 0x0000ff00) >> 8; mac[1] = (uidml & 0x000000ff); mac[2] = (uidl & 0xff000000) >> 24; mac[3] = (uidl & 0x00ff0000) >> 16; mac[4] = (uidl & 0x0000ff00) >> 8; mac[5] = (uidl & 0x000000ff); #endif /* Put the interface in the down state. This usually amounts to resetting * the device and/or calling kinetis_ifdown(). */ kinetis_ifdown(&priv->dev); /* Register the device with the OS so that socket IOCTLs can be performed */ netdev_register(&priv->dev, NET_LL_ETHERNET); return OK; } /**************************************************************************** * Name: up_netinitialize * * Description: * Initialize the first network interface. If there are more than one * interface in the chip, then board-specific logic will have to provide * this function to determine which, if any, Ethernet controllers should * be initialized. * ****************************************************************************/ #if CONFIG_KINETIS_ENETNETHIFS == 1 && !defined(CONFIG_NETDEV_LATEINIT) void up_netinitialize(void) { kinetis_netinitialize(0); } #endif #endif /* KINETIS_NENET > 0 */ #endif /* CONFIG_NET && CONFIG_KINETIS_ENET */
28.239982
97
0.616484
[ "vector", "model" ]
7f7e350d01b05c3b8648f144bdc112e1d7dd21e7
18,158
c
C
main/httpSimpleClient.c
annieZ/EllieSmelly
a61523bad12ab479f989fd1945a97007cb48ed24
[ "MIT" ]
null
null
null
main/httpSimpleClient.c
annieZ/EllieSmelly
a61523bad12ab479f989fd1945a97007cb48ed24
[ "MIT" ]
null
null
null
main/httpSimpleClient.c
annieZ/EllieSmelly
a61523bad12ab479f989fd1945a97007cb48ed24
[ "MIT" ]
null
null
null
/* * FreeRTOS V202107.00 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * https://www.FreeRTOS.org * https://github.com/FreeRTOS * */ /* * for showing use of the HTTP API using a plaintext network connection. * * This example resolves a domain, then establishes a TCP connection with an * HTTP server to nstrate HTTP request/response communication without using * an encrypted channel (i.e. without TLS). After which, HTTP Client library API * is used to send a GET, HEAD, PUT, and POST request in that order. For each * request, the HTTP response from the server (or an error code) is logged. * * This example uses a single task. */ /** * @file PlainTextHTTPExample.c * @brief nstrates usage of the HTTP library. */ /* Standard includes. */ #include <stdio.h> #include <stdlib.h> #include <string.h> /* Kernel includes. */ #include "FreeRTOS.h" #include "task.h" /* HTTP library includes. */ #include "core_http_config.h" /* Transport interface implementation include for plaintext communication. */ #include "using_plaintext.h" /* Common HTTP utilities. */ #include "http_demo_utils.h" /*------------- configurations -------------------------*/ /* Check that a path for HTTP Method POST is defined. */ #ifndef POST_SUBMIT_PATH #error "Please define configPOST_PATH in _config.h." #endif /* Check that a request body to send for the POST request is defined. */ #define configREQUEST_BODY "{ \"message\": \"Hello, world\" }" /* Check that a transport timeout for transport send and receive is defined. */ #ifndef configTRANSPORT_SEND_RECV_TIMEOUT_MS #define configTRANSPORT_SEND_RECV_TIMEOUT_MS ( 1000 ) #endif /* Check that a size for the user buffer is defined. */ #ifndef configUSER_BUFFER_LENGTH #define configUSER_BUFFER_LENGTH ( 2048 ) #endif /** * @brief The length of the server's hostname. */ #define httpexampleSERVER_HOSTNAME_LENGTH ( sizeof( SERVER_HOSTNAME ) - 1 ) /** * @brief The length of the HTTP GET method. */ #define httpexampleHTTP_METHOD_GET_LENGTH ( sizeof( HTTP_METHOD_GET ) - 1 ) /** * @brief The length of the HTTP HEAD method. */ #define httpexampleHTTP_METHOD_HEAD_LENGTH ( sizeof( HTTP_METHOD_HEAD ) - 1 ) /** * @brief The length of the HTTP PUT method. */ #define httpexampleHTTP_METHOD_PUT_LENGTH ( sizeof( HTTP_METHOD_PUT ) - 1 ) /** * @brief The length of the HTTP POST method. */ #define httpexampleHTTP_METHOD_POST_LENGTH ( sizeof( HTTP_METHOD_POST ) - 1 ) /** * @brief The length of the HTTP GET path. */ #define httpexampleGET_PATH_LENGTH ( sizeof( configGET_PATH ) - 1 ) /** * @brief The length of the HTTP HEAD path. */ #define httpexampleHEAD_PATH_LENGTH ( sizeof( configHEAD_PATH ) - 1 ) /** * @brief The length of the HTTP PUT path. */ #define httpexamplePUT_PATH_LENGTH ( sizeof( configPUT_PATH ) - 1 ) /** * @brief The length of the HTTP POST path. */ #define httpexamplePOST_PATH_LENGTH ( sizeof( POST_SUBMIT_PATH ) - 1 ) /** * @brief Length of the request body. */ #define httpexampleREQUEST_BODY_LENGTH ( sizeof( configREQUEST_BODY ) - 1 ) /** * @brief Number of HTTP paths to request. */ #define httpexampleNUMBER_HTTP_PATHS ( 4 ) /** * @brief Each compilation unit that consumes the NetworkContext must define it. * It should contain a single pointer to the type of your desired transport. * When using multiple transports in the same compilation unit, define this pointer as void *. * * @note Transport stacks are defined in FreeRTOS-Plus/Source/Application-Protocols/network_transport. */ struct NetworkContext { PlaintextTransportParams_t * pParams; }; /** * @brief The maximum number of times to run the loop in this . * * @note The loop is attempted to re-run only if it fails in an iteration. * Once the loop succeeds in an iteration, the exits successfully. */ #ifndef HTTP_MAX__LOOP_COUNT #define HTTP_MAX__LOOP_COUNT ( 3 ) #endif /** * @brief Time in ticks to wait between retries of the loop if * loop fails. */ #define DELAY_BETWEEN__RETRY_ITERATIONS_TICKS ( pdMS_TO_TICKS( 5000U ) ) /** * @brief A pair containing a path string of the URI and its length. */ typedef struct httpPathStrings { const char * pcHttpPath; size_t ulHttpPathLength; } httpPathStrings_t; /** * @brief A pair containing an HTTP method string and its length. */ typedef struct httpMethodStrings { const char * pcHttpMethod; size_t ulHttpMethodLength; } httpMethodStrings_t; /** * @brief A buffer used in the for storing HTTP request headers and * HTTP response headers and body. * * @note This shows how the same buffer can be re-used for storing the HTTP * response after the HTTP request is sent out. However, the user can also * decide to use separate buffers for storing the HTTP request and response. */ static uint8_t ucUserBuffer[ configUSER_BUFFER_LENGTH ]; /*-----------------------------------------------------------*/ /** * @brief The task used send receive samples back end * */ static void sendReceiveEllieSample( const char * pcMethod, const char * pcPath); /** * @brief Connect to HTTP server with reconnection retries. * * @param[out] pxNetworkContext The output parameter to return the created network context. * * @return pdPASS on successful connection, pdFAIL otherwise. */ static BaseType_t prvConnectToServer( NetworkContext_t * pxNetworkContext ); /** * @brief Send an HTTP request based on a specified method and path, then * print the response received from the server. * * @param[in] pxTransportInterface The transport interface for making network calls. * @param[in] pcMethod The HTTP request method. * @param[in] xMethodLen The length of the HTTP request method. * @param[in] pcPath The Request-URI to the objects of interest. * @param[in] xPathLen The length of the Request-URI. * * @return pdFAIL on failure; pdPASS on success. */ static BaseType_t prvSendHttpRequest( const TransportInterface_t * pxTransportInterface, const char * pcMethod, size_t xMethodLen, const char * pcPath, size_t xPathLen ); /*-----------------------------------------------------------*/ /*-----------------------------------------------------------*/ /** * @brief Entry point of the . * * This example resolves a domain, then establishes a TCP connection with an * HTTP server to nstrate HTTP request/response communication without using * an encrypted channel (i.e. without TLS). After which, HTTP Client library API * is used to send a GET, HEAD, PUT, and POST request in that order. For each * request, the HTTP response from the server (or an error code) is logged. * * @note This example uses a single task. * */ static void sendReceiveEllieSample( const char * pcMethod, const char * pcPath) { /* The transport layer interface used by the HTTP Client library. */ TransportInterface_t xTransportInterface; /* The network context for the transport layer interface. */ NetworkContext_t xNetworkContext = { 0 }; PlaintextTransportParams_t xPlaintextTransportParams = { 0 }; /* An array of HTTP paths to request. */ const httpPathStrings_t xHttpMethodPaths[] = { { POST_SUBMIT_PATH, httpexamplePOST_PATH_LENGTH } }; /* The respective method for the HTTP paths listed in #httpMethodPaths. */ const httpMethodStrings_t xHttpMethods[] = { { HTTP_METHOD_POST, httpexampleHTTP_METHOD_POST_LENGTH } }; BaseType_t xIsConnectionEstablished = pdFALSE; UBaseType_t uxHttpPathCount = 0U; UBaseType_t uxRunCount = 0UL; /* The user of this must check the logs for any failure codes. */ BaseType_t xStatus = pdPASS; /* Set the pParams member of the network context with desired transport. */ xNetworkContext.pParams = &xPlaintextTransportParams; /**************************** Connect. ******************************/ /* Attempt to connect to the HTTP server. If connection fails, retry after a * timeout. The timeout value will be exponentially increased until either the * maximum number of attempts or the maximum timeout value is reached. The * function returns pdFAIL if the TCP connection cannot be established with * the server after the number of attempts. */ xStatus = connectToServerWithBackoffRetries( prvConnectToServer, &xNetworkContext ); if( xStatus == pdPASS ) { /* Set a flag indicating that a TCP connection has been established. */ xIsConnectionEstablished = pdTRUE; /* Define the transport interface. */ xTransportInterface.pNetworkContext = &xNetworkContext; xTransportInterface.send = Plaintext_FreeRTOS_send; xTransportInterface.recv = Plaintext_FreeRTOS_recv; } else { /* Log error to indicate connection failure after all * reconnect attempts are over. */ LogError( ( "Failed to connect to HTTP server %.*s.", ( int32_t ) httpexampleSERVER_HOSTNAME_LENGTH, SERVER_HOSTNAME ) ); } /*********************** Send HTTP request.************************/ if( xStatus == pdPASS ) { xStatus = prvSendHttpRequest( &xTransportInterface, pcMethod, sizeof (pcMethod), pcPath, sizeof (pcPath)); } /**************************** Disconnect. ******************************/ /* Close the network connection to clean up any system resources that the * may have consumed. */ if( xIsConnectionEstablished == pdTRUE ) { /* Close the network connection. */ Plaintext_FreeRTOS_Disconnect( &xNetworkContext ); } /*********************** Retry in case of failure. ************************/ /* Increment the run count. */ uxRunCount++; if( xStatus == pdPASS ) { LogInfo( ( " iteration %lu was successful.", uxRunCount ) ); } /* Attempt to retry a failed iteration for up to #HTTP_MAX__LOOP_COUNT times. */ else if( uxRunCount < HTTP_MAX__LOOP_COUNT ) { LogWarn( ( " iteration %lu failed. Retrying...", uxRunCount ) ); vTaskDelay( DELAY_BETWEEN__RETRY_ITERATIONS_TICKS ); } /* Failed all #HTTP_MAX__LOOP_COUNT iterations. */ else { LogError( ( "All %d iterations failed.", HTTP_MAX__LOOP_COUNT ) ); } if( xStatus == pdPASS ) { LogInfo( ( "prvHTTPTask() completed successfully. " "Total free heap is %u.\r\n", xPortGetFreeHeapSize() ) ); LogInfo( ( " completed successfully.\r\n" ) ); vTaskDelete( NULL ); } } /*-----------------------------------------------------------*/ static BaseType_t prvConnectToServer( NetworkContext_t * pxNetworkContext ) { BaseType_t xStatus = pdPASS; PlaintextTransportStatus_t xNetworkStatus; configASSERT( pxNetworkContext != NULL ); /* Establish a TCP connection with the HTTP server. This example connects to * the HTTP server as specified in SERVER_HOSTNAME and * HTTP_PORT in _config.h. */ LogInfo( ( "Establishing a TCP connection to %.*s:%d.", ( int32_t ) httpexampleSERVER_HOSTNAME_LENGTH, SERVER_HOSTNAME,HTTP_PORT ) ); xNetworkStatus = Plaintext_FreeRTOS_Connect( pxNetworkContext, SERVER_HOSTNAME, HTTP_PORT, configTRANSPORT_SEND_RECV_TIMEOUT_MS, configTRANSPORT_SEND_RECV_TIMEOUT_MS ); if( xNetworkStatus != PLAINTEXT_TRANSPORT_SUCCESS ) { xStatus = pdFAIL; } return xStatus; } /*-----------------------------------------------------------*/ static BaseType_t prvSendHttpRequest( const TransportInterface_t * pxTransportInterface, const char * pcMethod, size_t xMethodLen, const char * pcPath, size_t xPathLen ) { /* Return value of this method. */ BaseType_t xStatus = pdPASS; /* Configurations of the initial request headers that are passed to * #HTTPClient_InitializeRequestHeaders. */ HTTPRequestInfo_t xRequestInfo; /* Represents a response returned from an HTTP server. */ HTTPResponse_t xResponse; /* Represents header data that will be sent in an HTTP request. */ HTTPRequestHeaders_t xRequestHeaders; /* Return value of all methods from the HTTP Client library API. */ HTTPStatus_t xHTTPStatus = HTTPSuccess; configASSERT( pcMethod != NULL ); configASSERT( pcPath != NULL ); /* Initialize all HTTP Client library API structs to 0. */ ( void ) memset( &xRequestInfo, 0, sizeof( xRequestInfo ) ); ( void ) memset( &xResponse, 0, sizeof( xResponse ) ); ( void ) memset( &xRequestHeaders, 0, sizeof( xRequestHeaders ) ); /* Initialize the request object. */ xRequestInfo.pHost = SERVER_HOSTNAME; xRequestInfo.hostLen = httpexampleSERVER_HOSTNAME_LENGTH; xRequestInfo.pMethod = pcMethod; xRequestInfo.methodLen = xMethodLen; xRequestInfo.pPath = pcPath; xRequestInfo.pathLen = xPathLen; /* Set "Connection" HTTP header to "keep-alive" so that multiple requests * can be sent over the same established TCP connection. */ xRequestInfo.reqFlags = HTTP_REQUEST_KEEP_ALIVE_FLAG; /* Set the buffer used for storing request headers. */ xRequestHeaders.pBuffer = ucUserBuffer; xRequestHeaders.bufferLen = configUSER_BUFFER_LENGTH; xHTTPStatus = HTTPClient_InitializeRequestHeaders( &xRequestHeaders, &xRequestInfo ); if( xHTTPStatus == HTTPSuccess ) { /* Initialize the response object. The same buffer used for storing * request headers is reused here. */ xResponse.pBuffer = ucUserBuffer; xResponse.bufferLen = configUSER_BUFFER_LENGTH; LogInfo( ( "Sending HTTP %.*s request to %.*s%.*s...", ( int32_t ) xRequestInfo.methodLen, xRequestInfo.pMethod, ( int32_t ) httpexampleSERVER_HOSTNAME_LENGTH, configSERVER_HOSTNAME, ( int32_t ) xRequestInfo.pathLen, xRequestInfo.pPath ) ); LogInfo( ( "Request Headers:\n%.*s\n" "Request Body:\n%.*s\n", ( int32_t ) xRequestHeaders.headersLen, ( char * ) xRequestHeaders.pBuffer, ( int32_t ) httpexampleREQUEST_BODY_LENGTH, configREQUEST_BODY ) ); /* Send the request and receive the response. */ xHTTPStatus = HTTPClient_Send( pxTransportInterface, &xRequestHeaders, ( uint8_t * ) configREQUEST_BODY, httpexampleREQUEST_BODY_LENGTH, &xResponse, 0 ); } else { LogError( ( "Failed to initialize HTTP request headers: Error=%s.", HTTPClient_strerror( xHTTPStatus ) ) ); } if( xHTTPStatus == HTTPSuccess ) { LogInfo( ( "Received HTTP response from %.*s%.*s...\n", ( int32_t ) httpexampleSERVER_HOSTNAME_LENGTH, SERVER_HOSTNAME, ( int32_t ) xRequestInfo.pathLen, xRequestInfo.pPath ) ); LogDebug( ( "Response Headers:\n%.*s\n", ( int32_t ) xResponse.headersLen, xResponse.pHeaders ) ); LogDebug( ( "Status Code:\n%u\n", xResponse.statusCode ) ); LogDebug( ( "Response Body:\n%.*s\n", ( int32_t ) xResponse.bodyLen, xResponse.pBody ) ); } else { LogError( ( "Failed to send HTTP %.*s request to %.*s%.*s: Error=%s.", ( int32_t ) xRequestInfo.methodLen, xRequestInfo.pMethod, ( int32_t ) httpexampleSERVER_HOSTNAME_LENGTH, SERVER_HOSTNAME, ( int32_t ) xRequestInfo.pathLen, xRequestInfo.pPath, HTTPClient_strerror( xHTTPStatus ) ) ); } if( xHTTPStatus != HTTPSuccess ) { xStatus = pdFAIL; } return xStatus; }
36.682828
102
0.617689
[ "object" ]
7f84564ee988e19e9c820e26e44510a01e1b9df4
2,936
h
C
third-party/llvm/llvm-src/include/llvm/DebugInfo/PDB/Native/GlobalsStream.h
ram-nad/chapel
1d4aae17e58699c1481d2b2209c9d1fcd2658fc8
[ "ECL-2.0", "Apache-2.0" ]
15
2019-08-05T01:24:20.000Z
2022-01-12T08:19:55.000Z
third-party/llvm/llvm-src/include/llvm/DebugInfo/PDB/Native/GlobalsStream.h
ram-nad/chapel
1d4aae17e58699c1481d2b2209c9d1fcd2658fc8
[ "ECL-2.0", "Apache-2.0" ]
4
2017-12-13T18:19:11.000Z
2018-11-17T04:37:14.000Z
third-party/llvm/llvm-src/include/llvm/DebugInfo/PDB/Native/GlobalsStream.h
ram-nad/chapel
1d4aae17e58699c1481d2b2209c9d1fcd2658fc8
[ "ECL-2.0", "Apache-2.0" ]
9
2019-06-11T06:15:44.000Z
2022-03-07T16:34:50.000Z
//===- GlobalsStream.h - PDB Index of Symbols by Name -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_DEBUGINFO_PDB_RAW_GLOBALS_STREAM_H #define LLVM_DEBUGINFO_PDB_RAW_GLOBALS_STREAM_H #include "llvm/ADT/iterator.h" #include "llvm/DebugInfo/CodeView/SymbolRecord.h" #include "llvm/DebugInfo/MSF/MappedBlockStream.h" #include "llvm/DebugInfo/PDB/Native/RawConstants.h" #include "llvm/DebugInfo/PDB/Native/RawTypes.h" #include "llvm/DebugInfo/PDB/PDBTypes.h" #include "llvm/Support/BinaryStreamArray.h" #include "llvm/Support/Error.h" namespace llvm { namespace pdb { class DbiStream; class PDBFile; class SymbolStream; /// Iterator over hash records producing symbol record offsets. Abstracts away /// the fact that symbol record offsets on disk are off-by-one. class GSIHashIterator : public iterator_adaptor_base< GSIHashIterator, FixedStreamArrayIterator<PSHashRecord>, std::random_access_iterator_tag, const uint32_t> { public: template <typename T> GSIHashIterator(T &&v) : GSIHashIterator::iterator_adaptor_base(std::forward<T &&>(v)) {} uint32_t operator*() const { uint32_t Off = this->I->Off; return --Off; } }; /// From https://github.com/Microsoft/microsoft-pdb/blob/master/PDB/dbi/gsi.cpp enum : unsigned { IPHR_HASH = 4096 }; /// A readonly view of a hash table used in the globals and publics streams. /// Most clients will only want to iterate this to get symbol record offsets /// into the PDB symbol stream. class GSIHashTable { public: const GSIHashHeader *HashHdr; FixedStreamArray<PSHashRecord> HashRecords; FixedStreamArray<support::ulittle32_t> HashBitmap; FixedStreamArray<support::ulittle32_t> HashBuckets; std::array<int32_t, IPHR_HASH + 1> BucketMap; Error read(BinaryStreamReader &Reader); uint32_t getVerSignature() const { return HashHdr->VerSignature; } uint32_t getVerHeader() const { return HashHdr->VerHdr; } uint32_t getHashRecordSize() const { return HashHdr->HrSize; } uint32_t getNumBuckets() const { return HashHdr->NumBuckets; } typedef GSIHashHeader iterator; GSIHashIterator begin() const { return GSIHashIterator(HashRecords.begin()); } GSIHashIterator end() const { return GSIHashIterator(HashRecords.end()); } }; class GlobalsStream { public: explicit GlobalsStream(std::unique_ptr<msf::MappedBlockStream> Stream); ~GlobalsStream(); const GSIHashTable &getGlobalsTable() const { return GlobalsTable; } Error reload(); std::vector<std::pair<uint32_t, codeview::CVSymbol>> findRecordsByName(StringRef Name, const SymbolStream &Symbols) const; private: GSIHashTable GlobalsTable; std::unique_ptr<msf::MappedBlockStream> Stream; }; } } #endif
32.988764
80
0.724796
[ "vector" ]
7f8708a68126b91c4d0525c314f9e450ab5ed631
9,814
h
C
openfst-1.3.2/src/include/fst/equivalent.h
glecorve/rnnlm2wfst
2bb1dcfb0ee34ddfb7959614820aec5fc79e18d4
[ "Apache-2.0" ]
51
2015-01-10T09:46:03.000Z
2022-03-30T00:07:19.000Z
openfst-1.3.2/src/include/fst/equivalent.h
glecorve/rnnlm2wfst
2bb1dcfb0ee34ddfb7959614820aec5fc79e18d4
[ "Apache-2.0" ]
3
2017-01-18T07:10:42.000Z
2020-03-16T03:43:35.000Z
openfst-1.3.2/include/fst/equivalent.h
glecorve/rnnlm2wfst
2bb1dcfb0ee34ddfb7959614820aec5fc79e18d4
[ "Apache-2.0" ]
20
2015-01-19T05:11:34.000Z
2022-02-08T01:57:20.000Z
// equivalent.h // 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. // // Copyright 2005-2010 Google, Inc. // Author: wojciech@google.com (Wojciech Skut) // // \file Functions and classes to determine the equivalence of two // FSTs. #ifndef FST_LIB_EQUIVALENT_H__ #define FST_LIB_EQUIVALENT_H__ #include <algorithm> #include <deque> #include <tr1/unordered_map> using std::tr1::unordered_map; using std::tr1::unordered_multimap; #include <utility> using std::pair; using std::make_pair; #include <vector> using std::vector; #include <fst/encode.h> #include <fst/push.h> #include <fst/union-find.h> #include <fst/vector-fst.h> namespace fst { // Traits-like struct holding utility functions/typedefs/constants for // the equivalence algorithm. // // Encoding device: in order to make the statesets of the two acceptors // disjoint, we map Arc::StateId on the type MappedId. The states of // the first acceptor are mapped on odd numbers (s -> 2s + 1), and // those of the second one on even numbers (s -> 2s + 2). The number 0 // is reserved for an implicit (non-final) 'dead state' (required for // the correct treatment of non-coaccessible states; kNoStateId is // mapped to kDeadState for both acceptors). The union-find algorithm // operates on the mapped IDs. template <class Arc> struct EquivalenceUtil { typedef typename Arc::StateId StateId; typedef typename Arc::Weight Weight; typedef StateId MappedId; // ID for an equivalence class. // MappedId for an implicit dead state. static const MappedId kDeadState = 0; // MappedId for lookup failure. static const MappedId kInvalidId = -1; // Maps state ID to the representative of the corresponding // equivalence class. The parameter 'which_fst' takes the values 1 // and 2, identifying the input FST. static MappedId MapState(StateId s, int32 which_fst) { return (kNoStateId == s) ? kDeadState : (static_cast<MappedId>(s) << 1) + which_fst; } // Maps set ID to State ID. static StateId UnMapState(MappedId id) { return static_cast<StateId>((--id) >> 1); } // Convenience function: checks if state with MappedId 's' is final // in acceptor 'fa'. static bool IsFinal(const Fst<Arc> &fa, MappedId s) { return (kDeadState == s) ? false : (fa.Final(UnMapState(s)) != Weight::Zero()); } // Convenience function: returns the representative of 'id' in 'sets', // creating a new set if needed. static MappedId FindSet(UnionFind<MappedId> *sets, MappedId id) { MappedId repr = sets->FindSet(id); if (repr != kInvalidId) { return repr; } else { sets->MakeSet(id); return id; } } }; template <class Arc> const typename EquivalenceUtil<Arc>::MappedId EquivalenceUtil<Arc>::kDeadState; template <class Arc> const typename EquivalenceUtil<Arc>::MappedId EquivalenceUtil<Arc>::kInvalidId; // Equivalence checking algorithm: determines if the two FSTs // <code>fst1</code> and <code>fst2</code> are equivalent. The input // FSTs must be deterministic input-side epsilon-free acceptors, // unweighted or with weights over a left semiring. Two acceptors are // considered equivalent if they accept exactly the same set of // strings (with the same weights). // // The algorithm (cf. Aho, Hopcroft and Ullman, "The Design and // Analysis of Computer Programs") successively constructs sets of // states that can be reached by the same prefixes, starting with a // set containing the start states of both acceptors. A disjoint tree // forest (the union-find algorithm) is used to represent the sets of // states. The algorithm returns 'false' if one of the constructed // sets contains both final and non-final states. Returns optional error // value (when FLAGS_error_fatal = false). // // Complexity: quasi-linear, i.e. O(n G(n)), where // n = |S1| + |S2| is the number of states in both acceptors // G(n) is a very slowly growing function that can be approximated // by 4 by all practical purposes. // template <class Arc> bool Equivalent(const Fst<Arc> &fst1, const Fst<Arc> &fst2, double delta = kDelta, bool *error = 0) { typedef typename Arc::Weight Weight; if (error) *error = false; // Check that the symbol table are compatible if (!CompatSymbols(fst1.InputSymbols(), fst2.InputSymbols()) || !CompatSymbols(fst1.OutputSymbols(), fst2.OutputSymbols())) { FSTERROR() << "Equivalent: input/output symbol tables of 1st argument " << "do not match input/output symbol tables of 2nd argument"; if (error) *error = true; return false; } // Check properties first: uint64 props = kNoEpsilons | kIDeterministic | kAcceptor; if (fst1.Properties(props, true) != props) { FSTERROR() << "Equivalent: first argument not an" << " epsilon-free deterministic acceptor"; if (error) *error = true; return false; } if (fst2.Properties(props, true) != props) { FSTERROR() << "Equivalent: second argument not an" << " epsilon-free deterministic acceptor"; if (error) *error = true; return false; } if ((fst1.Properties(kUnweighted , true) != kUnweighted) || (fst2.Properties(kUnweighted , true) != kUnweighted)) { VectorFst<Arc> efst1(fst1); VectorFst<Arc> efst2(fst2); Push(&efst1, REWEIGHT_TO_INITIAL, delta); Push(&efst2, REWEIGHT_TO_INITIAL, delta); ArcMap(&efst1, QuantizeMapper<Arc>(delta)); ArcMap(&efst2, QuantizeMapper<Arc>(delta)); EncodeMapper<Arc> mapper(kEncodeWeights|kEncodeLabels, ENCODE); ArcMap(&efst1, &mapper); ArcMap(&efst2, &mapper); return Equivalent(efst1, efst2); } // Convenience typedefs: typedef typename Arc::StateId StateId; typedef EquivalenceUtil<Arc> Util; typedef typename Util::MappedId MappedId; enum { FST1 = 1, FST2 = 2 }; // Required by Util::MapState(...) MappedId s1 = Util::MapState(fst1.Start(), FST1); MappedId s2 = Util::MapState(fst2.Start(), FST2); // The union-find structure. UnionFind<MappedId> eq_classes(1000, Util::kInvalidId); // Initialize the union-find structure. eq_classes.MakeSet(s1); eq_classes.MakeSet(s2); // Data structure for the (partial) acceptor transition function of // fst1 and fst2: input labels mapped to pairs of MappedId's // representing destination states of the corresponding arcs in fst1 // and fst2, respectively. typedef unordered_map<typename Arc::Label, pair<MappedId, MappedId> > Label2StatePairMap; Label2StatePairMap arc_pairs; // Pairs of MappedId's to be processed, organized in a queue. deque<pair<MappedId, MappedId> > q; bool ret = true; // Early return if the start states differ w.r.t. being final. if (Util::IsFinal(fst1, s1) != Util::IsFinal(fst2, s2)) { ret = false; } // Main loop: explores the two acceptors in a breadth-first manner, // updating the equivalence relation on the statesets. Loop // invariant: each block of states contains either final states only // or non-final states only. for (q.push_back(make_pair(s1, s2)); ret && !q.empty(); q.pop_front()) { s1 = q.front().first; s2 = q.front().second; // Representatives of the equivalence classes of s1/s2. MappedId rep1 = Util::FindSet(&eq_classes, s1); MappedId rep2 = Util::FindSet(&eq_classes, s2); if (rep1 != rep2) { eq_classes.Union(rep1, rep2); arc_pairs.clear(); // Copy outgoing arcs starting at s1 into the hashtable. if (Util::kDeadState != s1) { ArcIterator<Fst<Arc> > arc_iter(fst1, Util::UnMapState(s1)); for (; !arc_iter.Done(); arc_iter.Next()) { const Arc &arc = arc_iter.Value(); if (arc.weight != Weight::Zero()) { // Zero-weight arcs // are treated as // non-exisitent. arc_pairs[arc.ilabel].first = Util::MapState(arc.nextstate, FST1); } } } // Copy outgoing arcs starting at s2 into the hashtable. if (Util::kDeadState != s2) { ArcIterator<Fst<Arc> > arc_iter(fst2, Util::UnMapState(s2)); for (; !arc_iter.Done(); arc_iter.Next()) { const Arc &arc = arc_iter.Value(); if (arc.weight != Weight::Zero()) { // Zero-weight arcs // are treated as // non-existent. arc_pairs[arc.ilabel].second = Util::MapState(arc.nextstate, FST2); } } } // Iterate through the hashtable and process pairs of target // states. for (typename Label2StatePairMap::const_iterator arc_iter = arc_pairs.begin(); arc_iter != arc_pairs.end(); ++arc_iter) { const pair<MappedId, MappedId> &p = arc_iter->second; if (Util::IsFinal(fst1, p.first) != Util::IsFinal(fst2, p.second)) { // Detected inconsistency: return false. ret = false; break; } q.push_back(p); } } } if (fst1.Properties(kError, false) || fst2.Properties(kError, false)) { if (error) *error = true; return false; } return ret; } } // namespace fst #endif // FST_LIB_EQUIVALENT_H__
35.687273
79
0.660077
[ "vector" ]
7f8a283e76eba50d9eae713c19fff5691a20c99f
28,637
c
C
dlls/mf/session.c
sedwards/winexrdp
4ff5be5a880e4a976c13fdc707efcc82bc5970c6
[ "MIT" ]
42
2018-12-28T11:06:21.000Z
2022-02-26T23:29:51.000Z
dlls/mf/session.c
sedwards/winexrdp
4ff5be5a880e4a976c13fdc707efcc82bc5970c6
[ "MIT" ]
20
2018-12-15T13:10:16.000Z
2019-10-21T09:51:56.000Z
dlls/mf/session.c
sedwards/winexrdp
4ff5be5a880e4a976c13fdc707efcc82bc5970c6
[ "MIT" ]
3
2019-01-03T21:40:44.000Z
2019-05-20T12:53:35.000Z
/* * Copyright 2017 Nikolay Sivov * * 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 "mfidl.h" #include "mfapi.h" #include "mferror.h" #include "wine/debug.h" #include "wine/heap.h" #include "wine/list.h" WINE_DEFAULT_DEBUG_CHANNEL(mfplat); struct media_session { IMFMediaSession IMFMediaSession_iface; LONG refcount; IMFMediaEventQueue *event_queue; }; struct clock_sink { struct list entry; IMFClockStateSink *state_sink; }; enum clock_command { CLOCK_CMD_START = 0, CLOCK_CMD_STOP, CLOCK_CMD_PAUSE, CLOCK_CMD_MAX, }; enum clock_notification { CLOCK_NOTIFY_START, CLOCK_NOTIFY_STOP, CLOCK_NOTIFY_PAUSE, CLOCK_NOTIFY_RESTART, }; struct sink_notification { IUnknown IUnknown_iface; LONG refcount; MFTIME system_time; LONGLONG offset; enum clock_notification notification; IMFClockStateSink *sink; }; struct presentation_clock { IMFPresentationClock IMFPresentationClock_iface; IMFRateControl IMFRateControl_iface; IMFTimer IMFTimer_iface; IMFShutdown IMFShutdown_iface; IMFAsyncCallback IMFAsyncCallback_iface; LONG refcount; IMFPresentationTimeSource *time_source; IMFClockStateSink *time_source_sink; MFCLOCK_STATE state; struct list sinks; CRITICAL_SECTION cs; }; static inline struct media_session *impl_from_IMFMediaSession(IMFMediaSession *iface) { return CONTAINING_RECORD(iface, struct media_session, IMFMediaSession_iface); } static struct presentation_clock *impl_from_IMFPresentationClock(IMFPresentationClock *iface) { return CONTAINING_RECORD(iface, struct presentation_clock, IMFPresentationClock_iface); } static struct presentation_clock *impl_from_IMFRateControl(IMFRateControl *iface) { return CONTAINING_RECORD(iface, struct presentation_clock, IMFRateControl_iface); } static struct presentation_clock *impl_from_IMFTimer(IMFTimer *iface) { return CONTAINING_RECORD(iface, struct presentation_clock, IMFTimer_iface); } static struct presentation_clock *impl_from_IMFShutdown(IMFShutdown *iface) { return CONTAINING_RECORD(iface, struct presentation_clock, IMFShutdown_iface); } static struct presentation_clock *impl_from_IMFAsyncCallback(IMFAsyncCallback *iface) { return CONTAINING_RECORD(iface, struct presentation_clock, IMFAsyncCallback_iface); } static struct sink_notification *impl_from_IUnknown(IUnknown *iface) { return CONTAINING_RECORD(iface, struct sink_notification, IUnknown_iface); } static HRESULT WINAPI mfsession_QueryInterface(IMFMediaSession *iface, REFIID riid, void **out) { struct media_session *session = impl_from_IMFMediaSession(iface); TRACE("(%p)->(%s %p)\n", iface, debugstr_guid(riid), out); if (IsEqualIID(riid, &IID_IMFMediaSession) || IsEqualIID(riid, &IID_IMFMediaEventGenerator) || IsEqualIID(riid, &IID_IUnknown)) { *out = &session->IMFMediaSession_iface; IMFMediaSession_AddRef(iface); return S_OK; } WARN("Unsupported %s.\n", debugstr_guid(riid)); *out = NULL; return E_NOINTERFACE; } static ULONG WINAPI mfsession_AddRef(IMFMediaSession *iface) { struct media_session *session = impl_from_IMFMediaSession(iface); ULONG refcount = InterlockedIncrement(&session->refcount); TRACE("(%p) refcount=%u\n", iface, refcount); return refcount; } static ULONG WINAPI mfsession_Release(IMFMediaSession *iface) { struct media_session *session = impl_from_IMFMediaSession(iface); ULONG refcount = InterlockedDecrement(&session->refcount); TRACE("(%p) refcount=%u\n", iface, refcount); if (!refcount) { if (session->event_queue) IMFMediaEventQueue_Release(session->event_queue); heap_free(session); } return refcount; } static HRESULT WINAPI mfsession_GetEvent(IMFMediaSession *iface, DWORD flags, IMFMediaEvent **event) { struct media_session *session = impl_from_IMFMediaSession(iface); TRACE("(%p)->(%#x, %p)\n", iface, flags, event); return IMFMediaEventQueue_GetEvent(session->event_queue, flags, event); } static HRESULT WINAPI mfsession_BeginGetEvent(IMFMediaSession *iface, IMFAsyncCallback *callback, IUnknown *state) { struct media_session *session = impl_from_IMFMediaSession(iface); TRACE("(%p)->(%p, %p)\n", iface, callback, state); return IMFMediaEventQueue_BeginGetEvent(session->event_queue, callback, state); } static HRESULT WINAPI mfsession_EndGetEvent(IMFMediaSession *iface, IMFAsyncResult *result, IMFMediaEvent **event) { struct media_session *session = impl_from_IMFMediaSession(iface); TRACE("(%p)->(%p, %p)\n", iface, result, event); return IMFMediaEventQueue_EndGetEvent(session->event_queue, result, event); } static HRESULT WINAPI mfsession_QueueEvent(IMFMediaSession *iface, MediaEventType event_type, REFGUID ext_type, HRESULT hr, const PROPVARIANT *value) { struct media_session *session = impl_from_IMFMediaSession(iface); TRACE("(%p)->(%d, %s, %#x, %p)\n", iface, event_type, debugstr_guid(ext_type), hr, value); return IMFMediaEventQueue_QueueEventParamVar(session->event_queue, event_type, ext_type, hr, value); } static HRESULT WINAPI mfsession_SetTopology(IMFMediaSession *iface, DWORD flags, IMFTopology *topology) { FIXME("(%p)->(%#x, %p)\n", iface, flags, topology); return E_NOTIMPL; } static HRESULT WINAPI mfsession_ClearTopologies(IMFMediaSession *iface) { FIXME("(%p)\n", iface); return E_NOTIMPL; } static HRESULT WINAPI mfsession_Start(IMFMediaSession *iface, const GUID *format, const PROPVARIANT *start) { FIXME("(%p)->(%s, %p)\n", iface, debugstr_guid(format), start); return E_NOTIMPL; } static HRESULT WINAPI mfsession_Pause(IMFMediaSession *iface) { FIXME("(%p)\n", iface); return E_NOTIMPL; } static HRESULT WINAPI mfsession_Stop(IMFMediaSession *iface) { FIXME("(%p)\n", iface); return E_NOTIMPL; } static HRESULT WINAPI mfsession_Close(IMFMediaSession *iface) { FIXME("(%p)\n", iface); return S_OK; } static HRESULT WINAPI mfsession_Shutdown(IMFMediaSession *iface) { struct media_session *session = impl_from_IMFMediaSession(iface); FIXME("(%p)\n", iface); IMFMediaEventQueue_Shutdown(session->event_queue); return E_NOTIMPL; } static HRESULT WINAPI mfsession_GetClock(IMFMediaSession *iface, IMFClock **clock) { FIXME("(%p)->(%p)\n", iface, clock); return E_NOTIMPL; } static HRESULT WINAPI mfsession_GetSessionCapabilities(IMFMediaSession *iface, DWORD *caps) { FIXME("(%p)->(%p)\n", iface, caps); return E_NOTIMPL; } static HRESULT WINAPI mfsession_GetFullTopology(IMFMediaSession *iface, DWORD flags, TOPOID id, IMFTopology **topology) { FIXME("(%p)->(%#x, %s, %p)\n", iface, flags, wine_dbgstr_longlong(id), topology); return E_NOTIMPL; } static const IMFMediaSessionVtbl mfmediasessionvtbl = { mfsession_QueryInterface, mfsession_AddRef, mfsession_Release, mfsession_GetEvent, mfsession_BeginGetEvent, mfsession_EndGetEvent, mfsession_QueueEvent, mfsession_SetTopology, mfsession_ClearTopologies, mfsession_Start, mfsession_Pause, mfsession_Stop, mfsession_Close, mfsession_Shutdown, mfsession_GetClock, mfsession_GetSessionCapabilities, mfsession_GetFullTopology, }; /*********************************************************************** * MFCreateMediaSession (mf.@) */ HRESULT WINAPI MFCreateMediaSession(IMFAttributes *config, IMFMediaSession **session) { struct media_session *object; HRESULT hr; TRACE("(%p, %p)\n", config, session); if (config) FIXME("session configuration ignored\n"); object = heap_alloc_zero(sizeof(*object)); if (!object) return E_OUTOFMEMORY; object->IMFMediaSession_iface.lpVtbl = &mfmediasessionvtbl; object->refcount = 1; if (FAILED(hr = MFCreateEventQueue(&object->event_queue))) { IMFMediaSession_Release(&object->IMFMediaSession_iface); return hr; } *session = &object->IMFMediaSession_iface; return S_OK; } static HRESULT WINAPI present_clock_QueryInterface(IMFPresentationClock *iface, REFIID riid, void **out) { struct presentation_clock *clock = impl_from_IMFPresentationClock(iface); TRACE("%p, %s, %p.\n", iface, debugstr_guid(riid), out); if (IsEqualIID(riid, &IID_IMFPresentationClock) || IsEqualIID(riid, &IID_IMFClock) || IsEqualIID(riid, &IID_IUnknown)) { *out = &clock->IMFPresentationClock_iface; } else if (IsEqualIID(riid, &IID_IMFRateControl)) { *out = &clock->IMFRateControl_iface; } else if (IsEqualIID(riid, &IID_IMFTimer)) { *out = &clock->IMFTimer_iface; } else if (IsEqualIID(riid, &IID_IMFShutdown)) { *out = &clock->IMFShutdown_iface; } else { WARN("Unsupported %s.\n", debugstr_guid(riid)); *out = NULL; return E_NOINTERFACE; } IUnknown_AddRef((IUnknown *)*out); return S_OK; } static ULONG WINAPI present_clock_AddRef(IMFPresentationClock *iface) { struct presentation_clock *clock = impl_from_IMFPresentationClock(iface); ULONG refcount = InterlockedIncrement(&clock->refcount); TRACE("%p, refcount %u.\n", iface, refcount); return refcount; } static ULONG WINAPI present_clock_Release(IMFPresentationClock *iface) { struct presentation_clock *clock = impl_from_IMFPresentationClock(iface); ULONG refcount = InterlockedDecrement(&clock->refcount); struct clock_sink *sink, *sink2; TRACE("%p, refcount %u.\n", iface, refcount); if (!refcount) { if (clock->time_source) IMFPresentationTimeSource_Release(clock->time_source); if (clock->time_source_sink) IMFClockStateSink_Release(clock->time_source_sink); LIST_FOR_EACH_ENTRY_SAFE(sink, sink2, &clock->sinks, struct clock_sink, entry) { list_remove(&sink->entry); IMFClockStateSink_Release(sink->state_sink); heap_free(sink); } DeleteCriticalSection(&clock->cs); heap_free(clock); } return refcount; } static HRESULT WINAPI present_clock_GetClockCharacteristics(IMFPresentationClock *iface, DWORD *flags) { FIXME("%p, %p.\n", iface, flags); return E_NOTIMPL; } static HRESULT WINAPI present_clock_GetCorrelatedTime(IMFPresentationClock *iface, DWORD reserved, LONGLONG *clock_time, MFTIME *system_time) { FIXME("%p, %#x, %p, %p.\n", iface, reserved, clock_time, system_time); return E_NOTIMPL; } static HRESULT WINAPI present_clock_GetContinuityKey(IMFPresentationClock *iface, DWORD *key) { TRACE("%p, %p.\n", iface, key); *key = 0; return S_OK; } static HRESULT WINAPI present_clock_GetState(IMFPresentationClock *iface, DWORD reserved, MFCLOCK_STATE *state) { struct presentation_clock *clock = impl_from_IMFPresentationClock(iface); TRACE("%p, %#x, %p.\n", iface, reserved, state); EnterCriticalSection(&clock->cs); *state = clock->state; LeaveCriticalSection(&clock->cs); return S_OK; } static HRESULT WINAPI present_clock_GetProperties(IMFPresentationClock *iface, MFCLOCK_PROPERTIES *props) { FIXME("%p, %p.\n", iface, props); return E_NOTIMPL; } static HRESULT WINAPI present_clock_SetTimeSource(IMFPresentationClock *iface, IMFPresentationTimeSource *time_source) { struct presentation_clock *clock = impl_from_IMFPresentationClock(iface); HRESULT hr; TRACE("%p, %p.\n", iface, time_source); EnterCriticalSection(&clock->cs); if (clock->time_source) IMFPresentationTimeSource_Release(clock->time_source); if (clock->time_source_sink) IMFClockStateSink_Release(clock->time_source_sink); clock->time_source = NULL; clock->time_source_sink = NULL; hr = IMFPresentationTimeSource_QueryInterface(time_source, &IID_IMFClockStateSink, (void **)&clock->time_source_sink); if (SUCCEEDED(hr)) { clock->time_source = time_source; IMFPresentationTimeSource_AddRef(clock->time_source); } LeaveCriticalSection(&clock->cs); return hr; } static HRESULT WINAPI present_clock_GetTimeSource(IMFPresentationClock *iface, IMFPresentationTimeSource **time_source) { struct presentation_clock *clock = impl_from_IMFPresentationClock(iface); HRESULT hr = S_OK; TRACE("%p, %p.\n", iface, time_source); EnterCriticalSection(&clock->cs); if (clock->time_source) { *time_source = clock->time_source; IMFPresentationTimeSource_AddRef(*time_source); } else hr = MF_E_CLOCK_NO_TIME_SOURCE; LeaveCriticalSection(&clock->cs); return hr; } static HRESULT WINAPI present_clock_GetTime(IMFPresentationClock *iface, MFTIME *time) { FIXME("%p, %p.\n", iface, time); return E_NOTIMPL; } static HRESULT WINAPI present_clock_AddClockStateSink(IMFPresentationClock *iface, IMFClockStateSink *state_sink) { struct presentation_clock *clock = impl_from_IMFPresentationClock(iface); struct clock_sink *sink, *cur; HRESULT hr = S_OK; TRACE("%p, %p.\n", iface, state_sink); if (!state_sink) return E_INVALIDARG; sink = heap_alloc(sizeof(*sink)); if (!sink) return E_OUTOFMEMORY; sink->state_sink = state_sink; IMFClockStateSink_AddRef(sink->state_sink); EnterCriticalSection(&clock->cs); LIST_FOR_EACH_ENTRY(cur, &clock->sinks, struct clock_sink, entry) { if (cur->state_sink == state_sink) { hr = E_INVALIDARG; break; } } if (SUCCEEDED(hr)) list_add_tail(&clock->sinks, &sink->entry); LeaveCriticalSection(&clock->cs); if (FAILED(hr)) { IMFClockStateSink_Release(sink->state_sink); heap_free(sink); } return hr; } static HRESULT WINAPI present_clock_RemoveClockStateSink(IMFPresentationClock *iface, IMFClockStateSink *state_sink) { struct presentation_clock *clock = impl_from_IMFPresentationClock(iface); struct clock_sink *sink; TRACE("%p, %p.\n", iface, state_sink); if (!state_sink) return E_INVALIDARG; EnterCriticalSection(&clock->cs); LIST_FOR_EACH_ENTRY(sink, &clock->sinks, struct clock_sink, entry) { if (sink->state_sink == state_sink) { IMFClockStateSink_Release(sink->state_sink); list_remove(&sink->entry); heap_free(sink); break; } } LeaveCriticalSection(&clock->cs); return S_OK; } static HRESULT WINAPI sink_notification_QueryInterface(IUnknown *iface, REFIID riid, void **out) { if (IsEqualIID(riid, &IID_IUnknown)) { *out = iface; IUnknown_AddRef(iface); return S_OK; } WARN("Unsupported %s.\n", debugstr_guid(riid)); *out = NULL; return E_NOINTERFACE; } static ULONG WINAPI sink_notification_AddRef(IUnknown *iface) { struct sink_notification *notification = impl_from_IUnknown(iface); ULONG refcount = InterlockedIncrement(&notification->refcount); TRACE("%p, refcount %u.\n", iface, refcount); return refcount; } static ULONG WINAPI sink_notification_Release(IUnknown *iface) { struct sink_notification *notification = impl_from_IUnknown(iface); ULONG refcount = InterlockedDecrement(&notification->refcount); TRACE("%p, refcount %u.\n", iface, refcount); if (!refcount) { IMFClockStateSink_Release(notification->sink); heap_free(notification); } return refcount; } static const IUnknownVtbl sinknotificationvtbl = { sink_notification_QueryInterface, sink_notification_AddRef, sink_notification_Release, }; static HRESULT create_sink_notification(MFTIME system_time, LONGLONG offset, enum clock_notification notification, IMFClockStateSink *sink, IUnknown **out) { struct sink_notification *object; object = heap_alloc(sizeof(*object)); if (!object) return E_OUTOFMEMORY; object->IUnknown_iface.lpVtbl = &sinknotificationvtbl; object->refcount = 1; object->system_time = system_time; object->offset = offset; object->notification = notification; object->sink = sink; IMFClockStateSink_AddRef(object->sink); *out = &object->IUnknown_iface; return S_OK; } static HRESULT clock_call_state_change(MFTIME system_time, LONGLONG offset, enum clock_notification notification, IMFClockStateSink *sink) { HRESULT hr = S_OK; switch (notification) { case CLOCK_NOTIFY_START: hr = IMFClockStateSink_OnClockStart(sink, system_time, offset); break; case CLOCK_NOTIFY_STOP: hr = IMFClockStateSink_OnClockStop(sink, system_time); break; case CLOCK_NOTIFY_PAUSE: hr = IMFClockStateSink_OnClockPause(sink, system_time); break; case CLOCK_NOTIFY_RESTART: hr = IMFClockStateSink_OnClockRestart(sink, system_time); break; default: ; } return hr; } static HRESULT clock_change_state(struct presentation_clock *clock, enum clock_command command, LONGLONG offset) { static const BYTE state_change_is_allowed[MFCLOCK_STATE_PAUSED+1][CLOCK_CMD_MAX] = { /* S S* P */ /* INVALID */ { 1, 1, 1 }, /* RUNNING */ { 1, 1, 1 }, /* STOPPED */ { 1, 1, 0 }, /* PAUSED */ { 1, 1, 0 }, }; static const MFCLOCK_STATE states[CLOCK_CMD_MAX] = { /* CLOCK_CMD_START */ MFCLOCK_STATE_RUNNING, /* CLOCK_CMD_STOP */ MFCLOCK_STATE_STOPPED, /* CLOCK_CMD_PAUSE */ MFCLOCK_STATE_PAUSED, }; enum clock_notification notification; struct clock_sink *sink; IUnknown *notify_object; IMFAsyncResult *result; MFTIME system_time; HRESULT hr; if (clock->state == states[command] && clock->state != MFCLOCK_STATE_RUNNING) return MF_E_CLOCK_STATE_ALREADY_SET; if (!state_change_is_allowed[clock->state][command]) return MF_E_INVALIDREQUEST; system_time = MFGetSystemTime(); switch (command) { case CLOCK_CMD_START: if (clock->state == MFCLOCK_STATE_PAUSED && offset == PRESENTATION_CURRENT_POSITION) notification = CLOCK_NOTIFY_RESTART; else notification = CLOCK_NOTIFY_START; break; case CLOCK_CMD_STOP: notification = CLOCK_NOTIFY_STOP; break; case CLOCK_CMD_PAUSE: notification = CLOCK_NOTIFY_PAUSE; break; default: ; } if (FAILED(hr = clock_call_state_change(system_time, offset, notification, clock->time_source_sink))) return hr; clock->state = states[command]; LIST_FOR_EACH_ENTRY(sink, &clock->sinks, struct clock_sink, entry) { if (SUCCEEDED(create_sink_notification(system_time, offset, notification, sink->state_sink, &notify_object))) { hr = MFCreateAsyncResult(notify_object, &clock->IMFAsyncCallback_iface, NULL, &result); IUnknown_Release(notify_object); if (SUCCEEDED(hr)) { MFPutWorkItemEx(MFASYNC_CALLBACK_QUEUE_STANDARD, result); IMFAsyncResult_Release(result); } } } return S_OK; } static HRESULT WINAPI present_clock_Start(IMFPresentationClock *iface, LONGLONG start_offset) { struct presentation_clock *clock = impl_from_IMFPresentationClock(iface); HRESULT hr; TRACE("%p, %s.\n", iface, wine_dbgstr_longlong(start_offset)); EnterCriticalSection(&clock->cs); hr = clock_change_state(clock, CLOCK_CMD_START, start_offset); LeaveCriticalSection(&clock->cs); return hr; } static HRESULT WINAPI present_clock_Stop(IMFPresentationClock *iface) { struct presentation_clock *clock = impl_from_IMFPresentationClock(iface); HRESULT hr; TRACE("%p.\n", iface); EnterCriticalSection(&clock->cs); hr = clock_change_state(clock, CLOCK_CMD_STOP, 0); LeaveCriticalSection(&clock->cs); return hr; } static HRESULT WINAPI present_clock_Pause(IMFPresentationClock *iface) { struct presentation_clock *clock = impl_from_IMFPresentationClock(iface); HRESULT hr; TRACE("%p.\n", iface); EnterCriticalSection(&clock->cs); hr = clock_change_state(clock, CLOCK_CMD_PAUSE, 0); LeaveCriticalSection(&clock->cs); return hr; } static const IMFPresentationClockVtbl presentationclockvtbl = { present_clock_QueryInterface, present_clock_AddRef, present_clock_Release, present_clock_GetClockCharacteristics, present_clock_GetCorrelatedTime, present_clock_GetContinuityKey, present_clock_GetState, present_clock_GetProperties, present_clock_SetTimeSource, present_clock_GetTimeSource, present_clock_GetTime, present_clock_AddClockStateSink, present_clock_RemoveClockStateSink, present_clock_Start, present_clock_Stop, present_clock_Pause, }; static HRESULT WINAPI present_clock_rate_control_QueryInterface(IMFRateControl *iface, REFIID riid, void **out) { struct presentation_clock *clock = impl_from_IMFRateControl(iface); return IMFPresentationClock_QueryInterface(&clock->IMFPresentationClock_iface, riid, out); } static ULONG WINAPI present_clock_rate_control_AddRef(IMFRateControl *iface) { struct presentation_clock *clock = impl_from_IMFRateControl(iface); return IMFPresentationClock_AddRef(&clock->IMFPresentationClock_iface); } static ULONG WINAPI present_clock_rate_control_Release(IMFRateControl *iface) { struct presentation_clock *clock = impl_from_IMFRateControl(iface); return IMFPresentationClock_Release(&clock->IMFPresentationClock_iface); } static HRESULT WINAPI present_clock_rate_SetRate(IMFRateControl *iface, BOOL thin, float rate) { FIXME("%p, %d, %f.\n", iface, thin, rate); return E_NOTIMPL; } static HRESULT WINAPI present_clock_rate_GetRate(IMFRateControl *iface, BOOL *thin, float *rate) { FIXME("%p, %p, %p.\n", iface, thin, rate); return E_NOTIMPL; } static const IMFRateControlVtbl presentclockratecontrolvtbl = { present_clock_rate_control_QueryInterface, present_clock_rate_control_AddRef, present_clock_rate_control_Release, present_clock_rate_SetRate, present_clock_rate_GetRate, }; static HRESULT WINAPI present_clock_timer_QueryInterface(IMFTimer *iface, REFIID riid, void **out) { struct presentation_clock *clock = impl_from_IMFTimer(iface); return IMFPresentationClock_QueryInterface(&clock->IMFPresentationClock_iface, riid, out); } static ULONG WINAPI present_clock_timer_AddRef(IMFTimer *iface) { struct presentation_clock *clock = impl_from_IMFTimer(iface); return IMFPresentationClock_AddRef(&clock->IMFPresentationClock_iface); } static ULONG WINAPI present_clock_timer_Release(IMFTimer *iface) { struct presentation_clock *clock = impl_from_IMFTimer(iface); return IMFPresentationClock_Release(&clock->IMFPresentationClock_iface); } static HRESULT WINAPI present_clock_timer_SetTimer(IMFTimer *iface, DWORD flags, LONGLONG time, IMFAsyncCallback *callback, IUnknown *state, IUnknown **cancel_key) { FIXME("%p, %#x, %s, %p, %p, %p.\n", iface, flags, wine_dbgstr_longlong(time), callback, state, cancel_key); return E_NOTIMPL; } static HRESULT WINAPI present_clock_timer_CancelTimer(IMFTimer *iface, IUnknown *cancel_key) { FIXME("%p, %p.\n", iface, cancel_key); return E_NOTIMPL; } static const IMFTimerVtbl presentclocktimervtbl = { present_clock_timer_QueryInterface, present_clock_timer_AddRef, present_clock_timer_Release, present_clock_timer_SetTimer, present_clock_timer_CancelTimer, }; static HRESULT WINAPI present_clock_shutdown_QueryInterface(IMFShutdown *iface, REFIID riid, void **out) { struct presentation_clock *clock = impl_from_IMFShutdown(iface); return IMFPresentationClock_QueryInterface(&clock->IMFPresentationClock_iface, riid, out); } static ULONG WINAPI present_clock_shutdown_AddRef(IMFShutdown *iface) { struct presentation_clock *clock = impl_from_IMFShutdown(iface); return IMFPresentationClock_AddRef(&clock->IMFPresentationClock_iface); } static ULONG WINAPI present_clock_shutdown_Release(IMFShutdown *iface) { struct presentation_clock *clock = impl_from_IMFShutdown(iface); return IMFPresentationClock_Release(&clock->IMFPresentationClock_iface); } static HRESULT WINAPI present_clock_shutdown_Shutdown(IMFShutdown *iface) { FIXME("%p.\n", iface); return E_NOTIMPL; } static HRESULT WINAPI present_clock_shutdown_GetShutdownStatus(IMFShutdown *iface, MFSHUTDOWN_STATUS *status) { FIXME("%p, %p.\n", iface, status); return E_NOTIMPL; } static const IMFShutdownVtbl presentclockshutdownvtbl = { present_clock_shutdown_QueryInterface, present_clock_shutdown_AddRef, present_clock_shutdown_Release, present_clock_shutdown_Shutdown, present_clock_shutdown_GetShutdownStatus, }; static HRESULT WINAPI present_clock_sink_callback_QueryInterface(IMFAsyncCallback *iface, REFIID riid, void **out) { if (IsEqualIID(riid, &IID_IMFAsyncCallback) || IsEqualIID(riid, &IID_IUnknown)) { *out = iface; IMFAsyncCallback_AddRef(iface); return S_OK; } WARN("Unsupported %s.\n", wine_dbgstr_guid(riid)); *out = NULL; return E_NOINTERFACE; } static ULONG WINAPI present_clock_sink_callback_AddRef(IMFAsyncCallback *iface) { struct presentation_clock *clock = impl_from_IMFAsyncCallback(iface); return IMFPresentationClock_AddRef(&clock->IMFPresentationClock_iface); } static ULONG WINAPI present_clock_sink_callback_Release(IMFAsyncCallback *iface) { struct presentation_clock *clock = impl_from_IMFAsyncCallback(iface); return IMFPresentationClock_Release(&clock->IMFPresentationClock_iface); } static HRESULT WINAPI present_clock_sink_callback_GetParameters(IMFAsyncCallback *iface, DWORD *flags, DWORD *queue) { return E_NOTIMPL; } static HRESULT WINAPI present_clock_sink_callback_Invoke(IMFAsyncCallback *iface, IMFAsyncResult *result) { struct sink_notification *data; IUnknown *object; HRESULT hr; if (FAILED(hr = IMFAsyncResult_GetObject(result, &object))) return hr; data = impl_from_IUnknown(object); clock_call_state_change(data->system_time, data->offset, data->notification, data->sink); IUnknown_Release(object); return S_OK; } static const IMFAsyncCallbackVtbl presentclocksinkcallbackvtbl = { present_clock_sink_callback_QueryInterface, present_clock_sink_callback_AddRef, present_clock_sink_callback_Release, present_clock_sink_callback_GetParameters, present_clock_sink_callback_Invoke, }; /*********************************************************************** * MFCreatePresentationClock (mf.@) */ HRESULT WINAPI MFCreatePresentationClock(IMFPresentationClock **clock) { struct presentation_clock *object; TRACE("%p.\n", clock); object = heap_alloc_zero(sizeof(*object)); if (!object) return E_OUTOFMEMORY; object->IMFPresentationClock_iface.lpVtbl = &presentationclockvtbl; object->IMFRateControl_iface.lpVtbl = &presentclockratecontrolvtbl; object->IMFTimer_iface.lpVtbl = &presentclocktimervtbl; object->IMFShutdown_iface.lpVtbl = &presentclockshutdownvtbl; object->IMFAsyncCallback_iface.lpVtbl = &presentclocksinkcallbackvtbl; object->refcount = 1; list_init(&object->sinks); InitializeCriticalSection(&object->cs); *clock = &object->IMFPresentationClock_iface; return S_OK; }
28.381566
122
0.714949
[ "object" ]
7f8f913a935b523aa1e6670956c0e5f16245a961
16,546
h
C
Dockerized/rdpstack/cmake-3.17.2/Source/cmCTest.h
nsimbi/Proconsul
70cb520463bf9d9e36b37c57db5c7798a8604c03
[ "MIT" ]
3
2021-10-14T07:40:15.000Z
2022-02-27T09:20:33.000Z
Dockerized/rdpstack/cmake-3.17.2/Source/cmCTest.h
nsimbi/Proconsul
70cb520463bf9d9e36b37c57db5c7798a8604c03
[ "MIT" ]
null
null
null
Dockerized/rdpstack/cmake-3.17.2/Source/cmCTest.h
nsimbi/Proconsul
70cb520463bf9d9e36b37c57db5c7798a8604c03
[ "MIT" ]
2
2021-10-21T06:12:36.000Z
2022-03-07T15:52:28.000Z
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #ifndef cmCTest_h #define cmCTest_h #include "cmConfigure.h" // IWYU pragma: keep #include <chrono> #include <ctime> #include <map> #include <memory> #include <sstream> #include <string> #include <vector> #include "cmDuration.h" #include "cmProcessOutput.h" class cmCTestBuildHandler; class cmCTestBuildAndTestHandler; class cmCTestCoverageHandler; class cmCTestScriptHandler; class cmCTestTestHandler; class cmCTestUpdateHandler; class cmCTestConfigureHandler; class cmCTestMemCheckHandler; class cmCTestSubmitHandler; class cmCTestUploadHandler; class cmCTestStartCommand; class cmGeneratedFileStream; class cmMakefile; class cmXMLWriter; /** \class cmCTest * \brief Represents a ctest invocation. * * This class represents a ctest invocation. It is the top level class when * running ctest. * */ class cmCTest { public: using Encoding = cmProcessOutput::Encoding; /** Enumerate parts of the testing and submission process. */ enum Part { PartStart, PartUpdate, PartConfigure, PartBuild, PartTest, PartCoverage, PartMemCheck, PartSubmit, PartNotes, PartExtraFiles, PartUpload, PartDone, PartCount // Update names in constructor when adding a part }; /** Get a testing part id from its string name. Returns PartCount if the string does not name a valid part. */ Part GetPartFromName(const char* name); /** Process Command line arguments */ int Run(std::vector<std::string>&, std::string* output = nullptr); /** * Initialize and finalize testing */ bool InitializeFromCommand(cmCTestStartCommand* command); void Finalize(); /** * Process the dashboard client steps. * * Steps are enabled using SetTest() * * The execution of the steps (or #Part) should look like this: * * /code * ctest foo; * foo.Initialize(); * // Set some things on foo * foo.ProcessSteps(); * foo.Finalize(); * /endcode * * \sa Initialize(), Finalize(), Part, PartInfo, SetTest() */ int ProcessSteps(); /** * A utility function that returns the nightly time */ struct tm* GetNightlyTime(std::string const& str, bool tomorrowtag); /** * Is the tomorrow tag set? */ bool GetTomorrowTag() const; /** * Try to run tests of the project */ int TestDirectory(bool memcheck); /** what is the configuration type, e.g. Debug, Release etc. */ std::string const& GetConfigType(); cmDuration GetTimeOut() const; void SetTimeOut(cmDuration t); cmDuration GetGlobalTimeout() const; /** how many test to run at the same time */ int GetParallelLevel() const; void SetParallelLevel(int); unsigned long GetTestLoad() const; void SetTestLoad(unsigned long); /** * Check if CTest file exists */ bool CTestFileExists(const std::string& filename); bool AddIfExists(Part part, const char* file); /** * Set the cmake test */ bool SetTest(const char*, bool report = true); /** * Set the cmake test mode (experimental, nightly, continuous). */ void SetTestModel(int mode); int GetTestModel() const; std::string GetTestModelString(); static int GetTestModelFromString(const char* str); static std::string CleanString(const std::string& str); std::string GetCTestConfiguration(const std::string& name); void SetCTestConfiguration(const char* name, const char* value, bool suppress = false); void EmptyCTestConfiguration(); std::string GetSubmitURL(); /** * constructor and destructor */ cmCTest(); ~cmCTest(); cmCTest(const cmCTest&) = delete; cmCTest& operator=(const cmCTest&) = delete; /** Set the notes files to be created. */ void SetNotesFiles(const char* notes); void PopulateCustomVector(cmMakefile* mf, const std::string& definition, std::vector<std::string>& vec); void PopulateCustomInteger(cmMakefile* mf, const std::string& def, int& val); /** Get the current time as string */ std::string CurrentTime(); /** tar/gzip and then base 64 encode a file */ std::string Base64GzipEncodeFile(std::string const& file); /** base64 encode a file */ std::string Base64EncodeFile(std::string const& file); /** * Return the time remaining that the script is allowed to run in * seconds if the user has set the variable CTEST_TIME_LIMIT. If that has * not been set it returns a very large duration. */ cmDuration GetRemainingTimeAllowed(); static cmDuration MaxDuration(); /** * Open file in the output directory and set the stream */ bool OpenOutputFile(const std::string& path, const std::string& name, cmGeneratedFileStream& stream, bool compress = false); /** Should we only show what we would do? */ bool GetShowOnly(); bool GetOutputAsJson(); int GetOutputAsJsonVersion(); bool ShouldUseHTTP10() const; bool ShouldPrintLabels() const; bool ShouldCompressTestOutput(); bool CompressString(std::string& str); std::chrono::system_clock::time_point GetStopTime() const; void SetStopTime(std::string const& time); /** Used for parallel ctest job scheduling */ std::string GetScheduleType() const; void SetScheduleType(std::string const& type); /** The max output width */ int GetMaxTestNameWidth() const; void SetMaxTestNameWidth(int w); /** * Run a single executable command and put the stdout and stderr * in output. * * If verbose is false, no user-viewable output from the program * being run will be generated. * * If timeout is specified, the command will be terminated after * timeout expires. Timeout is specified in seconds. * * Argument retVal should be a pointer to the location where the * exit code will be stored. If the retVal is not specified and * the program exits with a code other than 0, then the this * function will return false. */ bool RunCommand(std::vector<std::string> const& args, std::string* stdOut, std::string* stdErr, int* retVal = nullptr, const char* dir = nullptr, cmDuration timeout = cmDuration::zero(), Encoding encoding = cmProcessOutput::Auto); /** * Clean/make safe for xml the given value such that it may be used as * one of the key fields by CDash when computing the buildid. */ static std::string SafeBuildIdField(const std::string& value); /** Start CTest XML output file */ void StartXML(cmXMLWriter& xml, bool append); /** End CTest XML output file */ void EndXML(cmXMLWriter& xml); /** * Run command specialized for make and configure. Returns process status * and retVal is return value or exception. */ int RunMakeCommand(const std::string& command, std::string& output, int* retVal, const char* dir, cmDuration timeout, std::ostream& ofs, Encoding encoding = cmProcessOutput::Auto); /** Return the current tag */ std::string GetCurrentTag(); /** Get the path to the build tree */ std::string GetBinaryDir(); /** * Get the short path to the file. * * This means if the file is in binary or * source directory, it will become /.../relative/path/to/file */ std::string GetShortPathToFile(const char* fname); enum { UNKNOWN = -1, EXPERIMENTAL = 0, NIGHTLY = 1, CONTINUOUS = 2, }; /** provide some more detailed info on the return code for ctest */ enum { UPDATE_ERRORS = 0x01, CONFIGURE_ERRORS = 0x02, BUILD_ERRORS = 0x04, TEST_ERRORS = 0x08, MEMORY_ERRORS = 0x10, COVERAGE_ERRORS = 0x20, SUBMIT_ERRORS = 0x40 }; /** Are we producing XML */ bool GetProduceXML(); void SetProduceXML(bool v); /** * Run command specialized for tests. Returns process status and retVal is * return value or exception. If environment is non-null, it is used to set * environment variables prior to running the test. After running the test, * environment variables are restored to their previous values. */ int RunTest(std::vector<const char*> args, std::string* output, int* retVal, std::ostream* logfile, cmDuration testTimeOut, std::vector<std::string>* environment, Encoding encoding = cmProcessOutput::Auto); /** * Get the handler object */ cmCTestBuildHandler* GetBuildHandler(); cmCTestBuildAndTestHandler* GetBuildAndTestHandler(); cmCTestCoverageHandler* GetCoverageHandler(); cmCTestScriptHandler* GetScriptHandler(); cmCTestTestHandler* GetTestHandler(); cmCTestUpdateHandler* GetUpdateHandler(); cmCTestConfigureHandler* GetConfigureHandler(); cmCTestMemCheckHandler* GetMemCheckHandler(); cmCTestSubmitHandler* GetSubmitHandler(); cmCTestUploadHandler* GetUploadHandler(); /** * Set the CTest variable from CMake variable */ bool SetCTestConfigurationFromCMakeVariable(cmMakefile* mf, const char* dconfig, const std::string& cmake_var, bool suppress = false); /** Decode a URL to the original string. */ static std::string DecodeURL(const std::string&); /** * Should ctect configuration be updated. When using new style ctest * script, this should be true. */ void SetSuppressUpdatingCTestConfiguration(bool val); /** * Add overwrite to ctest configuration. * * The format is key=value */ void AddCTestConfigurationOverwrite(const std::string& encstr); /** Create XML file that contains all the notes specified */ int GenerateNotesFile(std::vector<std::string> const& files); /** Create XML file to indicate that build is complete */ int GenerateDoneFile(); /** Submit extra files to the server */ bool SubmitExtraFiles(const char* files); bool SubmitExtraFiles(std::vector<std::string> const& files); /** Set the output log file name */ void SetOutputLogFileName(const char* name); /** Set the visual studio or Xcode config type */ void SetConfigType(const char* ct); /** Various log types */ enum { DEBUG = 0, OUTPUT, HANDLER_OUTPUT, HANDLER_PROGRESS_OUTPUT, HANDLER_TEST_PROGRESS_OUTPUT, HANDLER_VERBOSE_OUTPUT, WARNING, ERROR_MESSAGE, OTHER }; /** Add log to the output */ void Log(int logType, const char* file, int line, const char* msg, bool suppress = false); /** Color values */ enum class Color { CLEAR_COLOR = 0, RED = 31, GREEN = 32, YELLOW = 33, BLUE = 34 }; /** Get color code characters for a specific color */ std::string GetColorCode(Color color) const; /** The Build ID is assigned by CDash */ void SetBuildID(const std::string& id); std::string GetBuildID() const; /** Add file to be submitted */ void AddSubmitFile(Part part, const char* name); std::vector<std::string> const& GetSubmitFiles(Part part) const; void ClearSubmitFiles(Part part); /** * Read the custom configuration files and apply them to the current ctest */ int ReadCustomConfigurationFileTree(const char* dir, cmMakefile* mf); std::vector<std::string>& GetInitialCommandLineArguments(); /** Set the group to submit to */ void SetSpecificGroup(const char* group); const char* GetSpecificGroup(); void SetFailover(bool failover); bool GetFailover() const; bool GetTestProgressOutput() const; bool GetVerbose() const; bool GetExtraVerbose() const; /** Direct process output to given streams. */ void SetStreams(std::ostream* out, std::ostream* err); void AddSiteProperties(cmXMLWriter& xml); bool GetLabelSummary() const; bool GetSubprojectSummary() const; std::string GetCostDataFile(); bool GetOutputTestOutputOnTestFailure() const; const std::map<std::string, std::string>& GetDefinitions() const; /** Return the number of times a test should be run */ int GetRepeatCount() const; enum class Repeat { Never, UntilFail, UntilPass, AfterTimeout, }; Repeat GetRepeatMode() const; enum class NoTests { Legacy, Error, Ignore }; NoTests GetNoTestsMode() const; void GenerateSubprojectsOutput(cmXMLWriter& xml); std::vector<std::string> GetLabelsForSubprojects(); void SetRunCurrentScript(bool value); private: int GenerateNotesFile(const char* files); void BlockTestErrorDiagnostics(); /** * Initialize a dashboard run in the given build tree. The "command" * argument is non-NULL when running from a command-driven (ctest_start) * dashboard script, and NULL when running from the CTest command * line. Note that a declarative dashboard script does not actually * call this method because it sets CTEST_COMMAND to drive a build * through the ctest command line. */ int Initialize(const char* binary_dir, cmCTestStartCommand* command); /** parse the option after -D and convert it into the appropriate steps */ bool AddTestsForDashboardType(std::string& targ); /** read as "emit an error message for an unknown -D value" */ void ErrorMessageUnknownDashDValue(std::string& val); /** add a variable definition from a command line -D value */ bool AddVariableDefinition(const std::string& arg); /** parse and process most common command line arguments */ bool HandleCommandLineArguments(size_t& i, std::vector<std::string>& args, std::string& errormsg); #if !defined(_WIN32) /** returns true iff the console supports progress output */ static bool ConsoleIsNotDumb(); #endif /** returns true iff the console supports progress output */ static bool ProgressOutputSupportedByConsole(); /** returns true iff the console supports colored output */ static bool ColoredOutputSupportedByConsole(); /** handle the -S -SP and -SR arguments */ void HandleScriptArguments(size_t& i, std::vector<std::string>& args, bool& SRArgumentSpecified); /** Reread the configuration file */ bool UpdateCTestConfiguration(); /** Create note from files. */ int GenerateCTestNotesOutput(cmXMLWriter& xml, std::vector<std::string> const& files); /** Check if the argument is the one specified */ bool CheckArgument(const std::string& arg, const char* varg1, const char* varg2 = nullptr); /** Output errors from a test */ void OutputTestErrors(std::vector<char> const& process_output); /** Handle the --test-action command line argument */ bool HandleTestActionArgument(const char* ctestExec, size_t& i, const std::vector<std::string>& args); /** Handle the --test-model command line argument */ bool HandleTestModelArgument(const char* ctestExec, size_t& i, const std::vector<std::string>& args); int RunCMakeAndTest(std::string* output); int ExecuteTests(); struct Private; std::unique_ptr<Private> Impl; }; class cmCTestLogWrite { public: cmCTestLogWrite(const char* data, size_t length) : Data(data) , Length(length) { } const char* Data; size_t Length; }; inline std::ostream& operator<<(std::ostream& os, const cmCTestLogWrite& c) { if (!c.Length) { return os; } os.write(c.Data, c.Length); os.flush(); return os; } #define cmCTestLog(ctSelf, logType, msg) \ do { \ std::ostringstream cmCTestLog_msg; \ cmCTestLog_msg << msg; \ (ctSelf)->Log(cmCTest::logType, __FILE__, __LINE__, \ cmCTestLog_msg.str().c_str()); \ } while (false) #define cmCTestOptionalLog(ctSelf, logType, msg, suppress) \ do { \ std::ostringstream cmCTestLog_msg; \ cmCTestLog_msg << msg; \ (ctSelf)->Log(cmCTest::logType, __FILE__, __LINE__, \ cmCTestLog_msg.str().c_str(), suppress); \ } while (false) #endif
29.02807
79
0.657319
[ "object", "vector", "model" ]
7f940c53e54768902b9aa82d75daffce0255ac36
13,119
h
C
Userland/Libraries/LibWeb/Forward.h
TheOddGarlic/serenity
23ea5c6721e4cf71be3ffefd88cd3d9d4cc34825
[ "BSD-2-Clause" ]
1
2022-01-24T13:01:57.000Z
2022-01-24T13:01:57.000Z
Userland/Libraries/LibWeb/Forward.h
dayarthvader/serenity
82bdb8f0e1ddf04be8b621131db334fc634c8d90
[ "BSD-2-Clause" ]
null
null
null
Userland/Libraries/LibWeb/Forward.h
dayarthvader/serenity
82bdb8f0e1ddf04be8b621131db334fc634c8d90
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2020-2022, Andreas Kling <kling@serenityos.org> * Copyright (c) 2021, the SerenityOS developers. * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once namespace Web { class XMLDocumentBuilder; } namespace Web::Cookie { struct Cookie; struct ParsedCookie; enum class Source; } namespace Web::Crypto { class Crypto; class SubtleCrypto; } namespace Web::CSS { class Angle; class AnglePercentage; class AngleStyleValue; class BackgroundRepeatStyleValue; class BackgroundSizeStyleValue; class BackgroundStyleValue; class BorderRadiusStyleValue; class BorderStyleValue; class CalculatedStyleValue; class ColorStyleValue; class ContentStyleValue; class CSSImportRule; class CSSFontFaceRule; class CSSMediaRule; class CSSRule; class CSSRuleList; class CSSStyleDeclaration; class CSSStyleRule; class CSSStyleSheet; class CSSSupportsRule; class Display; class ElementInlineCSSStyleDeclaration; class FlexFlowStyleValue; class FlexStyleValue; class FontFace; class FontStyleValue; class Frequency; class FrequencyPercentage; class FrequencyStyleValue; class IdentifierStyleValue; class ImageStyleValue; class InheritStyleValue; class InitialStyleValue; class Length; class LengthPercentage; class LengthStyleValue; class ListStyleStyleValue; class MediaList; class MediaQuery; class MediaQueryList; class MediaQueryListEvent; class Number; class NumericStyleValue; class OverflowStyleValue; class Percentage; class PercentageStyleValue; class PositionStyleValue; class PropertyOwningCSSStyleDeclaration; class Resolution; class ResolutionStyleValue; class Screen; class Selector; class ShadowStyleValue; class StringStyleValue; class StyleComputer; class StyleProperties; class StyleSheet; class StyleSheetList; class StyleValue; class StyleValueList; class Supports; class TextDecorationStyleValue; class Time; class TimePercentage; class TimeStyleValue; class TransformationStyleValue; class UnicodeRange; class UnresolvedStyleValue; class UnsetStyleValue; } namespace Web::DOM { class AbstractRange; class AbortController; class AbortSignal; class Attribute; class CharacterData; class Comment; class CustomEvent; class Document; class DocumentFragment; class DocumentLoadEventDelayer; class DocumentType; class DOMEventListener; class DOMException; class DOMImplementation; class DOMTokenList; class Element; class Event; class EventHandler; class EventTarget; class HTMLCollection; class IDLEventListener; class LiveNodeList; class NamedNodeMap; class Node; class NodeFilter; class NodeIterator; class NodeList; class ParentNode; class Position; class ProcessingInstruction; class Range; class ShadowRoot; class StaticNodeList; class StaticRange; class Text; class TreeWalker; enum class QuirksMode; struct EventListenerOptions; struct AddEventListenerOptions; template<typename ValueType> class ExceptionOr; } namespace Web::Encoding { class TextEncoder; } namespace Web::Geometry { class DOMRect; class DOMRectList; class DOMRectReadOnly; } namespace Web::HTML { class BrowsingContext; class BrowsingContextContainer; class CanvasRenderingContext2D; class ClassicScript; class CloseEvent; class DOMParser; class DOMStringMap; struct Environment; struct EnvironmentSettingsObject; class ErrorEvent; struct EventHandler; class EventLoop; class HTMLAnchorElement; class HTMLAreaElement; class HTMLAudioElement; class HTMLBaseElement; class HTMLBlinkElement; class HTMLBodyElement; class HTMLBRElement; class HTMLButtonElement; class HTMLCanvasElement; class HTMLDataElement; class HTMLDataListElement; class HTMLDetailsElement; class HTMLDialogElement; class HTMLDirectoryElement; class HTMLDivElement; class HTMLDListElement; class HTMLElement; class HTMLEmbedElement; class HTMLFieldSetElement; class HTMLFontElement; class HTMLFormElement; class HTMLFrameElement; class HTMLFrameSetElement; class HTMLHeadElement; class HTMLHeadingElement; class HTMLHRElement; class HTMLHtmlElement; class HTMLIFrameElement; class HTMLImageElement; class HTMLInputElement; class HTMLLabelElement; class HTMLLegendElement; class HTMLLIElement; class HTMLLinkElement; class HTMLMapElement; class HTMLMarqueeElement; class HTMLMediaElement; class HTMLMenuElement; class HTMLMetaElement; class HTMLMeterElement; class HTMLModElement; class HTMLObjectElement; class HTMLOListElement; class HTMLOptGroupElement; class HTMLOptionElement; class HTMLOptionsCollection; class HTMLOutputElement; class HTMLParagraphElement; class HTMLParamElement; class HTMLParser; class HTMLPictureElement; class HTMLPreElement; class HTMLProgressElement; class HTMLQuoteElement; class HTMLScriptElement; class HTMLSelectElement; class HTMLSlotElement; class HTMLSourceElement; class HTMLSpanElement; class HTMLStyleElement; class HTMLTableCaptionElement; class HTMLTableCellElement; class HTMLTableColElement; class HTMLTableElement; class HTMLTableRowElement; class HTMLTableSectionElement; class HTMLTemplateElement; class HTMLTextAreaElement; class HTMLTimeElement; class HTMLTitleElement; class HTMLTrackElement; class HTMLUListElement; class HTMLUnknownElement; class HTMLVideoElement; class ImageData; class MessageChannel; class MessageEvent; class MessagePort; class PageTransitionEvent; class PromiseRejectionEvent; class WorkerDebugConsoleClient; class Storage; class SubmitEvent; class TextMetrics; class Timer; class Window; class WindowEnvironmentSettingsObject; class Worker; class WorkerEnvironmentSettingsObject; class WorkerGlobalScope; class WorkerLocation; class WorkerNavigator; } namespace Web::HighResolutionTime { class Performance; } namespace Web::IntersectionObserver { class IntersectionObserver; } namespace Web::MimeSniff { class MimeType; } namespace Web::NavigationTiming { class PerformanceTiming; } namespace Web::Painting { enum class PaintPhase; class ButtonPaintable; class CheckBoxPaintable; class LabelablePaintable; class Paintable; class PaintableBox; class PaintableWithLines; class StackingContext; class TextPaintable; struct BorderRadiusData; } namespace Web::RequestIdleCallback { class IdleDeadline; } namespace Web::ResizeObserver { class ResizeObserver; } namespace Web::SVG { class SVGAnimatedLength; class SVGCircleElement; class SVGClipPathElement; class SVGElement; class SVGEllipseElement; class SVGGeometryElement; class SVGGraphicsElement; class SVGLength; class SVGLineElement; class SVGPathElement; class SVGPolygonElement; class SVGPolylineElement; class SVGRectElement; class SVGSVGElement; } namespace Web::Selection { class Selection; } namespace Web::WebSockets { class WebSocket; } namespace Web::Layout { enum class LayoutMode; class BlockContainer; class BlockFormattingContext; class Box; class ButtonBox; class CheckBox; class FlexFormattingContext; class FormattingContext; struct FormattingState; class InitialContainingBlock; class InlineFormattingContext; class Label; class LabelableNode; class LineBox; class LineBoxFragment; class ListItemBox; class ListItemMarkerBox; class Node; class NodeWithStyle; class NodeWithStyleAndBoxModelMetrics; class RadioButton; class ReplacedBox; class TextNode; } namespace Web { class EditEventHandler; class EventHandler; class FrameLoader; class LoadRequest; class Origin; class OutOfProcessWebView; class Page; class PageClient; class PaintContext; class Resource; class ResourceLoader; } namespace Web::XHR { class ProgressEvent; class XMLHttpRequest; class XMLHttpRequestEventTarget; } namespace Web::UIEvents { class MouseEvent; class KeyboardEvent; class UIEvents; } namespace Web::URL { class URL; class URLSearchParams; class URLSearchParamsIterator; } namespace Web::Bindings { class AbstractRangeWrapper; class AbortControllerWrapper; class AbortSignalWrapper; class AttributeWrapper; struct CallbackType; class CanvasGradientWrapper; class CanvasRenderingContext2DWrapper; class CharacterDataWrapper; class CloseEventWrapper; class CommentWrapper; class CryptoWrapper; class CSSFontFaceRuleWrapper; class CSSRuleListWrapper; class CSSRuleWrapper; class CSSStyleDeclarationWrapper; class CSSStyleRuleWrapper; class CSSStyleSheetWrapper; class CustomEventWrapper; class DocumentFragmentWrapper; class DocumentTypeWrapper; class DocumentWrapper; class DOMExceptionWrapper; class DOMImplementationWrapper; class DOMParserWrapper; class DOMRectListWrapper; class DOMRectReadOnlyWrapper; class DOMRectWrapper; class DOMStringMapWrapper; class DOMTokenListWrapper; class ElementWrapper; class ErrorEventWrapper; class EventListenerWrapper; class EventTargetWrapper; class EventWrapper; class FocusEventWrapper; class HistoryWrapper; class HTMLAnchorElementWrapper; class HTMLAreaElementWrapper; class HTMLAudioElementWrapper; class HTMLBaseElementWrapper; class HTMLBodyElementWrapper; class HTMLBRElementWrapper; class HTMLButtonElementWrapper; class HTMLCanvasElementWrapper; class HTMLCollectionWrapper; class HTMLDataElementWrapper; class HTMLDataListElementWrapper; class HTMLDetailsElementWrapper; class HTMLDialogElementWrapper; class HTMLDirectoryElementWrapper; class HTMLDivElementWrapper; class HTMLDListElementWrapper; class HTMLElementWrapper; class HTMLEmbedElementWrapper; class HTMLFieldSetElementWrapper; class HTMLFontElementWrapper; class HTMLFormElementWrapper; class HTMLFrameElementWrapper; class HTMLFrameSetElementWrapper; class HTMLHeadElementWrapper; class HTMLHeadingElementWrapper; class HTMLHRElementWrapper; class HTMLHtmlElementWrapper; class HTMLIFrameElementWrapper; class HTMLImageElementWrapper; class HTMLInputElementWrapper; class HTMLLabelElementWrapper; class HTMLLegendElementWrapper; class HTMLLIElementWrapper; class HTMLLinkElementWrapper; class HTMLMapElementWrapper; class HTMLMarqueeElementWrapper; class HTMLMediaElementWrapper; class HTMLMenuElementWrapper; class HTMLMetaElementWrapper; class HTMLMeterElementWrapper; class HTMLModElementWrapper; class HTMLObjectElementWrapper; class HTMLOListElementWrapper; class HTMLOptGroupElementWrapper; class HTMLOptionElementWrapper; class HTMLOptionsCollectionWrapper; class HTMLOutputElementWrapper; class HTMLParagraphElementWrapper; class HTMLParamElementWrapper; class HTMLPictureElementWrapper; class HTMLPreElementWrapper; class HTMLProgressElementWrapper; class HTMLQuoteElementWrapper; class HTMLScriptElementWrapper; class HTMLSelectElementWrapper; class HTMLSlotElementWrapper; class HTMLSourceElementWrapper; class HTMLSpanElementWrapper; class HTMLStyleElementWrapper; class HTMLTableCaptionElementWrapper; class HTMLTableCellElementWrapper; class HTMLTableColElementWrapper; class HTMLTableElementWrapper; class HTMLTableRowElementWrapper; class HTMLTableSectionElementWrapper; class HTMLTemplateElementWrapper; class HTMLTextAreaElementWrapper; class HTMLTimeElementWrapper; class HTMLTitleElementWrapper; class HTMLTrackElementWrapper; class HTMLUListElementWrapper; class HTMLUnknownElementWrapper; class HTMLVideoElementWrapper; class IdleDeadlineWrapper; class ImageDataWrapper; class IntersectionObserverWrapper; class KeyboardEventWrapper; class LocationObject; class MediaQueryListEventWrapper; class MediaQueryListWrapper; class MessageChannelWrapper; class MessageEventWrapper; class MessagePortWrapper; class MouseEventWrapper; class NamedNodeMapWrapper; class NodeFilterWrapper; class NodeIteratorWrapper; class NodeListWrapper; class NodeWrapper; class OptionConstructor; class PageTransitionEventWrapper; class PerformanceTimingWrapper; class PerformanceWrapper; class ProcessingInstructionWrapper; class ProgressEventWrapper; class PromiseRejectionEventWrapper; class RangeConstructor; class RangePrototype; class RangeWrapper; class ResizeObserverWrapper; class ScreenWrapper; class SelectionWrapper; class StaticRangeWrapper; class StorageWrapper; class StyleSheetListWrapper; class StyleSheetWrapper; class SubmitEventWrapper; class SubtleCryptoWrapper; class SVGAnimatedLengthWrapper; class SVGCircleElementWrapper; class SVGClipPathElementWrapper; class SVGElementWrapper; class SVGEllipseElementWrapper; class SVGGeometryElementWrapper; class SVGGraphicsElementWrapper; class SVGLengthWrapper; class SVGLineElementWrapper; class SVGPathElementWrapper; class SVGPolygonElementWrapper; class SVGPolylineElementWrapper; class SVGRectElementWrapper; class SVGSVGElementWrapper; class SVGTextContentElementWrapper; class TextDecoderWrapper; class TextEncoderWrapper; class TextMetricsWrapper; class TextWrapper; class TreeWalkerWrapper; class UIEventWrapper; class URLConstructor; class URLPrototype; class URLSearchParamsConstructor; class URLSearchParamsIteratorPrototype; class URLSearchParamsIteratorWrapper; class URLSearchParamsPrototype; class URLSearchParamsWrapper; class URLWrapper; class WebSocketWrapper; class WindowObject; class WindowProxy; class WorkerWrapper; class WorkerGlobalScopeWrapper; class WorkerLocationWrapper; class WorkerNavigatorWrapper; class Wrappable; class Wrapper; class XMLHttpRequestConstructor; class XMLHttpRequestEventTargetWrapper; class XMLHttpRequestPrototype; class XMLHttpRequestWrapper; enum class CanPlayTypeResult; enum class DOMParserSupportedType; enum class ResizeObserverBoxOptions; enum class XMLHttpRequestResponseType; }
22.975482
64
0.867139
[ "geometry" ]
7f96815c083684e4543342f0eb166b15aba9dd6e
2,408
h
C
core/src/field_variable/field_variable.h
maierbn/opendihu
577650e2f6b36a7306766b0f4176f8124458cbf0
[ "MIT" ]
17
2018-11-25T19:29:34.000Z
2021-09-20T04:46:22.000Z
core/src/field_variable/field_variable.h
maierbn/opendihu
577650e2f6b36a7306766b0f4176f8124458cbf0
[ "MIT" ]
1
2020-11-12T15:15:58.000Z
2020-12-29T15:29:24.000Z
core/src/field_variable/field_variable.h
maierbn/opendihu
577650e2f6b36a7306766b0f4176f8124458cbf0
[ "MIT" ]
4
2018-10-17T12:18:10.000Z
2021-05-28T13:24:20.000Z
#pragma once #include "field_variable/09_field_variable_composite.h" namespace FieldVariable { /** General field variable, this is a vector with as many entries as there are unknowns in the function space. * It uses a PartitionedPetscVec at data container which is a wrapper for Petsc Vec. */ template<typename FunctionSpaceType,int nComponents> class FieldVariable : public FieldVariableComposite<FunctionSpaceType,nComponents> { public: //! inherited constructor using FieldVariableComposite<FunctionSpaceType,nComponents>::FieldVariableComposite; typedef FunctionSpaceType FunctionSpace; //! this has to be called before the vector is manipulated (i.e. VecSetValues or vecZeroEntries is called), to ensure that the current state of the vector is fetched from the global vector void startGhostManipulation(); //! zero all values in the local ghost buffer. Needed if between startGhostManipulation() and finishGhostManipulation() only some ghost will be reassigned. To prevent that the "old" ghost values that were present in the local ghost values buffer get again added to the real values which actually did not change. void zeroGhostBuffer(); //! this has to be called after the vector is manipulated (i.e. VecSetValues or vecZeroEntries is called), to ensure that operations on different partitions are merged by Petsc //! It sums up the values in the ghost buffer and the actual nodal value. void finishGhostManipulation(); //! set the internal representation to be global, i.e. using the global vectors, if it was local, ghost buffer entries are discarded (use finishGhostManipulation to consider ghost dofs) void setRepresentationGlobal(); //! set the internal representation to be local, i.e. using the local vectors, ghost buffer is not filled (use startGhostManipulation to consider ghost dofs) void setRepresentationLocal(); //! set the internal representation to be contiguous, i.e. using the contiguous vectors void setRepresentationContiguous(); //! check if the field variable contains Nan or Inf values bool containsNanOrInf(); }; // output operator template<typename FunctionSpaceType,int nComponents> std::ostream &operator<<(std::ostream &stream, const FieldVariable<FunctionSpaceType,nComponents> &rhs) { #ifndef NDEBUG rhs.output(stream); #endif return stream; } } // namespace #include "field_variable/field_variable.tpp"
42.245614
313
0.784468
[ "vector" ]
7f975a2c8990fcff4491b4171cae626490d45807
118,935
c
C
linux/drivers/net/fddi/defxx.c
bradchesney79/illacceptanything
4594ae4634fdb5e39263a6423dc255ed46c25208
[ "MIT" ]
16
2021-04-20T04:25:45.000Z
2022-02-07T15:58:16.000Z
linux/drivers/net/fddi/defxx.c
bradchesney79/illacceptanything
4594ae4634fdb5e39263a6423dc255ed46c25208
[ "MIT" ]
null
null
null
linux/drivers/net/fddi/defxx.c
bradchesney79/illacceptanything
4594ae4634fdb5e39263a6423dc255ed46c25208
[ "MIT" ]
2
2021-08-02T21:41:09.000Z
2021-09-29T13:33:24.000Z
/* * File Name: * defxx.c * * Copyright Information: * Copyright Digital Equipment Corporation 1996. * * This software may be used and distributed according to the terms of * the GNU General Public License, incorporated herein by reference. * * Abstract: * A Linux device driver supporting the Digital Equipment Corporation * FDDI TURBOchannel, EISA and PCI controller families. Supported * adapters include: * * DEC FDDIcontroller/TURBOchannel (DEFTA) * DEC FDDIcontroller/EISA (DEFEA) * DEC FDDIcontroller/PCI (DEFPA) * * The original author: * LVS Lawrence V. Stefani <lstefani@yahoo.com> * * Maintainers: * macro Maciej W. Rozycki <macro@linux-mips.org> * * Credits: * I'd like to thank Patricia Cross for helping me get started with * Linux, David Davies for a lot of help upgrading and configuring * my development system and for answering many OS and driver * development questions, and Alan Cox for recommendations and * integration help on getting FDDI support into Linux. LVS * * Driver Architecture: * The driver architecture is largely based on previous driver work * for other operating systems. The upper edge interface and * functions were largely taken from existing Linux device drivers * such as David Davies' DE4X5.C driver and Donald Becker's TULIP.C * driver. * * Adapter Probe - * The driver scans for supported EISA adapters by reading the * SLOT ID register for each EISA slot and making a match * against the expected value. * * Bus-Specific Initialization - * This driver currently supports both EISA and PCI controller * families. While the custom DMA chip and FDDI logic is similar * or identical, the bus logic is very different. After * initialization, the only bus-specific differences is in how the * driver enables and disables interrupts. Other than that, the * run-time critical code behaves the same on both families. * It's important to note that both adapter families are configured * to I/O map, rather than memory map, the adapter registers. * * Driver Open/Close - * In the driver open routine, the driver ISR (interrupt service * routine) is registered and the adapter is brought to an * operational state. In the driver close routine, the opposite * occurs; the driver ISR is deregistered and the adapter is * brought to a safe, but closed state. Users may use consecutive * commands to bring the adapter up and down as in the following * example: * ifconfig fddi0 up * ifconfig fddi0 down * ifconfig fddi0 up * * Driver Shutdown - * Apparently, there is no shutdown or halt routine support under * Linux. This routine would be called during "reboot" or * "shutdown" to allow the driver to place the adapter in a safe * state before a warm reboot occurs. To be really safe, the user * should close the adapter before shutdown (eg. ifconfig fddi0 down) * to ensure that the adapter DMA engine is taken off-line. However, * the current driver code anticipates this problem and always issues * a soft reset of the adapter at the beginning of driver initialization. * A future driver enhancement in this area may occur in 2.1.X where * Alan indicated that a shutdown handler may be implemented. * * Interrupt Service Routine - * The driver supports shared interrupts, so the ISR is registered for * each board with the appropriate flag and the pointer to that board's * device structure. This provides the context during interrupt * processing to support shared interrupts and multiple boards. * * Interrupt enabling/disabling can occur at many levels. At the host * end, you can disable system interrupts, or disable interrupts at the * PIC (on Intel systems). Across the bus, both EISA and PCI adapters * have a bus-logic chip interrupt enable/disable as well as a DMA * controller interrupt enable/disable. * * The driver currently enables and disables adapter interrupts at the * bus-logic chip and assumes that Linux will take care of clearing or * acknowledging any host-based interrupt chips. * * Control Functions - * Control functions are those used to support functions such as adding * or deleting multicast addresses, enabling or disabling packet * reception filters, or other custom/proprietary commands. Presently, * the driver supports the "get statistics", "set multicast list", and * "set mac address" functions defined by Linux. A list of possible * enhancements include: * * - Custom ioctl interface for executing port interface commands * - Custom ioctl interface for adding unicast addresses to * adapter CAM (to support bridge functions). * - Custom ioctl interface for supporting firmware upgrades. * * Hardware (port interface) Support Routines - * The driver function names that start with "dfx_hw_" represent * low-level port interface routines that are called frequently. They * include issuing a DMA or port control command to the adapter, * resetting the adapter, or reading the adapter state. Since the * driver initialization and run-time code must make calls into the * port interface, these routines were written to be as generic and * usable as possible. * * Receive Path - * The adapter DMA engine supports a 256 entry receive descriptor block * of which up to 255 entries can be used at any given time. The * architecture is a standard producer, consumer, completion model in * which the driver "produces" receive buffers to the adapter, the * adapter "consumes" the receive buffers by DMAing incoming packet data, * and the driver "completes" the receive buffers by servicing the * incoming packet, then "produces" a new buffer and starts the cycle * again. Receive buffers can be fragmented in up to 16 fragments * (descriptor entries). For simplicity, this driver posts * single-fragment receive buffers of 4608 bytes, then allocates a * sk_buff, copies the data, then reposts the buffer. To reduce CPU * utilization, a better approach would be to pass up the receive * buffer (no extra copy) then allocate and post a replacement buffer. * This is a performance enhancement that should be looked into at * some point. * * Transmit Path - * Like the receive path, the adapter DMA engine supports a 256 entry * transmit descriptor block of which up to 255 entries can be used at * any given time. Transmit buffers can be fragmented in up to 255 * fragments (descriptor entries). This driver always posts one * fragment per transmit packet request. * * The fragment contains the entire packet from FC to end of data. * Before posting the buffer to the adapter, the driver sets a three-byte * packet request header (PRH) which is required by the Motorola MAC chip * used on the adapters. The PRH tells the MAC the type of token to * receive/send, whether or not to generate and append the CRC, whether * synchronous or asynchronous framing is used, etc. Since the PRH * definition is not necessarily consistent across all FDDI chipsets, * the driver, rather than the common FDDI packet handler routines, * sets these bytes. * * To reduce the amount of descriptor fetches needed per transmit request, * the driver takes advantage of the fact that there are at least three * bytes available before the skb->data field on the outgoing transmit * request. This is guaranteed by having fddi_setup() in net_init.c set * dev->hard_header_len to 24 bytes. 21 bytes accounts for the largest * header in an 802.2 SNAP frame. The other 3 bytes are the extra "pad" * bytes which we'll use to store the PRH. * * There's a subtle advantage to adding these pad bytes to the * hard_header_len, it ensures that the data portion of the packet for * an 802.2 SNAP frame is longword aligned. Other FDDI driver * implementations may not need the extra padding and can start copying * or DMAing directly from the FC byte which starts at skb->data. Should * another driver implementation need ADDITIONAL padding, the net_init.c * module should be updated and dev->hard_header_len should be increased. * NOTE: To maintain the alignment on the data portion of the packet, * dev->hard_header_len should always be evenly divisible by 4 and at * least 24 bytes in size. * * Modification History: * Date Name Description * 16-Aug-96 LVS Created. * 20-Aug-96 LVS Updated dfx_probe so that version information * string is only displayed if 1 or more cards are * found. Changed dfx_rcv_queue_process to copy * 3 NULL bytes before FC to ensure that data is * longword aligned in receive buffer. * 09-Sep-96 LVS Updated dfx_ctl_set_multicast_list to enable * LLC group promiscuous mode if multicast list * is too large. LLC individual/group promiscuous * mode is now disabled if IFF_PROMISC flag not set. * dfx_xmt_queue_pkt no longer checks for NULL skb * on Alan Cox recommendation. Added node address * override support. * 12-Sep-96 LVS Reset current address to factory address during * device open. Updated transmit path to post a * single fragment which includes PRH->end of data. * Mar 2000 AC Did various cleanups for 2.3.x * Jun 2000 jgarzik PCI and resource alloc cleanups * Jul 2000 tjeerd Much cleanup and some bug fixes * Sep 2000 tjeerd Fix leak on unload, cosmetic code cleanup * Feb 2001 Skb allocation fixes * Feb 2001 davej PCI enable cleanups. * 04 Aug 2003 macro Converted to the DMA API. * 14 Aug 2004 macro Fix device names reported. * 14 Jun 2005 macro Use irqreturn_t. * 23 Oct 2006 macro Big-endian host support. * 14 Dec 2006 macro TURBOchannel support. * 01 Jul 2014 macro Fixes for DMA on 64-bit hosts. */ /* Include files */ #include <linux/bitops.h> #include <linux/compiler.h> #include <linux/delay.h> #include <linux/dma-mapping.h> #include <linux/eisa.h> #include <linux/errno.h> #include <linux/fddidevice.h> #include <linux/interrupt.h> #include <linux/ioport.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/netdevice.h> #include <linux/pci.h> #include <linux/skbuff.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/tc.h> #include <asm/byteorder.h> #include <asm/io.h> #include "defxx.h" /* Version information string should be updated prior to each new release! */ #define DRV_NAME "defxx" #define DRV_VERSION "v1.11" #define DRV_RELDATE "2014/07/01" static char version[] = DRV_NAME ": " DRV_VERSION " " DRV_RELDATE " Lawrence V. Stefani and others\n"; #define DYNAMIC_BUFFERS 1 #define SKBUFF_RX_COPYBREAK 200 /* * NEW_SKB_SIZE = PI_RCV_DATA_K_SIZE_MAX+128 to allow 128 byte * alignment for compatibility with old EISA boards. */ #define NEW_SKB_SIZE (PI_RCV_DATA_K_SIZE_MAX+128) #ifdef CONFIG_EISA #define DFX_BUS_EISA(dev) (dev->bus == &eisa_bus_type) #else #define DFX_BUS_EISA(dev) 0 #endif #ifdef CONFIG_TC #define DFX_BUS_TC(dev) (dev->bus == &tc_bus_type) #else #define DFX_BUS_TC(dev) 0 #endif #ifdef CONFIG_DEFXX_MMIO #define DFX_MMIO 1 #else #define DFX_MMIO 0 #endif /* Define module-wide (static) routines */ static void dfx_bus_init(struct net_device *dev); static void dfx_bus_uninit(struct net_device *dev); static void dfx_bus_config_check(DFX_board_t *bp); static int dfx_driver_init(struct net_device *dev, const char *print_name, resource_size_t bar_start); static int dfx_adap_init(DFX_board_t *bp, int get_buffers); static int dfx_open(struct net_device *dev); static int dfx_close(struct net_device *dev); static void dfx_int_pr_halt_id(DFX_board_t *bp); static void dfx_int_type_0_process(DFX_board_t *bp); static void dfx_int_common(struct net_device *dev); static irqreturn_t dfx_interrupt(int irq, void *dev_id); static struct net_device_stats *dfx_ctl_get_stats(struct net_device *dev); static void dfx_ctl_set_multicast_list(struct net_device *dev); static int dfx_ctl_set_mac_address(struct net_device *dev, void *addr); static int dfx_ctl_update_cam(DFX_board_t *bp); static int dfx_ctl_update_filters(DFX_board_t *bp); static int dfx_hw_dma_cmd_req(DFX_board_t *bp); static int dfx_hw_port_ctrl_req(DFX_board_t *bp, PI_UINT32 command, PI_UINT32 data_a, PI_UINT32 data_b, PI_UINT32 *host_data); static void dfx_hw_adap_reset(DFX_board_t *bp, PI_UINT32 type); static int dfx_hw_adap_state_rd(DFX_board_t *bp); static int dfx_hw_dma_uninit(DFX_board_t *bp, PI_UINT32 type); static int dfx_rcv_init(DFX_board_t *bp, int get_buffers); static void dfx_rcv_queue_process(DFX_board_t *bp); #ifdef DYNAMIC_BUFFERS static void dfx_rcv_flush(DFX_board_t *bp); #else static inline void dfx_rcv_flush(DFX_board_t *bp) {} #endif static netdev_tx_t dfx_xmt_queue_pkt(struct sk_buff *skb, struct net_device *dev); static int dfx_xmt_done(DFX_board_t *bp); static void dfx_xmt_flush(DFX_board_t *bp); /* Define module-wide (static) variables */ static struct pci_driver dfx_pci_driver; static struct eisa_driver dfx_eisa_driver; static struct tc_driver dfx_tc_driver; /* * ======================= * = dfx_port_write_long = * = dfx_port_read_long = * ======================= * * Overview: * Routines for reading and writing values from/to adapter * * Returns: * None * * Arguments: * bp - pointer to board information * offset - register offset from base I/O address * data - for dfx_port_write_long, this is a value to write; * for dfx_port_read_long, this is a pointer to store * the read value * * Functional Description: * These routines perform the correct operation to read or write * the adapter register. * * EISA port block base addresses are based on the slot number in which the * controller is installed. For example, if the EISA controller is installed * in slot 4, the port block base address is 0x4000. If the controller is * installed in slot 2, the port block base address is 0x2000, and so on. * This port block can be used to access PDQ, ESIC, and DEFEA on-board * registers using the register offsets defined in DEFXX.H. * * PCI port block base addresses are assigned by the PCI BIOS or system * firmware. There is one 128 byte port block which can be accessed. It * allows for I/O mapping of both PDQ and PFI registers using the register * offsets defined in DEFXX.H. * * Return Codes: * None * * Assumptions: * bp->base is a valid base I/O address for this adapter. * offset is a valid register offset for this adapter. * * Side Effects: * Rather than produce macros for these functions, these routines * are defined using "inline" to ensure that the compiler will * generate inline code and not waste a procedure call and return. * This provides all the benefits of macros, but with the * advantage of strict data type checking. */ static inline void dfx_writel(DFX_board_t *bp, int offset, u32 data) { writel(data, bp->base.mem + offset); mb(); } static inline void dfx_outl(DFX_board_t *bp, int offset, u32 data) { outl(data, bp->base.port + offset); } static void dfx_port_write_long(DFX_board_t *bp, int offset, u32 data) { struct device __maybe_unused *bdev = bp->bus_dev; int dfx_bus_tc = DFX_BUS_TC(bdev); int dfx_use_mmio = DFX_MMIO || dfx_bus_tc; if (dfx_use_mmio) dfx_writel(bp, offset, data); else dfx_outl(bp, offset, data); } static inline void dfx_readl(DFX_board_t *bp, int offset, u32 *data) { mb(); *data = readl(bp->base.mem + offset); } static inline void dfx_inl(DFX_board_t *bp, int offset, u32 *data) { *data = inl(bp->base.port + offset); } static void dfx_port_read_long(DFX_board_t *bp, int offset, u32 *data) { struct device __maybe_unused *bdev = bp->bus_dev; int dfx_bus_tc = DFX_BUS_TC(bdev); int dfx_use_mmio = DFX_MMIO || dfx_bus_tc; if (dfx_use_mmio) dfx_readl(bp, offset, data); else dfx_inl(bp, offset, data); } /* * ================ * = dfx_get_bars = * ================ * * Overview: * Retrieves the address ranges used to access control and status * registers. * * Returns: * None * * Arguments: * bdev - pointer to device information * bar_start - pointer to store the start addresses * bar_len - pointer to store the lengths of the areas * * Assumptions: * I am sure there are some. * * Side Effects: * None */ static void dfx_get_bars(struct device *bdev, resource_size_t *bar_start, resource_size_t *bar_len) { int dfx_bus_pci = dev_is_pci(bdev); int dfx_bus_eisa = DFX_BUS_EISA(bdev); int dfx_bus_tc = DFX_BUS_TC(bdev); int dfx_use_mmio = DFX_MMIO || dfx_bus_tc; if (dfx_bus_pci) { int num = dfx_use_mmio ? 0 : 1; bar_start[0] = pci_resource_start(to_pci_dev(bdev), num); bar_len[0] = pci_resource_len(to_pci_dev(bdev), num); bar_start[2] = bar_start[1] = 0; bar_len[2] = bar_len[1] = 0; } if (dfx_bus_eisa) { unsigned long base_addr = to_eisa_device(bdev)->base_addr; resource_size_t bar_lo; resource_size_t bar_hi; if (dfx_use_mmio) { bar_lo = inb(base_addr + PI_ESIC_K_MEM_ADD_LO_CMP_2); bar_lo <<= 8; bar_lo |= inb(base_addr + PI_ESIC_K_MEM_ADD_LO_CMP_1); bar_lo <<= 8; bar_lo |= inb(base_addr + PI_ESIC_K_MEM_ADD_LO_CMP_0); bar_lo <<= 8; bar_start[0] = bar_lo; bar_hi = inb(base_addr + PI_ESIC_K_MEM_ADD_HI_CMP_2); bar_hi <<= 8; bar_hi |= inb(base_addr + PI_ESIC_K_MEM_ADD_HI_CMP_1); bar_hi <<= 8; bar_hi |= inb(base_addr + PI_ESIC_K_MEM_ADD_HI_CMP_0); bar_hi <<= 8; bar_len[0] = ((bar_hi - bar_lo) | PI_MEM_ADD_MASK_M) + 1; } else { bar_start[0] = base_addr; bar_len[0] = PI_ESIC_K_CSR_IO_LEN; } bar_start[1] = base_addr + PI_DEFEA_K_BURST_HOLDOFF; bar_len[1] = PI_ESIC_K_BURST_HOLDOFF_LEN; bar_start[2] = base_addr + PI_ESIC_K_ESIC_CSR; bar_len[2] = PI_ESIC_K_ESIC_CSR_LEN; } if (dfx_bus_tc) { bar_start[0] = to_tc_dev(bdev)->resource.start + PI_TC_K_CSR_OFFSET; bar_len[0] = PI_TC_K_CSR_LEN; bar_start[2] = bar_start[1] = 0; bar_len[2] = bar_len[1] = 0; } } static const struct net_device_ops dfx_netdev_ops = { .ndo_open = dfx_open, .ndo_stop = dfx_close, .ndo_start_xmit = dfx_xmt_queue_pkt, .ndo_get_stats = dfx_ctl_get_stats, .ndo_set_rx_mode = dfx_ctl_set_multicast_list, .ndo_set_mac_address = dfx_ctl_set_mac_address, }; /* * ================ * = dfx_register = * ================ * * Overview: * Initializes a supported FDDI controller * * Returns: * Condition code * * Arguments: * bdev - pointer to device information * * Functional Description: * * Return Codes: * 0 - This device (fddi0, fddi1, etc) configured successfully * -EBUSY - Failed to get resources, or dfx_driver_init failed. * * Assumptions: * It compiles so it should work :-( (PCI cards do :-) * * Side Effects: * Device structures for FDDI adapters (fddi0, fddi1, etc) are * initialized and the board resources are read and stored in * the device structure. */ static int dfx_register(struct device *bdev) { static int version_disp; int dfx_bus_pci = dev_is_pci(bdev); int dfx_bus_eisa = DFX_BUS_EISA(bdev); int dfx_bus_tc = DFX_BUS_TC(bdev); int dfx_use_mmio = DFX_MMIO || dfx_bus_tc; const char *print_name = dev_name(bdev); struct net_device *dev; DFX_board_t *bp; /* board pointer */ resource_size_t bar_start[3]; /* pointers to ports */ resource_size_t bar_len[3]; /* resource length */ int alloc_size; /* total buffer size used */ struct resource *region; int err = 0; if (!version_disp) { /* display version info if adapter is found */ version_disp = 1; /* set display flag to TRUE so that */ printk(version); /* we only display this string ONCE */ } dev = alloc_fddidev(sizeof(*bp)); if (!dev) { printk(KERN_ERR "%s: Unable to allocate fddidev, aborting\n", print_name); return -ENOMEM; } /* Enable PCI device. */ if (dfx_bus_pci) { err = pci_enable_device(to_pci_dev(bdev)); if (err) { pr_err("%s: Cannot enable PCI device, aborting\n", print_name); goto err_out; } } SET_NETDEV_DEV(dev, bdev); bp = netdev_priv(dev); bp->bus_dev = bdev; dev_set_drvdata(bdev, dev); dfx_get_bars(bdev, bar_start, bar_len); if (dfx_bus_eisa && dfx_use_mmio && bar_start[0] == 0) { pr_err("%s: Cannot use MMIO, no address set, aborting\n", print_name); pr_err("%s: Run ECU and set adapter's MMIO location\n", print_name); pr_err("%s: Or recompile driver with \"CONFIG_DEFXX_MMIO=n\"" "\n", print_name); err = -ENXIO; goto err_out; } if (dfx_use_mmio) region = request_mem_region(bar_start[0], bar_len[0], print_name); else region = request_region(bar_start[0], bar_len[0], print_name); if (!region) { pr_err("%s: Cannot reserve %s resource 0x%lx @ 0x%lx, " "aborting\n", dfx_use_mmio ? "MMIO" : "I/O", print_name, (long)bar_len[0], (long)bar_start[0]); err = -EBUSY; goto err_out_disable; } if (bar_start[1] != 0) { region = request_region(bar_start[1], bar_len[1], print_name); if (!region) { pr_err("%s: Cannot reserve I/O resource " "0x%lx @ 0x%lx, aborting\n", print_name, (long)bar_len[1], (long)bar_start[1]); err = -EBUSY; goto err_out_csr_region; } } if (bar_start[2] != 0) { region = request_region(bar_start[2], bar_len[2], print_name); if (!region) { pr_err("%s: Cannot reserve I/O resource " "0x%lx @ 0x%lx, aborting\n", print_name, (long)bar_len[2], (long)bar_start[2]); err = -EBUSY; goto err_out_bh_region; } } /* Set up I/O base address. */ if (dfx_use_mmio) { bp->base.mem = ioremap_nocache(bar_start[0], bar_len[0]); if (!bp->base.mem) { printk(KERN_ERR "%s: Cannot map MMIO\n", print_name); err = -ENOMEM; goto err_out_esic_region; } } else { bp->base.port = bar_start[0]; dev->base_addr = bar_start[0]; } /* Initialize new device structure */ dev->netdev_ops = &dfx_netdev_ops; if (dfx_bus_pci) pci_set_master(to_pci_dev(bdev)); if (dfx_driver_init(dev, print_name, bar_start[0]) != DFX_K_SUCCESS) { err = -ENODEV; goto err_out_unmap; } err = register_netdev(dev); if (err) goto err_out_kfree; printk("%s: registered as %s\n", print_name, dev->name); return 0; err_out_kfree: alloc_size = sizeof(PI_DESCR_BLOCK) + PI_CMD_REQ_K_SIZE_MAX + PI_CMD_RSP_K_SIZE_MAX + #ifndef DYNAMIC_BUFFERS (bp->rcv_bufs_to_post * PI_RCV_DATA_K_SIZE_MAX) + #endif sizeof(PI_CONSUMER_BLOCK) + (PI_ALIGN_K_DESC_BLK - 1); if (bp->kmalloced) dma_free_coherent(bdev, alloc_size, bp->kmalloced, bp->kmalloced_dma); err_out_unmap: if (dfx_use_mmio) iounmap(bp->base.mem); err_out_esic_region: if (bar_start[2] != 0) release_region(bar_start[2], bar_len[2]); err_out_bh_region: if (bar_start[1] != 0) release_region(bar_start[1], bar_len[1]); err_out_csr_region: if (dfx_use_mmio) release_mem_region(bar_start[0], bar_len[0]); else release_region(bar_start[0], bar_len[0]); err_out_disable: if (dfx_bus_pci) pci_disable_device(to_pci_dev(bdev)); err_out: free_netdev(dev); return err; } /* * ================ * = dfx_bus_init = * ================ * * Overview: * Initializes the bus-specific controller logic. * * Returns: * None * * Arguments: * dev - pointer to device information * * Functional Description: * Determine and save adapter IRQ in device table, * then perform bus-specific logic initialization. * * Return Codes: * None * * Assumptions: * bp->base has already been set with the proper * base I/O address for this device. * * Side Effects: * Interrupts are enabled at the adapter bus-specific logic. * Note: Interrupts at the DMA engine (PDQ chip) are not * enabled yet. */ static void dfx_bus_init(struct net_device *dev) { DFX_board_t *bp = netdev_priv(dev); struct device *bdev = bp->bus_dev; int dfx_bus_pci = dev_is_pci(bdev); int dfx_bus_eisa = DFX_BUS_EISA(bdev); int dfx_bus_tc = DFX_BUS_TC(bdev); int dfx_use_mmio = DFX_MMIO || dfx_bus_tc; u8 val; DBG_printk("In dfx_bus_init...\n"); /* Initialize a pointer back to the net_device struct */ bp->dev = dev; /* Initialize adapter based on bus type */ if (dfx_bus_tc) dev->irq = to_tc_dev(bdev)->interrupt; if (dfx_bus_eisa) { unsigned long base_addr = to_eisa_device(bdev)->base_addr; /* Disable the board before fiddling with the decoders. */ outb(0, base_addr + PI_ESIC_K_SLOT_CNTRL); /* Get the interrupt level from the ESIC chip. */ val = inb(base_addr + PI_ESIC_K_IO_CONFIG_STAT_0); val &= PI_CONFIG_STAT_0_M_IRQ; val >>= PI_CONFIG_STAT_0_V_IRQ; switch (val) { case PI_CONFIG_STAT_0_IRQ_K_9: dev->irq = 9; break; case PI_CONFIG_STAT_0_IRQ_K_10: dev->irq = 10; break; case PI_CONFIG_STAT_0_IRQ_K_11: dev->irq = 11; break; case PI_CONFIG_STAT_0_IRQ_K_15: dev->irq = 15; break; } /* * Enable memory decoding (MEMCS1) and/or port decoding * (IOCS1/IOCS0) as appropriate in Function Control * Register. MEMCS1 or IOCS0 is used for PDQ registers, * taking 16 32-bit words, while IOCS1 is used for the * Burst Holdoff register, taking a single 32-bit word * only. We use the slot-specific I/O range as per the * ESIC spec, that is set bits 15:12 in the mask registers * to mask them out. */ /* Set the decode range of the board. */ val = 0; outb(val, base_addr + PI_ESIC_K_IO_ADD_CMP_0_1); val = PI_DEFEA_K_CSR_IO; outb(val, base_addr + PI_ESIC_K_IO_ADD_CMP_0_0); val = PI_IO_CMP_M_SLOT; outb(val, base_addr + PI_ESIC_K_IO_ADD_MASK_0_1); val = (PI_ESIC_K_CSR_IO_LEN - 1) & ~3; outb(val, base_addr + PI_ESIC_K_IO_ADD_MASK_0_0); val = 0; outb(val, base_addr + PI_ESIC_K_IO_ADD_CMP_1_1); val = PI_DEFEA_K_BURST_HOLDOFF; outb(val, base_addr + PI_ESIC_K_IO_ADD_CMP_1_0); val = PI_IO_CMP_M_SLOT; outb(val, base_addr + PI_ESIC_K_IO_ADD_MASK_1_1); val = (PI_ESIC_K_BURST_HOLDOFF_LEN - 1) & ~3; outb(val, base_addr + PI_ESIC_K_IO_ADD_MASK_1_0); /* Enable the decoders. */ val = PI_FUNCTION_CNTRL_M_IOCS1; if (dfx_use_mmio) val |= PI_FUNCTION_CNTRL_M_MEMCS1; else val |= PI_FUNCTION_CNTRL_M_IOCS0; outb(val, base_addr + PI_ESIC_K_FUNCTION_CNTRL); /* * Enable access to the rest of the module * (including PDQ and packet memory). */ val = PI_SLOT_CNTRL_M_ENB; outb(val, base_addr + PI_ESIC_K_SLOT_CNTRL); /* * Map PDQ registers into memory or port space. This is * done with a bit in the Burst Holdoff register. */ val = inb(base_addr + PI_DEFEA_K_BURST_HOLDOFF); if (dfx_use_mmio) val |= PI_BURST_HOLDOFF_M_MEM_MAP; else val &= ~PI_BURST_HOLDOFF_M_MEM_MAP; outb(val, base_addr + PI_DEFEA_K_BURST_HOLDOFF); /* Enable interrupts at EISA bus interface chip (ESIC) */ val = inb(base_addr + PI_ESIC_K_IO_CONFIG_STAT_0); val |= PI_CONFIG_STAT_0_M_INT_ENB; outb(val, base_addr + PI_ESIC_K_IO_CONFIG_STAT_0); } if (dfx_bus_pci) { struct pci_dev *pdev = to_pci_dev(bdev); /* Get the interrupt level from the PCI Configuration Table */ dev->irq = pdev->irq; /* Check Latency Timer and set if less than minimal */ pci_read_config_byte(pdev, PCI_LATENCY_TIMER, &val); if (val < PFI_K_LAT_TIMER_MIN) { val = PFI_K_LAT_TIMER_DEF; pci_write_config_byte(pdev, PCI_LATENCY_TIMER, val); } /* Enable interrupts at PCI bus interface chip (PFI) */ val = PFI_MODE_M_PDQ_INT_ENB | PFI_MODE_M_DMA_ENB; dfx_port_write_long(bp, PFI_K_REG_MODE_CTRL, val); } } /* * ================== * = dfx_bus_uninit = * ================== * * Overview: * Uninitializes the bus-specific controller logic. * * Returns: * None * * Arguments: * dev - pointer to device information * * Functional Description: * Perform bus-specific logic uninitialization. * * Return Codes: * None * * Assumptions: * bp->base has already been set with the proper * base I/O address for this device. * * Side Effects: * Interrupts are disabled at the adapter bus-specific logic. */ static void dfx_bus_uninit(struct net_device *dev) { DFX_board_t *bp = netdev_priv(dev); struct device *bdev = bp->bus_dev; int dfx_bus_pci = dev_is_pci(bdev); int dfx_bus_eisa = DFX_BUS_EISA(bdev); u8 val; DBG_printk("In dfx_bus_uninit...\n"); /* Uninitialize adapter based on bus type */ if (dfx_bus_eisa) { unsigned long base_addr = to_eisa_device(bdev)->base_addr; /* Disable interrupts at EISA bus interface chip (ESIC) */ val = inb(base_addr + PI_ESIC_K_IO_CONFIG_STAT_0); val &= ~PI_CONFIG_STAT_0_M_INT_ENB; outb(val, base_addr + PI_ESIC_K_IO_CONFIG_STAT_0); /* Disable the board. */ outb(0, base_addr + PI_ESIC_K_SLOT_CNTRL); /* Disable memory and port decoders. */ outb(0, base_addr + PI_ESIC_K_FUNCTION_CNTRL); } if (dfx_bus_pci) { /* Disable interrupts at PCI bus interface chip (PFI) */ dfx_port_write_long(bp, PFI_K_REG_MODE_CTRL, 0); } } /* * ======================== * = dfx_bus_config_check = * ======================== * * Overview: * Checks the configuration (burst size, full-duplex, etc.) If any parameters * are illegal, then this routine will set new defaults. * * Returns: * None * * Arguments: * bp - pointer to board information * * Functional Description: * For Revision 1 FDDI EISA, Revision 2 or later FDDI EISA with rev E or later * PDQ, and all FDDI PCI controllers, all values are legal. * * Return Codes: * None * * Assumptions: * dfx_adap_init has NOT been called yet so burst size and other items have * not been set. * * Side Effects: * None */ static void dfx_bus_config_check(DFX_board_t *bp) { struct device __maybe_unused *bdev = bp->bus_dev; int dfx_bus_eisa = DFX_BUS_EISA(bdev); int status; /* return code from adapter port control call */ u32 host_data; /* LW data returned from port control call */ DBG_printk("In dfx_bus_config_check...\n"); /* Configuration check only valid for EISA adapter */ if (dfx_bus_eisa) { /* * First check if revision 2 EISA controller. Rev. 1 cards used * PDQ revision B, so no workaround needed in this case. Rev. 3 * cards used PDQ revision E, so no workaround needed in this * case, either. Only Rev. 2 cards used either Rev. D or E * chips, so we must verify the chip revision on Rev. 2 cards. */ if (to_eisa_device(bdev)->id.driver_data == DEFEA_PROD_ID_2) { /* * Revision 2 FDDI EISA controller found, * so let's check PDQ revision of adapter. */ status = dfx_hw_port_ctrl_req(bp, PI_PCTRL_M_SUB_CMD, PI_SUB_CMD_K_PDQ_REV_GET, 0, &host_data); if ((status != DFX_K_SUCCESS) || (host_data == 2)) { /* * Either we couldn't determine the PDQ revision, or * we determined that it is at revision D. In either case, * we need to implement the workaround. */ /* Ensure that the burst size is set to 8 longwords or less */ switch (bp->burst_size) { case PI_PDATA_B_DMA_BURST_SIZE_32: case PI_PDATA_B_DMA_BURST_SIZE_16: bp->burst_size = PI_PDATA_B_DMA_BURST_SIZE_8; break; default: break; } /* Ensure that full-duplex mode is not enabled */ bp->full_duplex_enb = PI_SNMP_K_FALSE; } } } } /* * =================== * = dfx_driver_init = * =================== * * Overview: * Initializes remaining adapter board structure information * and makes sure adapter is in a safe state prior to dfx_open(). * * Returns: * Condition code * * Arguments: * dev - pointer to device information * print_name - printable device name * * Functional Description: * This function allocates additional resources such as the host memory * blocks needed by the adapter (eg. descriptor and consumer blocks). * Remaining bus initialization steps are also completed. The adapter * is also reset so that it is in the DMA_UNAVAILABLE state. The OS * must call dfx_open() to open the adapter and bring it on-line. * * Return Codes: * DFX_K_SUCCESS - initialization succeeded * DFX_K_FAILURE - initialization failed - could not allocate memory * or read adapter MAC address * * Assumptions: * Memory allocated from pci_alloc_consistent() call is physically * contiguous, locked memory. * * Side Effects: * Adapter is reset and should be in DMA_UNAVAILABLE state before * returning from this routine. */ static int dfx_driver_init(struct net_device *dev, const char *print_name, resource_size_t bar_start) { DFX_board_t *bp = netdev_priv(dev); struct device *bdev = bp->bus_dev; int dfx_bus_pci = dev_is_pci(bdev); int dfx_bus_eisa = DFX_BUS_EISA(bdev); int dfx_bus_tc = DFX_BUS_TC(bdev); int dfx_use_mmio = DFX_MMIO || dfx_bus_tc; int alloc_size; /* total buffer size needed */ char *top_v, *curr_v; /* virtual addrs into memory block */ dma_addr_t top_p, curr_p; /* physical addrs into memory block */ u32 data; /* host data register value */ __le32 le32; char *board_name = NULL; DBG_printk("In dfx_driver_init...\n"); /* Initialize bus-specific hardware registers */ dfx_bus_init(dev); /* * Initialize default values for configurable parameters * * Note: All of these parameters are ones that a user may * want to customize. It'd be nice to break these * out into Space.c or someplace else that's more * accessible/understandable than this file. */ bp->full_duplex_enb = PI_SNMP_K_FALSE; bp->req_ttrt = 8 * 12500; /* 8ms in 80 nanosec units */ bp->burst_size = PI_PDATA_B_DMA_BURST_SIZE_DEF; bp->rcv_bufs_to_post = RCV_BUFS_DEF; /* * Ensure that HW configuration is OK * * Note: Depending on the hardware revision, we may need to modify * some of the configurable parameters to workaround hardware * limitations. We'll perform this configuration check AFTER * setting the parameters to their default values. */ dfx_bus_config_check(bp); /* Disable PDQ interrupts first */ dfx_port_write_long(bp, PI_PDQ_K_REG_HOST_INT_ENB, PI_HOST_INT_K_DISABLE_ALL_INTS); /* Place adapter in DMA_UNAVAILABLE state by resetting adapter */ (void) dfx_hw_dma_uninit(bp, PI_PDATA_A_RESET_M_SKIP_ST); /* Read the factory MAC address from the adapter then save it */ if (dfx_hw_port_ctrl_req(bp, PI_PCTRL_M_MLA, PI_PDATA_A_MLA_K_LO, 0, &data) != DFX_K_SUCCESS) { printk("%s: Could not read adapter factory MAC address!\n", print_name); return DFX_K_FAILURE; } le32 = cpu_to_le32(data); memcpy(&bp->factory_mac_addr[0], &le32, sizeof(u32)); if (dfx_hw_port_ctrl_req(bp, PI_PCTRL_M_MLA, PI_PDATA_A_MLA_K_HI, 0, &data) != DFX_K_SUCCESS) { printk("%s: Could not read adapter factory MAC address!\n", print_name); return DFX_K_FAILURE; } le32 = cpu_to_le32(data); memcpy(&bp->factory_mac_addr[4], &le32, sizeof(u16)); /* * Set current address to factory address * * Note: Node address override support is handled through * dfx_ctl_set_mac_address. */ memcpy(dev->dev_addr, bp->factory_mac_addr, FDDI_K_ALEN); if (dfx_bus_tc) board_name = "DEFTA"; if (dfx_bus_eisa) board_name = "DEFEA"; if (dfx_bus_pci) board_name = "DEFPA"; pr_info("%s: %s at %s addr = 0x%llx, IRQ = %d, Hardware addr = %pMF\n", print_name, board_name, dfx_use_mmio ? "MMIO" : "I/O", (long long)bar_start, dev->irq, dev->dev_addr); /* * Get memory for descriptor block, consumer block, and other buffers * that need to be DMA read or written to by the adapter. */ alloc_size = sizeof(PI_DESCR_BLOCK) + PI_CMD_REQ_K_SIZE_MAX + PI_CMD_RSP_K_SIZE_MAX + #ifndef DYNAMIC_BUFFERS (bp->rcv_bufs_to_post * PI_RCV_DATA_K_SIZE_MAX) + #endif sizeof(PI_CONSUMER_BLOCK) + (PI_ALIGN_K_DESC_BLK - 1); bp->kmalloced = top_v = dma_zalloc_coherent(bp->bus_dev, alloc_size, &bp->kmalloced_dma, GFP_ATOMIC); if (top_v == NULL) return DFX_K_FAILURE; top_p = bp->kmalloced_dma; /* get physical address of buffer */ /* * To guarantee the 8K alignment required for the descriptor block, 8K - 1 * plus the amount of memory needed was allocated. The physical address * is now 8K aligned. By carving up the memory in a specific order, * we'll guarantee the alignment requirements for all other structures. * * Note: If the assumptions change regarding the non-paged, non-cached, * physically contiguous nature of the memory block or the address * alignments, then we'll need to implement a different algorithm * for allocating the needed memory. */ curr_p = ALIGN(top_p, PI_ALIGN_K_DESC_BLK); curr_v = top_v + (curr_p - top_p); /* Reserve space for descriptor block */ bp->descr_block_virt = (PI_DESCR_BLOCK *) curr_v; bp->descr_block_phys = curr_p; curr_v += sizeof(PI_DESCR_BLOCK); curr_p += sizeof(PI_DESCR_BLOCK); /* Reserve space for command request buffer */ bp->cmd_req_virt = (PI_DMA_CMD_REQ *) curr_v; bp->cmd_req_phys = curr_p; curr_v += PI_CMD_REQ_K_SIZE_MAX; curr_p += PI_CMD_REQ_K_SIZE_MAX; /* Reserve space for command response buffer */ bp->cmd_rsp_virt = (PI_DMA_CMD_RSP *) curr_v; bp->cmd_rsp_phys = curr_p; curr_v += PI_CMD_RSP_K_SIZE_MAX; curr_p += PI_CMD_RSP_K_SIZE_MAX; /* Reserve space for the LLC host receive queue buffers */ bp->rcv_block_virt = curr_v; bp->rcv_block_phys = curr_p; #ifndef DYNAMIC_BUFFERS curr_v += (bp->rcv_bufs_to_post * PI_RCV_DATA_K_SIZE_MAX); curr_p += (bp->rcv_bufs_to_post * PI_RCV_DATA_K_SIZE_MAX); #endif /* Reserve space for the consumer block */ bp->cons_block_virt = (PI_CONSUMER_BLOCK *) curr_v; bp->cons_block_phys = curr_p; /* Display virtual and physical addresses if debug driver */ DBG_printk("%s: Descriptor block virt = %p, phys = %pad\n", print_name, bp->descr_block_virt, &bp->descr_block_phys); DBG_printk("%s: Command Request buffer virt = %p, phys = %pad\n", print_name, bp->cmd_req_virt, &bp->cmd_req_phys); DBG_printk("%s: Command Response buffer virt = %p, phys = %pad\n", print_name, bp->cmd_rsp_virt, &bp->cmd_rsp_phys); DBG_printk("%s: Receive buffer block virt = %p, phys = %pad\n", print_name, bp->rcv_block_virt, &bp->rcv_block_phys); DBG_printk("%s: Consumer block virt = %p, phys = %pad\n", print_name, bp->cons_block_virt, &bp->cons_block_phys); return DFX_K_SUCCESS; } /* * ================= * = dfx_adap_init = * ================= * * Overview: * Brings the adapter to the link avail/link unavailable state. * * Returns: * Condition code * * Arguments: * bp - pointer to board information * get_buffers - non-zero if buffers to be allocated * * Functional Description: * Issues the low-level firmware/hardware calls necessary to bring * the adapter up, or to properly reset and restore adapter during * run-time. * * Return Codes: * DFX_K_SUCCESS - Adapter brought up successfully * DFX_K_FAILURE - Adapter initialization failed * * Assumptions: * bp->reset_type should be set to a valid reset type value before * calling this routine. * * Side Effects: * Adapter should be in LINK_AVAILABLE or LINK_UNAVAILABLE state * upon a successful return of this routine. */ static int dfx_adap_init(DFX_board_t *bp, int get_buffers) { DBG_printk("In dfx_adap_init...\n"); /* Disable PDQ interrupts first */ dfx_port_write_long(bp, PI_PDQ_K_REG_HOST_INT_ENB, PI_HOST_INT_K_DISABLE_ALL_INTS); /* Place adapter in DMA_UNAVAILABLE state by resetting adapter */ if (dfx_hw_dma_uninit(bp, bp->reset_type) != DFX_K_SUCCESS) { printk("%s: Could not uninitialize/reset adapter!\n", bp->dev->name); return DFX_K_FAILURE; } /* * When the PDQ is reset, some false Type 0 interrupts may be pending, * so we'll acknowledge all Type 0 interrupts now before continuing. */ dfx_port_write_long(bp, PI_PDQ_K_REG_TYPE_0_STATUS, PI_HOST_INT_K_ACK_ALL_TYPE_0); /* * Clear Type 1 and Type 2 registers before going to DMA_AVAILABLE state * * Note: We only need to clear host copies of these registers. The PDQ reset * takes care of the on-board register values. */ bp->cmd_req_reg.lword = 0; bp->cmd_rsp_reg.lword = 0; bp->rcv_xmt_reg.lword = 0; /* Clear consumer block before going to DMA_AVAILABLE state */ memset(bp->cons_block_virt, 0, sizeof(PI_CONSUMER_BLOCK)); /* Initialize the DMA Burst Size */ if (dfx_hw_port_ctrl_req(bp, PI_PCTRL_M_SUB_CMD, PI_SUB_CMD_K_BURST_SIZE_SET, bp->burst_size, NULL) != DFX_K_SUCCESS) { printk("%s: Could not set adapter burst size!\n", bp->dev->name); return DFX_K_FAILURE; } /* * Set base address of Consumer Block * * Assumption: 32-bit physical address of consumer block is 64 byte * aligned. That is, bits 0-5 of the address must be zero. */ if (dfx_hw_port_ctrl_req(bp, PI_PCTRL_M_CONS_BLOCK, bp->cons_block_phys, 0, NULL) != DFX_K_SUCCESS) { printk("%s: Could not set consumer block address!\n", bp->dev->name); return DFX_K_FAILURE; } /* * Set the base address of Descriptor Block and bring adapter * to DMA_AVAILABLE state. * * Note: We also set the literal and data swapping requirements * in this command. * * Assumption: 32-bit physical address of descriptor block * is 8Kbyte aligned. */ if (dfx_hw_port_ctrl_req(bp, PI_PCTRL_M_INIT, (u32)(bp->descr_block_phys | PI_PDATA_A_INIT_M_BSWAP_INIT), 0, NULL) != DFX_K_SUCCESS) { printk("%s: Could not set descriptor block address!\n", bp->dev->name); return DFX_K_FAILURE; } /* Set transmit flush timeout value */ bp->cmd_req_virt->cmd_type = PI_CMD_K_CHARS_SET; bp->cmd_req_virt->char_set.item[0].item_code = PI_ITEM_K_FLUSH_TIME; bp->cmd_req_virt->char_set.item[0].value = 3; /* 3 seconds */ bp->cmd_req_virt->char_set.item[0].item_index = 0; bp->cmd_req_virt->char_set.item[1].item_code = PI_ITEM_K_EOL; if (dfx_hw_dma_cmd_req(bp) != DFX_K_SUCCESS) { printk("%s: DMA command request failed!\n", bp->dev->name); return DFX_K_FAILURE; } /* Set the initial values for eFDXEnable and MACTReq MIB objects */ bp->cmd_req_virt->cmd_type = PI_CMD_K_SNMP_SET; bp->cmd_req_virt->snmp_set.item[0].item_code = PI_ITEM_K_FDX_ENB_DIS; bp->cmd_req_virt->snmp_set.item[0].value = bp->full_duplex_enb; bp->cmd_req_virt->snmp_set.item[0].item_index = 0; bp->cmd_req_virt->snmp_set.item[1].item_code = PI_ITEM_K_MAC_T_REQ; bp->cmd_req_virt->snmp_set.item[1].value = bp->req_ttrt; bp->cmd_req_virt->snmp_set.item[1].item_index = 0; bp->cmd_req_virt->snmp_set.item[2].item_code = PI_ITEM_K_EOL; if (dfx_hw_dma_cmd_req(bp) != DFX_K_SUCCESS) { printk("%s: DMA command request failed!\n", bp->dev->name); return DFX_K_FAILURE; } /* Initialize adapter CAM */ if (dfx_ctl_update_cam(bp) != DFX_K_SUCCESS) { printk("%s: Adapter CAM update failed!\n", bp->dev->name); return DFX_K_FAILURE; } /* Initialize adapter filters */ if (dfx_ctl_update_filters(bp) != DFX_K_SUCCESS) { printk("%s: Adapter filters update failed!\n", bp->dev->name); return DFX_K_FAILURE; } /* * Remove any existing dynamic buffers (i.e. if the adapter is being * reinitialized) */ if (get_buffers) dfx_rcv_flush(bp); /* Initialize receive descriptor block and produce buffers */ if (dfx_rcv_init(bp, get_buffers)) { printk("%s: Receive buffer allocation failed\n", bp->dev->name); if (get_buffers) dfx_rcv_flush(bp); return DFX_K_FAILURE; } /* Issue START command and bring adapter to LINK_(UN)AVAILABLE state */ bp->cmd_req_virt->cmd_type = PI_CMD_K_START; if (dfx_hw_dma_cmd_req(bp) != DFX_K_SUCCESS) { printk("%s: Start command failed\n", bp->dev->name); if (get_buffers) dfx_rcv_flush(bp); return DFX_K_FAILURE; } /* Initialization succeeded, reenable PDQ interrupts */ dfx_port_write_long(bp, PI_PDQ_K_REG_HOST_INT_ENB, PI_HOST_INT_K_ENABLE_DEF_INTS); return DFX_K_SUCCESS; } /* * ============ * = dfx_open = * ============ * * Overview: * Opens the adapter * * Returns: * Condition code * * Arguments: * dev - pointer to device information * * Functional Description: * This function brings the adapter to an operational state. * * Return Codes: * 0 - Adapter was successfully opened * -EAGAIN - Could not register IRQ or adapter initialization failed * * Assumptions: * This routine should only be called for a device that was * initialized successfully. * * Side Effects: * Adapter should be in LINK_AVAILABLE or LINK_UNAVAILABLE state * if the open is successful. */ static int dfx_open(struct net_device *dev) { DFX_board_t *bp = netdev_priv(dev); int ret; DBG_printk("In dfx_open...\n"); /* Register IRQ - support shared interrupts by passing device ptr */ ret = request_irq(dev->irq, dfx_interrupt, IRQF_SHARED, dev->name, dev); if (ret) { printk(KERN_ERR "%s: Requested IRQ %d is busy\n", dev->name, dev->irq); return ret; } /* * Set current address to factory MAC address * * Note: We've already done this step in dfx_driver_init. * However, it's possible that a user has set a node * address override, then closed and reopened the * adapter. Unless we reset the device address field * now, we'll continue to use the existing modified * address. */ memcpy(dev->dev_addr, bp->factory_mac_addr, FDDI_K_ALEN); /* Clear local unicast/multicast address tables and counts */ memset(bp->uc_table, 0, sizeof(bp->uc_table)); memset(bp->mc_table, 0, sizeof(bp->mc_table)); bp->uc_count = 0; bp->mc_count = 0; /* Disable promiscuous filter settings */ bp->ind_group_prom = PI_FSTATE_K_BLOCK; bp->group_prom = PI_FSTATE_K_BLOCK; spin_lock_init(&bp->lock); /* Reset and initialize adapter */ bp->reset_type = PI_PDATA_A_RESET_M_SKIP_ST; /* skip self-test */ if (dfx_adap_init(bp, 1) != DFX_K_SUCCESS) { printk(KERN_ERR "%s: Adapter open failed!\n", dev->name); free_irq(dev->irq, dev); return -EAGAIN; } /* Set device structure info */ netif_start_queue(dev); return 0; } /* * ============= * = dfx_close = * ============= * * Overview: * Closes the device/module. * * Returns: * Condition code * * Arguments: * dev - pointer to device information * * Functional Description: * This routine closes the adapter and brings it to a safe state. * The interrupt service routine is deregistered with the OS. * The adapter can be opened again with another call to dfx_open(). * * Return Codes: * Always return 0. * * Assumptions: * No further requests for this adapter are made after this routine is * called. dfx_open() can be called to reset and reinitialize the * adapter. * * Side Effects: * Adapter should be in DMA_UNAVAILABLE state upon completion of this * routine. */ static int dfx_close(struct net_device *dev) { DFX_board_t *bp = netdev_priv(dev); DBG_printk("In dfx_close...\n"); /* Disable PDQ interrupts first */ dfx_port_write_long(bp, PI_PDQ_K_REG_HOST_INT_ENB, PI_HOST_INT_K_DISABLE_ALL_INTS); /* Place adapter in DMA_UNAVAILABLE state by resetting adapter */ (void) dfx_hw_dma_uninit(bp, PI_PDATA_A_RESET_M_SKIP_ST); /* * Flush any pending transmit buffers * * Note: It's important that we flush the transmit buffers * BEFORE we clear our copy of the Type 2 register. * Otherwise, we'll have no idea how many buffers * we need to free. */ dfx_xmt_flush(bp); /* * Clear Type 1 and Type 2 registers after adapter reset * * Note: Even though we're closing the adapter, it's * possible that an interrupt will occur after * dfx_close is called. Without some assurance to * the contrary we want to make sure that we don't * process receive and transmit LLC frames and update * the Type 2 register with bad information. */ bp->cmd_req_reg.lword = 0; bp->cmd_rsp_reg.lword = 0; bp->rcv_xmt_reg.lword = 0; /* Clear consumer block for the same reason given above */ memset(bp->cons_block_virt, 0, sizeof(PI_CONSUMER_BLOCK)); /* Release all dynamically allocate skb in the receive ring. */ dfx_rcv_flush(bp); /* Clear device structure flags */ netif_stop_queue(dev); /* Deregister (free) IRQ */ free_irq(dev->irq, dev); return 0; } /* * ====================== * = dfx_int_pr_halt_id = * ====================== * * Overview: * Displays halt id's in string form. * * Returns: * None * * Arguments: * bp - pointer to board information * * Functional Description: * Determine current halt id and display appropriate string. * * Return Codes: * None * * Assumptions: * None * * Side Effects: * None */ static void dfx_int_pr_halt_id(DFX_board_t *bp) { PI_UINT32 port_status; /* PDQ port status register value */ PI_UINT32 halt_id; /* PDQ port status halt ID */ /* Read the latest port status */ dfx_port_read_long(bp, PI_PDQ_K_REG_PORT_STATUS, &port_status); /* Display halt state transition information */ halt_id = (port_status & PI_PSTATUS_M_HALT_ID) >> PI_PSTATUS_V_HALT_ID; switch (halt_id) { case PI_HALT_ID_K_SELFTEST_TIMEOUT: printk("%s: Halt ID: Selftest Timeout\n", bp->dev->name); break; case PI_HALT_ID_K_PARITY_ERROR: printk("%s: Halt ID: Host Bus Parity Error\n", bp->dev->name); break; case PI_HALT_ID_K_HOST_DIR_HALT: printk("%s: Halt ID: Host-Directed Halt\n", bp->dev->name); break; case PI_HALT_ID_K_SW_FAULT: printk("%s: Halt ID: Adapter Software Fault\n", bp->dev->name); break; case PI_HALT_ID_K_HW_FAULT: printk("%s: Halt ID: Adapter Hardware Fault\n", bp->dev->name); break; case PI_HALT_ID_K_PC_TRACE: printk("%s: Halt ID: FDDI Network PC Trace Path Test\n", bp->dev->name); break; case PI_HALT_ID_K_DMA_ERROR: printk("%s: Halt ID: Adapter DMA Error\n", bp->dev->name); break; case PI_HALT_ID_K_IMAGE_CRC_ERROR: printk("%s: Halt ID: Firmware Image CRC Error\n", bp->dev->name); break; case PI_HALT_ID_K_BUS_EXCEPTION: printk("%s: Halt ID: 68000 Bus Exception\n", bp->dev->name); break; default: printk("%s: Halt ID: Unknown (code = %X)\n", bp->dev->name, halt_id); break; } } /* * ========================== * = dfx_int_type_0_process = * ========================== * * Overview: * Processes Type 0 interrupts. * * Returns: * None * * Arguments: * bp - pointer to board information * * Functional Description: * Processes all enabled Type 0 interrupts. If the reason for the interrupt * is a serious fault on the adapter, then an error message is displayed * and the adapter is reset. * * One tricky potential timing window is the rapid succession of "link avail" * "link unavail" state change interrupts. The acknowledgement of the Type 0 * interrupt must be done before reading the state from the Port Status * register. This is true because a state change could occur after reading * the data, but before acknowledging the interrupt. If this state change * does happen, it would be lost because the driver is using the old state, * and it will never know about the new state because it subsequently * acknowledges the state change interrupt. * * INCORRECT CORRECT * read type 0 int reasons read type 0 int reasons * read adapter state ack type 0 interrupts * ack type 0 interrupts read adapter state * ... process interrupt ... ... process interrupt ... * * Return Codes: * None * * Assumptions: * None * * Side Effects: * An adapter reset may occur if the adapter has any Type 0 error interrupts * or if the port status indicates that the adapter is halted. The driver * is responsible for reinitializing the adapter with the current CAM * contents and adapter filter settings. */ static void dfx_int_type_0_process(DFX_board_t *bp) { PI_UINT32 type_0_status; /* Host Interrupt Type 0 register */ PI_UINT32 state; /* current adap state (from port status) */ /* * Read host interrupt Type 0 register to determine which Type 0 * interrupts are pending. Immediately write it back out to clear * those interrupts. */ dfx_port_read_long(bp, PI_PDQ_K_REG_TYPE_0_STATUS, &type_0_status); dfx_port_write_long(bp, PI_PDQ_K_REG_TYPE_0_STATUS, type_0_status); /* Check for Type 0 error interrupts */ if (type_0_status & (PI_TYPE_0_STAT_M_NXM | PI_TYPE_0_STAT_M_PM_PAR_ERR | PI_TYPE_0_STAT_M_BUS_PAR_ERR)) { /* Check for Non-Existent Memory error */ if (type_0_status & PI_TYPE_0_STAT_M_NXM) printk("%s: Non-Existent Memory Access Error\n", bp->dev->name); /* Check for Packet Memory Parity error */ if (type_0_status & PI_TYPE_0_STAT_M_PM_PAR_ERR) printk("%s: Packet Memory Parity Error\n", bp->dev->name); /* Check for Host Bus Parity error */ if (type_0_status & PI_TYPE_0_STAT_M_BUS_PAR_ERR) printk("%s: Host Bus Parity Error\n", bp->dev->name); /* Reset adapter and bring it back on-line */ bp->link_available = PI_K_FALSE; /* link is no longer available */ bp->reset_type = 0; /* rerun on-board diagnostics */ printk("%s: Resetting adapter...\n", bp->dev->name); if (dfx_adap_init(bp, 0) != DFX_K_SUCCESS) { printk("%s: Adapter reset failed! Disabling adapter interrupts.\n", bp->dev->name); dfx_port_write_long(bp, PI_PDQ_K_REG_HOST_INT_ENB, PI_HOST_INT_K_DISABLE_ALL_INTS); return; } printk("%s: Adapter reset successful!\n", bp->dev->name); return; } /* Check for transmit flush interrupt */ if (type_0_status & PI_TYPE_0_STAT_M_XMT_FLUSH) { /* Flush any pending xmt's and acknowledge the flush interrupt */ bp->link_available = PI_K_FALSE; /* link is no longer available */ dfx_xmt_flush(bp); /* flush any outstanding packets */ (void) dfx_hw_port_ctrl_req(bp, PI_PCTRL_M_XMT_DATA_FLUSH_DONE, 0, 0, NULL); } /* Check for adapter state change */ if (type_0_status & PI_TYPE_0_STAT_M_STATE_CHANGE) { /* Get latest adapter state */ state = dfx_hw_adap_state_rd(bp); /* get adapter state */ if (state == PI_STATE_K_HALTED) { /* * Adapter has transitioned to HALTED state, try to reset * adapter to bring it back on-line. If reset fails, * leave the adapter in the broken state. */ printk("%s: Controller has transitioned to HALTED state!\n", bp->dev->name); dfx_int_pr_halt_id(bp); /* display halt id as string */ /* Reset adapter and bring it back on-line */ bp->link_available = PI_K_FALSE; /* link is no longer available */ bp->reset_type = 0; /* rerun on-board diagnostics */ printk("%s: Resetting adapter...\n", bp->dev->name); if (dfx_adap_init(bp, 0) != DFX_K_SUCCESS) { printk("%s: Adapter reset failed! Disabling adapter interrupts.\n", bp->dev->name); dfx_port_write_long(bp, PI_PDQ_K_REG_HOST_INT_ENB, PI_HOST_INT_K_DISABLE_ALL_INTS); return; } printk("%s: Adapter reset successful!\n", bp->dev->name); } else if (state == PI_STATE_K_LINK_AVAIL) { bp->link_available = PI_K_TRUE; /* set link available flag */ } } } /* * ================== * = dfx_int_common = * ================== * * Overview: * Interrupt service routine (ISR) * * Returns: * None * * Arguments: * bp - pointer to board information * * Functional Description: * This is the ISR which processes incoming adapter interrupts. * * Return Codes: * None * * Assumptions: * This routine assumes PDQ interrupts have not been disabled. * When interrupts are disabled at the PDQ, the Port Status register * is automatically cleared. This routine uses the Port Status * register value to determine whether a Type 0 interrupt occurred, * so it's important that adapter interrupts are not normally * enabled/disabled at the PDQ. * * It's vital that this routine is NOT reentered for the * same board and that the OS is not in another section of * code (eg. dfx_xmt_queue_pkt) for the same board on a * different thread. * * Side Effects: * Pending interrupts are serviced. Depending on the type of * interrupt, acknowledging and clearing the interrupt at the * PDQ involves writing a register to clear the interrupt bit * or updating completion indices. */ static void dfx_int_common(struct net_device *dev) { DFX_board_t *bp = netdev_priv(dev); PI_UINT32 port_status; /* Port Status register */ /* Process xmt interrupts - frequent case, so always call this routine */ if(dfx_xmt_done(bp)) /* free consumed xmt packets */ netif_wake_queue(dev); /* Process rcv interrupts - frequent case, so always call this routine */ dfx_rcv_queue_process(bp); /* service received LLC frames */ /* * Transmit and receive producer and completion indices are updated on the * adapter by writing to the Type 2 Producer register. Since the frequent * case is that we'll be processing either LLC transmit or receive buffers, * we'll optimize I/O writes by doing a single register write here. */ dfx_port_write_long(bp, PI_PDQ_K_REG_TYPE_2_PROD, bp->rcv_xmt_reg.lword); /* Read PDQ Port Status register to find out which interrupts need processing */ dfx_port_read_long(bp, PI_PDQ_K_REG_PORT_STATUS, &port_status); /* Process Type 0 interrupts (if any) - infrequent, so only call when needed */ if (port_status & PI_PSTATUS_M_TYPE_0_PENDING) dfx_int_type_0_process(bp); /* process Type 0 interrupts */ } /* * ================= * = dfx_interrupt = * ================= * * Overview: * Interrupt processing routine * * Returns: * Whether a valid interrupt was seen. * * Arguments: * irq - interrupt vector * dev_id - pointer to device information * * Functional Description: * This routine calls the interrupt processing routine for this adapter. It * disables and reenables adapter interrupts, as appropriate. We can support * shared interrupts since the incoming dev_id pointer provides our device * structure context. * * Return Codes: * IRQ_HANDLED - an IRQ was handled. * IRQ_NONE - no IRQ was handled. * * Assumptions: * The interrupt acknowledgement at the hardware level (eg. ACKing the PIC * on Intel-based systems) is done by the operating system outside this * routine. * * System interrupts are enabled through this call. * * Side Effects: * Interrupts are disabled, then reenabled at the adapter. */ static irqreturn_t dfx_interrupt(int irq, void *dev_id) { struct net_device *dev = dev_id; DFX_board_t *bp = netdev_priv(dev); struct device *bdev = bp->bus_dev; int dfx_bus_pci = dev_is_pci(bdev); int dfx_bus_eisa = DFX_BUS_EISA(bdev); int dfx_bus_tc = DFX_BUS_TC(bdev); /* Service adapter interrupts */ if (dfx_bus_pci) { u32 status; dfx_port_read_long(bp, PFI_K_REG_STATUS, &status); if (!(status & PFI_STATUS_M_PDQ_INT)) return IRQ_NONE; spin_lock(&bp->lock); /* Disable PDQ-PFI interrupts at PFI */ dfx_port_write_long(bp, PFI_K_REG_MODE_CTRL, PFI_MODE_M_DMA_ENB); /* Call interrupt service routine for this adapter */ dfx_int_common(dev); /* Clear PDQ interrupt status bit and reenable interrupts */ dfx_port_write_long(bp, PFI_K_REG_STATUS, PFI_STATUS_M_PDQ_INT); dfx_port_write_long(bp, PFI_K_REG_MODE_CTRL, (PFI_MODE_M_PDQ_INT_ENB | PFI_MODE_M_DMA_ENB)); spin_unlock(&bp->lock); } if (dfx_bus_eisa) { unsigned long base_addr = to_eisa_device(bdev)->base_addr; u8 status; status = inb(base_addr + PI_ESIC_K_IO_CONFIG_STAT_0); if (!(status & PI_CONFIG_STAT_0_M_PEND)) return IRQ_NONE; spin_lock(&bp->lock); /* Disable interrupts at the ESIC */ status &= ~PI_CONFIG_STAT_0_M_INT_ENB; outb(status, base_addr + PI_ESIC_K_IO_CONFIG_STAT_0); /* Call interrupt service routine for this adapter */ dfx_int_common(dev); /* Reenable interrupts at the ESIC */ status = inb(base_addr + PI_ESIC_K_IO_CONFIG_STAT_0); status |= PI_CONFIG_STAT_0_M_INT_ENB; outb(status, base_addr + PI_ESIC_K_IO_CONFIG_STAT_0); spin_unlock(&bp->lock); } if (dfx_bus_tc) { u32 status; dfx_port_read_long(bp, PI_PDQ_K_REG_PORT_STATUS, &status); if (!(status & (PI_PSTATUS_M_RCV_DATA_PENDING | PI_PSTATUS_M_XMT_DATA_PENDING | PI_PSTATUS_M_SMT_HOST_PENDING | PI_PSTATUS_M_UNSOL_PENDING | PI_PSTATUS_M_CMD_RSP_PENDING | PI_PSTATUS_M_CMD_REQ_PENDING | PI_PSTATUS_M_TYPE_0_PENDING))) return IRQ_NONE; spin_lock(&bp->lock); /* Call interrupt service routine for this adapter */ dfx_int_common(dev); spin_unlock(&bp->lock); } return IRQ_HANDLED; } /* * ===================== * = dfx_ctl_get_stats = * ===================== * * Overview: * Get statistics for FDDI adapter * * Returns: * Pointer to FDDI statistics structure * * Arguments: * dev - pointer to device information * * Functional Description: * Gets current MIB objects from adapter, then * returns FDDI statistics structure as defined * in if_fddi.h. * * Note: Since the FDDI statistics structure is * still new and the device structure doesn't * have an FDDI-specific get statistics handler, * we'll return the FDDI statistics structure as * a pointer to an Ethernet statistics structure. * That way, at least the first part of the statistics * structure can be decoded properly, and it allows * "smart" applications to perform a second cast to * decode the FDDI-specific statistics. * * We'll have to pay attention to this routine as the * device structure becomes more mature and LAN media * independent. * * Return Codes: * None * * Assumptions: * None * * Side Effects: * None */ static struct net_device_stats *dfx_ctl_get_stats(struct net_device *dev) { DFX_board_t *bp = netdev_priv(dev); /* Fill the bp->stats structure with driver-maintained counters */ bp->stats.gen.rx_packets = bp->rcv_total_frames; bp->stats.gen.tx_packets = bp->xmt_total_frames; bp->stats.gen.rx_bytes = bp->rcv_total_bytes; bp->stats.gen.tx_bytes = bp->xmt_total_bytes; bp->stats.gen.rx_errors = bp->rcv_crc_errors + bp->rcv_frame_status_errors + bp->rcv_length_errors; bp->stats.gen.tx_errors = bp->xmt_length_errors; bp->stats.gen.rx_dropped = bp->rcv_discards; bp->stats.gen.tx_dropped = bp->xmt_discards; bp->stats.gen.multicast = bp->rcv_multicast_frames; bp->stats.gen.collisions = 0; /* always zero (0) for FDDI */ /* Get FDDI SMT MIB objects */ bp->cmd_req_virt->cmd_type = PI_CMD_K_SMT_MIB_GET; if (dfx_hw_dma_cmd_req(bp) != DFX_K_SUCCESS) return (struct net_device_stats *)&bp->stats; /* Fill the bp->stats structure with the SMT MIB object values */ memcpy(bp->stats.smt_station_id, &bp->cmd_rsp_virt->smt_mib_get.smt_station_id, sizeof(bp->cmd_rsp_virt->smt_mib_get.smt_station_id)); bp->stats.smt_op_version_id = bp->cmd_rsp_virt->smt_mib_get.smt_op_version_id; bp->stats.smt_hi_version_id = bp->cmd_rsp_virt->smt_mib_get.smt_hi_version_id; bp->stats.smt_lo_version_id = bp->cmd_rsp_virt->smt_mib_get.smt_lo_version_id; memcpy(bp->stats.smt_user_data, &bp->cmd_rsp_virt->smt_mib_get.smt_user_data, sizeof(bp->cmd_rsp_virt->smt_mib_get.smt_user_data)); bp->stats.smt_mib_version_id = bp->cmd_rsp_virt->smt_mib_get.smt_mib_version_id; bp->stats.smt_mac_cts = bp->cmd_rsp_virt->smt_mib_get.smt_mac_ct; bp->stats.smt_non_master_cts = bp->cmd_rsp_virt->smt_mib_get.smt_non_master_ct; bp->stats.smt_master_cts = bp->cmd_rsp_virt->smt_mib_get.smt_master_ct; bp->stats.smt_available_paths = bp->cmd_rsp_virt->smt_mib_get.smt_available_paths; bp->stats.smt_config_capabilities = bp->cmd_rsp_virt->smt_mib_get.smt_config_capabilities; bp->stats.smt_config_policy = bp->cmd_rsp_virt->smt_mib_get.smt_config_policy; bp->stats.smt_connection_policy = bp->cmd_rsp_virt->smt_mib_get.smt_connection_policy; bp->stats.smt_t_notify = bp->cmd_rsp_virt->smt_mib_get.smt_t_notify; bp->stats.smt_stat_rpt_policy = bp->cmd_rsp_virt->smt_mib_get.smt_stat_rpt_policy; bp->stats.smt_trace_max_expiration = bp->cmd_rsp_virt->smt_mib_get.smt_trace_max_expiration; bp->stats.smt_bypass_present = bp->cmd_rsp_virt->smt_mib_get.smt_bypass_present; bp->stats.smt_ecm_state = bp->cmd_rsp_virt->smt_mib_get.smt_ecm_state; bp->stats.smt_cf_state = bp->cmd_rsp_virt->smt_mib_get.smt_cf_state; bp->stats.smt_remote_disconnect_flag = bp->cmd_rsp_virt->smt_mib_get.smt_remote_disconnect_flag; bp->stats.smt_station_status = bp->cmd_rsp_virt->smt_mib_get.smt_station_status; bp->stats.smt_peer_wrap_flag = bp->cmd_rsp_virt->smt_mib_get.smt_peer_wrap_flag; bp->stats.smt_time_stamp = bp->cmd_rsp_virt->smt_mib_get.smt_msg_time_stamp.ls; bp->stats.smt_transition_time_stamp = bp->cmd_rsp_virt->smt_mib_get.smt_transition_time_stamp.ls; bp->stats.mac_frame_status_functions = bp->cmd_rsp_virt->smt_mib_get.mac_frame_status_functions; bp->stats.mac_t_max_capability = bp->cmd_rsp_virt->smt_mib_get.mac_t_max_capability; bp->stats.mac_tvx_capability = bp->cmd_rsp_virt->smt_mib_get.mac_tvx_capability; bp->stats.mac_available_paths = bp->cmd_rsp_virt->smt_mib_get.mac_available_paths; bp->stats.mac_current_path = bp->cmd_rsp_virt->smt_mib_get.mac_current_path; memcpy(bp->stats.mac_upstream_nbr, &bp->cmd_rsp_virt->smt_mib_get.mac_upstream_nbr, FDDI_K_ALEN); memcpy(bp->stats.mac_downstream_nbr, &bp->cmd_rsp_virt->smt_mib_get.mac_downstream_nbr, FDDI_K_ALEN); memcpy(bp->stats.mac_old_upstream_nbr, &bp->cmd_rsp_virt->smt_mib_get.mac_old_upstream_nbr, FDDI_K_ALEN); memcpy(bp->stats.mac_old_downstream_nbr, &bp->cmd_rsp_virt->smt_mib_get.mac_old_downstream_nbr, FDDI_K_ALEN); bp->stats.mac_dup_address_test = bp->cmd_rsp_virt->smt_mib_get.mac_dup_address_test; bp->stats.mac_requested_paths = bp->cmd_rsp_virt->smt_mib_get.mac_requested_paths; bp->stats.mac_downstream_port_type = bp->cmd_rsp_virt->smt_mib_get.mac_downstream_port_type; memcpy(bp->stats.mac_smt_address, &bp->cmd_rsp_virt->smt_mib_get.mac_smt_address, FDDI_K_ALEN); bp->stats.mac_t_req = bp->cmd_rsp_virt->smt_mib_get.mac_t_req; bp->stats.mac_t_neg = bp->cmd_rsp_virt->smt_mib_get.mac_t_neg; bp->stats.mac_t_max = bp->cmd_rsp_virt->smt_mib_get.mac_t_max; bp->stats.mac_tvx_value = bp->cmd_rsp_virt->smt_mib_get.mac_tvx_value; bp->stats.mac_frame_error_threshold = bp->cmd_rsp_virt->smt_mib_get.mac_frame_error_threshold; bp->stats.mac_frame_error_ratio = bp->cmd_rsp_virt->smt_mib_get.mac_frame_error_ratio; bp->stats.mac_rmt_state = bp->cmd_rsp_virt->smt_mib_get.mac_rmt_state; bp->stats.mac_da_flag = bp->cmd_rsp_virt->smt_mib_get.mac_da_flag; bp->stats.mac_una_da_flag = bp->cmd_rsp_virt->smt_mib_get.mac_unda_flag; bp->stats.mac_frame_error_flag = bp->cmd_rsp_virt->smt_mib_get.mac_frame_error_flag; bp->stats.mac_ma_unitdata_available = bp->cmd_rsp_virt->smt_mib_get.mac_ma_unitdata_available; bp->stats.mac_hardware_present = bp->cmd_rsp_virt->smt_mib_get.mac_hardware_present; bp->stats.mac_ma_unitdata_enable = bp->cmd_rsp_virt->smt_mib_get.mac_ma_unitdata_enable; bp->stats.path_tvx_lower_bound = bp->cmd_rsp_virt->smt_mib_get.path_tvx_lower_bound; bp->stats.path_t_max_lower_bound = bp->cmd_rsp_virt->smt_mib_get.path_t_max_lower_bound; bp->stats.path_max_t_req = bp->cmd_rsp_virt->smt_mib_get.path_max_t_req; memcpy(bp->stats.path_configuration, &bp->cmd_rsp_virt->smt_mib_get.path_configuration, sizeof(bp->cmd_rsp_virt->smt_mib_get.path_configuration)); bp->stats.port_my_type[0] = bp->cmd_rsp_virt->smt_mib_get.port_my_type[0]; bp->stats.port_my_type[1] = bp->cmd_rsp_virt->smt_mib_get.port_my_type[1]; bp->stats.port_neighbor_type[0] = bp->cmd_rsp_virt->smt_mib_get.port_neighbor_type[0]; bp->stats.port_neighbor_type[1] = bp->cmd_rsp_virt->smt_mib_get.port_neighbor_type[1]; bp->stats.port_connection_policies[0] = bp->cmd_rsp_virt->smt_mib_get.port_connection_policies[0]; bp->stats.port_connection_policies[1] = bp->cmd_rsp_virt->smt_mib_get.port_connection_policies[1]; bp->stats.port_mac_indicated[0] = bp->cmd_rsp_virt->smt_mib_get.port_mac_indicated[0]; bp->stats.port_mac_indicated[1] = bp->cmd_rsp_virt->smt_mib_get.port_mac_indicated[1]; bp->stats.port_current_path[0] = bp->cmd_rsp_virt->smt_mib_get.port_current_path[0]; bp->stats.port_current_path[1] = bp->cmd_rsp_virt->smt_mib_get.port_current_path[1]; memcpy(&bp->stats.port_requested_paths[0*3], &bp->cmd_rsp_virt->smt_mib_get.port_requested_paths[0], 3); memcpy(&bp->stats.port_requested_paths[1*3], &bp->cmd_rsp_virt->smt_mib_get.port_requested_paths[1], 3); bp->stats.port_mac_placement[0] = bp->cmd_rsp_virt->smt_mib_get.port_mac_placement[0]; bp->stats.port_mac_placement[1] = bp->cmd_rsp_virt->smt_mib_get.port_mac_placement[1]; bp->stats.port_available_paths[0] = bp->cmd_rsp_virt->smt_mib_get.port_available_paths[0]; bp->stats.port_available_paths[1] = bp->cmd_rsp_virt->smt_mib_get.port_available_paths[1]; bp->stats.port_pmd_class[0] = bp->cmd_rsp_virt->smt_mib_get.port_pmd_class[0]; bp->stats.port_pmd_class[1] = bp->cmd_rsp_virt->smt_mib_get.port_pmd_class[1]; bp->stats.port_connection_capabilities[0] = bp->cmd_rsp_virt->smt_mib_get.port_connection_capabilities[0]; bp->stats.port_connection_capabilities[1] = bp->cmd_rsp_virt->smt_mib_get.port_connection_capabilities[1]; bp->stats.port_bs_flag[0] = bp->cmd_rsp_virt->smt_mib_get.port_bs_flag[0]; bp->stats.port_bs_flag[1] = bp->cmd_rsp_virt->smt_mib_get.port_bs_flag[1]; bp->stats.port_ler_estimate[0] = bp->cmd_rsp_virt->smt_mib_get.port_ler_estimate[0]; bp->stats.port_ler_estimate[1] = bp->cmd_rsp_virt->smt_mib_get.port_ler_estimate[1]; bp->stats.port_ler_cutoff[0] = bp->cmd_rsp_virt->smt_mib_get.port_ler_cutoff[0]; bp->stats.port_ler_cutoff[1] = bp->cmd_rsp_virt->smt_mib_get.port_ler_cutoff[1]; bp->stats.port_ler_alarm[0] = bp->cmd_rsp_virt->smt_mib_get.port_ler_alarm[0]; bp->stats.port_ler_alarm[1] = bp->cmd_rsp_virt->smt_mib_get.port_ler_alarm[1]; bp->stats.port_connect_state[0] = bp->cmd_rsp_virt->smt_mib_get.port_connect_state[0]; bp->stats.port_connect_state[1] = bp->cmd_rsp_virt->smt_mib_get.port_connect_state[1]; bp->stats.port_pcm_state[0] = bp->cmd_rsp_virt->smt_mib_get.port_pcm_state[0]; bp->stats.port_pcm_state[1] = bp->cmd_rsp_virt->smt_mib_get.port_pcm_state[1]; bp->stats.port_pc_withhold[0] = bp->cmd_rsp_virt->smt_mib_get.port_pc_withhold[0]; bp->stats.port_pc_withhold[1] = bp->cmd_rsp_virt->smt_mib_get.port_pc_withhold[1]; bp->stats.port_ler_flag[0] = bp->cmd_rsp_virt->smt_mib_get.port_ler_flag[0]; bp->stats.port_ler_flag[1] = bp->cmd_rsp_virt->smt_mib_get.port_ler_flag[1]; bp->stats.port_hardware_present[0] = bp->cmd_rsp_virt->smt_mib_get.port_hardware_present[0]; bp->stats.port_hardware_present[1] = bp->cmd_rsp_virt->smt_mib_get.port_hardware_present[1]; /* Get FDDI counters */ bp->cmd_req_virt->cmd_type = PI_CMD_K_CNTRS_GET; if (dfx_hw_dma_cmd_req(bp) != DFX_K_SUCCESS) return (struct net_device_stats *)&bp->stats; /* Fill the bp->stats structure with the FDDI counter values */ bp->stats.mac_frame_cts = bp->cmd_rsp_virt->cntrs_get.cntrs.frame_cnt.ls; bp->stats.mac_copied_cts = bp->cmd_rsp_virt->cntrs_get.cntrs.copied_cnt.ls; bp->stats.mac_transmit_cts = bp->cmd_rsp_virt->cntrs_get.cntrs.transmit_cnt.ls; bp->stats.mac_error_cts = bp->cmd_rsp_virt->cntrs_get.cntrs.error_cnt.ls; bp->stats.mac_lost_cts = bp->cmd_rsp_virt->cntrs_get.cntrs.lost_cnt.ls; bp->stats.port_lct_fail_cts[0] = bp->cmd_rsp_virt->cntrs_get.cntrs.lct_rejects[0].ls; bp->stats.port_lct_fail_cts[1] = bp->cmd_rsp_virt->cntrs_get.cntrs.lct_rejects[1].ls; bp->stats.port_lem_reject_cts[0] = bp->cmd_rsp_virt->cntrs_get.cntrs.lem_rejects[0].ls; bp->stats.port_lem_reject_cts[1] = bp->cmd_rsp_virt->cntrs_get.cntrs.lem_rejects[1].ls; bp->stats.port_lem_cts[0] = bp->cmd_rsp_virt->cntrs_get.cntrs.link_errors[0].ls; bp->stats.port_lem_cts[1] = bp->cmd_rsp_virt->cntrs_get.cntrs.link_errors[1].ls; return (struct net_device_stats *)&bp->stats; } /* * ============================== * = dfx_ctl_set_multicast_list = * ============================== * * Overview: * Enable/Disable LLC frame promiscuous mode reception * on the adapter and/or update multicast address table. * * Returns: * None * * Arguments: * dev - pointer to device information * * Functional Description: * This routine follows a fairly simple algorithm for setting the * adapter filters and CAM: * * if IFF_PROMISC flag is set * enable LLC individual/group promiscuous mode * else * disable LLC individual/group promiscuous mode * if number of incoming multicast addresses > * (CAM max size - number of unicast addresses in CAM) * enable LLC group promiscuous mode * set driver-maintained multicast address count to zero * else * disable LLC group promiscuous mode * set driver-maintained multicast address count to incoming count * update adapter CAM * update adapter filters * * Return Codes: * None * * Assumptions: * Multicast addresses are presented in canonical (LSB) format. * * Side Effects: * On-board adapter CAM and filters are updated. */ static void dfx_ctl_set_multicast_list(struct net_device *dev) { DFX_board_t *bp = netdev_priv(dev); int i; /* used as index in for loop */ struct netdev_hw_addr *ha; /* Enable LLC frame promiscuous mode, if necessary */ if (dev->flags & IFF_PROMISC) bp->ind_group_prom = PI_FSTATE_K_PASS; /* Enable LLC ind/group prom mode */ /* Else, update multicast address table */ else { bp->ind_group_prom = PI_FSTATE_K_BLOCK; /* Disable LLC ind/group prom mode */ /* * Check whether incoming multicast address count exceeds table size * * Note: The adapters utilize an on-board 64 entry CAM for * supporting perfect filtering of multicast packets * and bridge functions when adding unicast addresses. * There is no hash function available. To support * additional multicast addresses, the all multicast * filter (LLC group promiscuous mode) must be enabled. * * The firmware reserves two CAM entries for SMT-related * multicast addresses, which leaves 62 entries available. * The following code ensures that we're not being asked * to add more than 62 addresses to the CAM. If we are, * the driver will enable the all multicast filter. * Should the number of multicast addresses drop below * the high water mark, the filter will be disabled and * perfect filtering will be used. */ if (netdev_mc_count(dev) > (PI_CMD_ADDR_FILTER_K_SIZE - bp->uc_count)) { bp->group_prom = PI_FSTATE_K_PASS; /* Enable LLC group prom mode */ bp->mc_count = 0; /* Don't add mc addrs to CAM */ } else { bp->group_prom = PI_FSTATE_K_BLOCK; /* Disable LLC group prom mode */ bp->mc_count = netdev_mc_count(dev); /* Add mc addrs to CAM */ } /* Copy addresses to multicast address table, then update adapter CAM */ i = 0; netdev_for_each_mc_addr(ha, dev) memcpy(&bp->mc_table[i++ * FDDI_K_ALEN], ha->addr, FDDI_K_ALEN); if (dfx_ctl_update_cam(bp) != DFX_K_SUCCESS) { DBG_printk("%s: Could not update multicast address table!\n", dev->name); } else { DBG_printk("%s: Multicast address table updated! Added %d addresses.\n", dev->name, bp->mc_count); } } /* Update adapter filters */ if (dfx_ctl_update_filters(bp) != DFX_K_SUCCESS) { DBG_printk("%s: Could not update adapter filters!\n", dev->name); } else { DBG_printk("%s: Adapter filters updated!\n", dev->name); } } /* * =========================== * = dfx_ctl_set_mac_address = * =========================== * * Overview: * Add node address override (unicast address) to adapter * CAM and update dev_addr field in device table. * * Returns: * None * * Arguments: * dev - pointer to device information * addr - pointer to sockaddr structure containing unicast address to add * * Functional Description: * The adapter supports node address overrides by adding one or more * unicast addresses to the adapter CAM. This is similar to adding * multicast addresses. In this routine we'll update the driver and * device structures with the new address, then update the adapter CAM * to ensure that the adapter will copy and strip frames destined and * sourced by that address. * * Return Codes: * Always returns zero. * * Assumptions: * The address pointed to by addr->sa_data is a valid unicast * address and is presented in canonical (LSB) format. * * Side Effects: * On-board adapter CAM is updated. On-board adapter filters * may be updated. */ static int dfx_ctl_set_mac_address(struct net_device *dev, void *addr) { struct sockaddr *p_sockaddr = (struct sockaddr *)addr; DFX_board_t *bp = netdev_priv(dev); /* Copy unicast address to driver-maintained structs and update count */ memcpy(dev->dev_addr, p_sockaddr->sa_data, FDDI_K_ALEN); /* update device struct */ memcpy(&bp->uc_table[0], p_sockaddr->sa_data, FDDI_K_ALEN); /* update driver struct */ bp->uc_count = 1; /* * Verify we're not exceeding the CAM size by adding unicast address * * Note: It's possible that before entering this routine we've * already filled the CAM with 62 multicast addresses. * Since we need to place the node address override into * the CAM, we have to check to see that we're not * exceeding the CAM size. If we are, we have to enable * the LLC group (multicast) promiscuous mode filter as * in dfx_ctl_set_multicast_list. */ if ((bp->uc_count + bp->mc_count) > PI_CMD_ADDR_FILTER_K_SIZE) { bp->group_prom = PI_FSTATE_K_PASS; /* Enable LLC group prom mode */ bp->mc_count = 0; /* Don't add mc addrs to CAM */ /* Update adapter filters */ if (dfx_ctl_update_filters(bp) != DFX_K_SUCCESS) { DBG_printk("%s: Could not update adapter filters!\n", dev->name); } else { DBG_printk("%s: Adapter filters updated!\n", dev->name); } } /* Update adapter CAM with new unicast address */ if (dfx_ctl_update_cam(bp) != DFX_K_SUCCESS) { DBG_printk("%s: Could not set new MAC address!\n", dev->name); } else { DBG_printk("%s: Adapter CAM updated with new MAC address\n", dev->name); } return 0; /* always return zero */ } /* * ====================== * = dfx_ctl_update_cam = * ====================== * * Overview: * Procedure to update adapter CAM (Content Addressable Memory) * with desired unicast and multicast address entries. * * Returns: * Condition code * * Arguments: * bp - pointer to board information * * Functional Description: * Updates adapter CAM with current contents of board structure * unicast and multicast address tables. Since there are only 62 * free entries in CAM, this routine ensures that the command * request buffer is not overrun. * * Return Codes: * DFX_K_SUCCESS - Request succeeded * DFX_K_FAILURE - Request failed * * Assumptions: * All addresses being added (unicast and multicast) are in canonical * order. * * Side Effects: * On-board adapter CAM is updated. */ static int dfx_ctl_update_cam(DFX_board_t *bp) { int i; /* used as index */ PI_LAN_ADDR *p_addr; /* pointer to CAM entry */ /* * Fill in command request information * * Note: Even though both the unicast and multicast address * table entries are stored as contiguous 6 byte entries, * the firmware address filter set command expects each * entry to be two longwords (8 bytes total). We must be * careful to only copy the six bytes of each unicast and * multicast table entry into each command entry. This * is also why we must first clear the entire command * request buffer. */ memset(bp->cmd_req_virt, 0, PI_CMD_REQ_K_SIZE_MAX); /* first clear buffer */ bp->cmd_req_virt->cmd_type = PI_CMD_K_ADDR_FILTER_SET; p_addr = &bp->cmd_req_virt->addr_filter_set.entry[0]; /* Now add unicast addresses to command request buffer, if any */ for (i=0; i < (int)bp->uc_count; i++) { if (i < PI_CMD_ADDR_FILTER_K_SIZE) { memcpy(p_addr, &bp->uc_table[i*FDDI_K_ALEN], FDDI_K_ALEN); p_addr++; /* point to next command entry */ } } /* Now add multicast addresses to command request buffer, if any */ for (i=0; i < (int)bp->mc_count; i++) { if ((i + bp->uc_count) < PI_CMD_ADDR_FILTER_K_SIZE) { memcpy(p_addr, &bp->mc_table[i*FDDI_K_ALEN], FDDI_K_ALEN); p_addr++; /* point to next command entry */ } } /* Issue command to update adapter CAM, then return */ if (dfx_hw_dma_cmd_req(bp) != DFX_K_SUCCESS) return DFX_K_FAILURE; return DFX_K_SUCCESS; } /* * ========================== * = dfx_ctl_update_filters = * ========================== * * Overview: * Procedure to update adapter filters with desired * filter settings. * * Returns: * Condition code * * Arguments: * bp - pointer to board information * * Functional Description: * Enables or disables filter using current filter settings. * * Return Codes: * DFX_K_SUCCESS - Request succeeded. * DFX_K_FAILURE - Request failed. * * Assumptions: * We must always pass up packets destined to the broadcast * address (FF-FF-FF-FF-FF-FF), so we'll always keep the * broadcast filter enabled. * * Side Effects: * On-board adapter filters are updated. */ static int dfx_ctl_update_filters(DFX_board_t *bp) { int i = 0; /* used as index */ /* Fill in command request information */ bp->cmd_req_virt->cmd_type = PI_CMD_K_FILTERS_SET; /* Initialize Broadcast filter - * ALWAYS ENABLED * */ bp->cmd_req_virt->filter_set.item[i].item_code = PI_ITEM_K_BROADCAST; bp->cmd_req_virt->filter_set.item[i++].value = PI_FSTATE_K_PASS; /* Initialize LLC Individual/Group Promiscuous filter */ bp->cmd_req_virt->filter_set.item[i].item_code = PI_ITEM_K_IND_GROUP_PROM; bp->cmd_req_virt->filter_set.item[i++].value = bp->ind_group_prom; /* Initialize LLC Group Promiscuous filter */ bp->cmd_req_virt->filter_set.item[i].item_code = PI_ITEM_K_GROUP_PROM; bp->cmd_req_virt->filter_set.item[i++].value = bp->group_prom; /* Terminate the item code list */ bp->cmd_req_virt->filter_set.item[i].item_code = PI_ITEM_K_EOL; /* Issue command to update adapter filters, then return */ if (dfx_hw_dma_cmd_req(bp) != DFX_K_SUCCESS) return DFX_K_FAILURE; return DFX_K_SUCCESS; } /* * ====================== * = dfx_hw_dma_cmd_req = * ====================== * * Overview: * Sends PDQ DMA command to adapter firmware * * Returns: * Condition code * * Arguments: * bp - pointer to board information * * Functional Description: * The command request and response buffers are posted to the adapter in the manner * described in the PDQ Port Specification: * * 1. Command Response Buffer is posted to adapter. * 2. Command Request Buffer is posted to adapter. * 3. Command Request consumer index is polled until it indicates that request * buffer has been DMA'd to adapter. * 4. Command Response consumer index is polled until it indicates that response * buffer has been DMA'd from adapter. * * This ordering ensures that a response buffer is already available for the firmware * to use once it's done processing the request buffer. * * Return Codes: * DFX_K_SUCCESS - DMA command succeeded * DFX_K_OUTSTATE - Adapter is NOT in proper state * DFX_K_HW_TIMEOUT - DMA command timed out * * Assumptions: * Command request buffer has already been filled with desired DMA command. * * Side Effects: * None */ static int dfx_hw_dma_cmd_req(DFX_board_t *bp) { int status; /* adapter status */ int timeout_cnt; /* used in for loops */ /* Make sure the adapter is in a state that we can issue the DMA command in */ status = dfx_hw_adap_state_rd(bp); if ((status == PI_STATE_K_RESET) || (status == PI_STATE_K_HALTED) || (status == PI_STATE_K_DMA_UNAVAIL) || (status == PI_STATE_K_UPGRADE)) return DFX_K_OUTSTATE; /* Put response buffer on the command response queue */ bp->descr_block_virt->cmd_rsp[bp->cmd_rsp_reg.index.prod].long_0 = (u32) (PI_RCV_DESCR_M_SOP | ((PI_CMD_RSP_K_SIZE_MAX / PI_ALIGN_K_CMD_RSP_BUFF) << PI_RCV_DESCR_V_SEG_LEN)); bp->descr_block_virt->cmd_rsp[bp->cmd_rsp_reg.index.prod].long_1 = bp->cmd_rsp_phys; /* Bump (and wrap) the producer index and write out to register */ bp->cmd_rsp_reg.index.prod += 1; bp->cmd_rsp_reg.index.prod &= PI_CMD_RSP_K_NUM_ENTRIES-1; dfx_port_write_long(bp, PI_PDQ_K_REG_CMD_RSP_PROD, bp->cmd_rsp_reg.lword); /* Put request buffer on the command request queue */ bp->descr_block_virt->cmd_req[bp->cmd_req_reg.index.prod].long_0 = (u32) (PI_XMT_DESCR_M_SOP | PI_XMT_DESCR_M_EOP | (PI_CMD_REQ_K_SIZE_MAX << PI_XMT_DESCR_V_SEG_LEN)); bp->descr_block_virt->cmd_req[bp->cmd_req_reg.index.prod].long_1 = bp->cmd_req_phys; /* Bump (and wrap) the producer index and write out to register */ bp->cmd_req_reg.index.prod += 1; bp->cmd_req_reg.index.prod &= PI_CMD_REQ_K_NUM_ENTRIES-1; dfx_port_write_long(bp, PI_PDQ_K_REG_CMD_REQ_PROD, bp->cmd_req_reg.lword); /* * Here we wait for the command request consumer index to be equal * to the producer, indicating that the adapter has DMAed the request. */ for (timeout_cnt = 20000; timeout_cnt > 0; timeout_cnt--) { if (bp->cmd_req_reg.index.prod == (u8)(bp->cons_block_virt->cmd_req)) break; udelay(100); /* wait for 100 microseconds */ } if (timeout_cnt == 0) return DFX_K_HW_TIMEOUT; /* Bump (and wrap) the completion index and write out to register */ bp->cmd_req_reg.index.comp += 1; bp->cmd_req_reg.index.comp &= PI_CMD_REQ_K_NUM_ENTRIES-1; dfx_port_write_long(bp, PI_PDQ_K_REG_CMD_REQ_PROD, bp->cmd_req_reg.lword); /* * Here we wait for the command response consumer index to be equal * to the producer, indicating that the adapter has DMAed the response. */ for (timeout_cnt = 20000; timeout_cnt > 0; timeout_cnt--) { if (bp->cmd_rsp_reg.index.prod == (u8)(bp->cons_block_virt->cmd_rsp)) break; udelay(100); /* wait for 100 microseconds */ } if (timeout_cnt == 0) return DFX_K_HW_TIMEOUT; /* Bump (and wrap) the completion index and write out to register */ bp->cmd_rsp_reg.index.comp += 1; bp->cmd_rsp_reg.index.comp &= PI_CMD_RSP_K_NUM_ENTRIES-1; dfx_port_write_long(bp, PI_PDQ_K_REG_CMD_RSP_PROD, bp->cmd_rsp_reg.lword); return DFX_K_SUCCESS; } /* * ======================== * = dfx_hw_port_ctrl_req = * ======================== * * Overview: * Sends PDQ port control command to adapter firmware * * Returns: * Host data register value in host_data if ptr is not NULL * * Arguments: * bp - pointer to board information * command - port control command * data_a - port data A register value * data_b - port data B register value * host_data - ptr to host data register value * * Functional Description: * Send generic port control command to adapter by writing * to various PDQ port registers, then polling for completion. * * Return Codes: * DFX_K_SUCCESS - port control command succeeded * DFX_K_HW_TIMEOUT - port control command timed out * * Assumptions: * None * * Side Effects: * None */ static int dfx_hw_port_ctrl_req( DFX_board_t *bp, PI_UINT32 command, PI_UINT32 data_a, PI_UINT32 data_b, PI_UINT32 *host_data ) { PI_UINT32 port_cmd; /* Port Control command register value */ int timeout_cnt; /* used in for loops */ /* Set Command Error bit in command longword */ port_cmd = (PI_UINT32) (command | PI_PCTRL_M_CMD_ERROR); /* Issue port command to the adapter */ dfx_port_write_long(bp, PI_PDQ_K_REG_PORT_DATA_A, data_a); dfx_port_write_long(bp, PI_PDQ_K_REG_PORT_DATA_B, data_b); dfx_port_write_long(bp, PI_PDQ_K_REG_PORT_CTRL, port_cmd); /* Now wait for command to complete */ if (command == PI_PCTRL_M_BLAST_FLASH) timeout_cnt = 600000; /* set command timeout count to 60 seconds */ else timeout_cnt = 20000; /* set command timeout count to 2 seconds */ for (; timeout_cnt > 0; timeout_cnt--) { dfx_port_read_long(bp, PI_PDQ_K_REG_PORT_CTRL, &port_cmd); if (!(port_cmd & PI_PCTRL_M_CMD_ERROR)) break; udelay(100); /* wait for 100 microseconds */ } if (timeout_cnt == 0) return DFX_K_HW_TIMEOUT; /* * If the address of host_data is non-zero, assume caller has supplied a * non NULL pointer, and return the contents of the HOST_DATA register in * it. */ if (host_data != NULL) dfx_port_read_long(bp, PI_PDQ_K_REG_HOST_DATA, host_data); return DFX_K_SUCCESS; } /* * ===================== * = dfx_hw_adap_reset = * ===================== * * Overview: * Resets adapter * * Returns: * None * * Arguments: * bp - pointer to board information * type - type of reset to perform * * Functional Description: * Issue soft reset to adapter by writing to PDQ Port Reset * register. Use incoming reset type to tell adapter what * kind of reset operation to perform. * * Return Codes: * None * * Assumptions: * This routine merely issues a soft reset to the adapter. * It is expected that after this routine returns, the caller * will appropriately poll the Port Status register for the * adapter to enter the proper state. * * Side Effects: * Internal adapter registers are cleared. */ static void dfx_hw_adap_reset( DFX_board_t *bp, PI_UINT32 type ) { /* Set Reset type and assert reset */ dfx_port_write_long(bp, PI_PDQ_K_REG_PORT_DATA_A, type); /* tell adapter type of reset */ dfx_port_write_long(bp, PI_PDQ_K_REG_PORT_RESET, PI_RESET_M_ASSERT_RESET); /* Wait for at least 1 Microsecond according to the spec. We wait 20 just to be safe */ udelay(20); /* Deassert reset */ dfx_port_write_long(bp, PI_PDQ_K_REG_PORT_RESET, 0); } /* * ======================== * = dfx_hw_adap_state_rd = * ======================== * * Overview: * Returns current adapter state * * Returns: * Adapter state per PDQ Port Specification * * Arguments: * bp - pointer to board information * * Functional Description: * Reads PDQ Port Status register and returns adapter state. * * Return Codes: * None * * Assumptions: * None * * Side Effects: * None */ static int dfx_hw_adap_state_rd(DFX_board_t *bp) { PI_UINT32 port_status; /* Port Status register value */ dfx_port_read_long(bp, PI_PDQ_K_REG_PORT_STATUS, &port_status); return (port_status & PI_PSTATUS_M_STATE) >> PI_PSTATUS_V_STATE; } /* * ===================== * = dfx_hw_dma_uninit = * ===================== * * Overview: * Brings adapter to DMA_UNAVAILABLE state * * Returns: * Condition code * * Arguments: * bp - pointer to board information * type - type of reset to perform * * Functional Description: * Bring adapter to DMA_UNAVAILABLE state by performing the following: * 1. Set reset type bit in Port Data A Register then reset adapter. * 2. Check that adapter is in DMA_UNAVAILABLE state. * * Return Codes: * DFX_K_SUCCESS - adapter is in DMA_UNAVAILABLE state * DFX_K_HW_TIMEOUT - adapter did not reset properly * * Assumptions: * None * * Side Effects: * Internal adapter registers are cleared. */ static int dfx_hw_dma_uninit(DFX_board_t *bp, PI_UINT32 type) { int timeout_cnt; /* used in for loops */ /* Set reset type bit and reset adapter */ dfx_hw_adap_reset(bp, type); /* Now wait for adapter to enter DMA_UNAVAILABLE state */ for (timeout_cnt = 100000; timeout_cnt > 0; timeout_cnt--) { if (dfx_hw_adap_state_rd(bp) == PI_STATE_K_DMA_UNAVAIL) break; udelay(100); /* wait for 100 microseconds */ } if (timeout_cnt == 0) return DFX_K_HW_TIMEOUT; return DFX_K_SUCCESS; } /* * Align an sk_buff to a boundary power of 2 * */ #ifdef DYNAMIC_BUFFERS static void my_skb_align(struct sk_buff *skb, int n) { unsigned long x = (unsigned long)skb->data; unsigned long v; v = ALIGN(x, n); /* Where we want to be */ skb_reserve(skb, v - x); } #endif /* * ================ * = dfx_rcv_init = * ================ * * Overview: * Produces buffers to adapter LLC Host receive descriptor block * * Returns: * None * * Arguments: * bp - pointer to board information * get_buffers - non-zero if buffers to be allocated * * Functional Description: * This routine can be called during dfx_adap_init() or during an adapter * reset. It initializes the descriptor block and produces all allocated * LLC Host queue receive buffers. * * Return Codes: * Return 0 on success or -ENOMEM if buffer allocation failed (when using * dynamic buffer allocation). If the buffer allocation failed, the * already allocated buffers will not be released and the caller should do * this. * * Assumptions: * The PDQ has been reset and the adapter and driver maintained Type 2 * register indices are cleared. * * Side Effects: * Receive buffers are posted to the adapter LLC queue and the adapter * is notified. */ static int dfx_rcv_init(DFX_board_t *bp, int get_buffers) { int i, j; /* used in for loop */ /* * Since each receive buffer is a single fragment of same length, initialize * first longword in each receive descriptor for entire LLC Host descriptor * block. Also initialize second longword in each receive descriptor with * physical address of receive buffer. We'll always allocate receive * buffers in powers of 2 so that we can easily fill the 256 entry descriptor * block and produce new receive buffers by simply updating the receive * producer index. * * Assumptions: * To support all shipping versions of PDQ, the receive buffer size * must be mod 128 in length and the physical address must be 128 byte * aligned. In other words, bits 0-6 of the length and address must * be zero for the following descriptor field entries to be correct on * all PDQ-based boards. We guaranteed both requirements during * driver initialization when we allocated memory for the receive buffers. */ if (get_buffers) { #ifdef DYNAMIC_BUFFERS for (i = 0; i < (int)(bp->rcv_bufs_to_post); i++) for (j = 0; (i + j) < (int)PI_RCV_DATA_K_NUM_ENTRIES; j += bp->rcv_bufs_to_post) { struct sk_buff *newskb; dma_addr_t dma_addr; newskb = __netdev_alloc_skb(bp->dev, NEW_SKB_SIZE, GFP_NOIO); if (!newskb) return -ENOMEM; /* * align to 128 bytes for compatibility with * the old EISA boards. */ my_skb_align(newskb, 128); dma_addr = dma_map_single(bp->bus_dev, newskb->data, PI_RCV_DATA_K_SIZE_MAX, DMA_FROM_DEVICE); if (dma_mapping_error(bp->bus_dev, dma_addr)) { dev_kfree_skb(newskb); return -ENOMEM; } bp->descr_block_virt->rcv_data[i + j].long_0 = (u32)(PI_RCV_DESCR_M_SOP | ((PI_RCV_DATA_K_SIZE_MAX / PI_ALIGN_K_RCV_DATA_BUFF) << PI_RCV_DESCR_V_SEG_LEN)); bp->descr_block_virt->rcv_data[i + j].long_1 = (u32)dma_addr; /* * p_rcv_buff_va is only used inside the * kernel so we put the skb pointer here. */ bp->p_rcv_buff_va[i+j] = (char *) newskb; } #else for (i=0; i < (int)(bp->rcv_bufs_to_post); i++) for (j=0; (i + j) < (int)PI_RCV_DATA_K_NUM_ENTRIES; j += bp->rcv_bufs_to_post) { bp->descr_block_virt->rcv_data[i+j].long_0 = (u32) (PI_RCV_DESCR_M_SOP | ((PI_RCV_DATA_K_SIZE_MAX / PI_ALIGN_K_RCV_DATA_BUFF) << PI_RCV_DESCR_V_SEG_LEN)); bp->descr_block_virt->rcv_data[i+j].long_1 = (u32) (bp->rcv_block_phys + (i * PI_RCV_DATA_K_SIZE_MAX)); bp->p_rcv_buff_va[i+j] = (bp->rcv_block_virt + (i * PI_RCV_DATA_K_SIZE_MAX)); } #endif } /* Update receive producer and Type 2 register */ bp->rcv_xmt_reg.index.rcv_prod = bp->rcv_bufs_to_post; dfx_port_write_long(bp, PI_PDQ_K_REG_TYPE_2_PROD, bp->rcv_xmt_reg.lword); return 0; } /* * ========================= * = dfx_rcv_queue_process = * ========================= * * Overview: * Process received LLC frames. * * Returns: * None * * Arguments: * bp - pointer to board information * * Functional Description: * Received LLC frames are processed until there are no more consumed frames. * Once all frames are processed, the receive buffers are returned to the * adapter. Note that this algorithm fixes the length of time that can be spent * in this routine, because there are a fixed number of receive buffers to * process and buffers are not produced until this routine exits and returns * to the ISR. * * Return Codes: * None * * Assumptions: * None * * Side Effects: * None */ static void dfx_rcv_queue_process( DFX_board_t *bp ) { PI_TYPE_2_CONSUMER *p_type_2_cons; /* ptr to rcv/xmt consumer block register */ char *p_buff; /* ptr to start of packet receive buffer (FMC descriptor) */ u32 descr, pkt_len; /* FMC descriptor field and packet length */ struct sk_buff *skb = NULL; /* pointer to a sk_buff to hold incoming packet data */ /* Service all consumed LLC receive frames */ p_type_2_cons = (PI_TYPE_2_CONSUMER *)(&bp->cons_block_virt->xmt_rcv_data); while (bp->rcv_xmt_reg.index.rcv_comp != p_type_2_cons->index.rcv_cons) { /* Process any errors */ dma_addr_t dma_addr; int entry; entry = bp->rcv_xmt_reg.index.rcv_comp; #ifdef DYNAMIC_BUFFERS p_buff = (char *) (((struct sk_buff *)bp->p_rcv_buff_va[entry])->data); #else p_buff = bp->p_rcv_buff_va[entry]; #endif dma_addr = bp->descr_block_virt->rcv_data[entry].long_1; dma_sync_single_for_cpu(bp->bus_dev, dma_addr + RCV_BUFF_K_DESCR, sizeof(u32), DMA_FROM_DEVICE); memcpy(&descr, p_buff + RCV_BUFF_K_DESCR, sizeof(u32)); if (descr & PI_FMC_DESCR_M_RCC_FLUSH) { if (descr & PI_FMC_DESCR_M_RCC_CRC) bp->rcv_crc_errors++; else bp->rcv_frame_status_errors++; } else { int rx_in_place = 0; /* The frame was received without errors - verify packet length */ pkt_len = (u32)((descr & PI_FMC_DESCR_M_LEN) >> PI_FMC_DESCR_V_LEN); pkt_len -= 4; /* subtract 4 byte CRC */ if (!IN_RANGE(pkt_len, FDDI_K_LLC_ZLEN, FDDI_K_LLC_LEN)) bp->rcv_length_errors++; else{ #ifdef DYNAMIC_BUFFERS struct sk_buff *newskb = NULL; if (pkt_len > SKBUFF_RX_COPYBREAK) { dma_addr_t new_dma_addr; newskb = netdev_alloc_skb(bp->dev, NEW_SKB_SIZE); if (newskb){ my_skb_align(newskb, 128); new_dma_addr = dma_map_single( bp->bus_dev, newskb->data, PI_RCV_DATA_K_SIZE_MAX, DMA_FROM_DEVICE); if (dma_mapping_error( bp->bus_dev, new_dma_addr)) { dev_kfree_skb(newskb); newskb = NULL; } } if (newskb) { rx_in_place = 1; skb = (struct sk_buff *)bp->p_rcv_buff_va[entry]; dma_unmap_single(bp->bus_dev, dma_addr, PI_RCV_DATA_K_SIZE_MAX, DMA_FROM_DEVICE); skb_reserve(skb, RCV_BUFF_K_PADDING); bp->p_rcv_buff_va[entry] = (char *)newskb; bp->descr_block_virt->rcv_data[entry].long_1 = (u32)new_dma_addr; } } if (!newskb) #endif /* Alloc new buffer to pass up, * add room for PRH. */ skb = netdev_alloc_skb(bp->dev, pkt_len + 3); if (skb == NULL) { printk("%s: Could not allocate receive buffer. Dropping packet.\n", bp->dev->name); bp->rcv_discards++; break; } else { if (!rx_in_place) { /* Receive buffer allocated, pass receive packet up */ dma_sync_single_for_cpu( bp->bus_dev, dma_addr + RCV_BUFF_K_PADDING, pkt_len + 3, DMA_FROM_DEVICE); skb_copy_to_linear_data(skb, p_buff + RCV_BUFF_K_PADDING, pkt_len + 3); } skb_reserve(skb,3); /* adjust data field so that it points to FC byte */ skb_put(skb, pkt_len); /* pass up packet length, NOT including CRC */ skb->protocol = fddi_type_trans(skb, bp->dev); bp->rcv_total_bytes += skb->len; netif_rx(skb); /* Update the rcv counters */ bp->rcv_total_frames++; if (*(p_buff + RCV_BUFF_K_DA) & 0x01) bp->rcv_multicast_frames++; } } } /* * Advance the producer (for recycling) and advance the completion * (for servicing received frames). Note that it is okay to * advance the producer without checking that it passes the * completion index because they are both advanced at the same * rate. */ bp->rcv_xmt_reg.index.rcv_prod += 1; bp->rcv_xmt_reg.index.rcv_comp += 1; } } /* * ===================== * = dfx_xmt_queue_pkt = * ===================== * * Overview: * Queues packets for transmission * * Returns: * Condition code * * Arguments: * skb - pointer to sk_buff to queue for transmission * dev - pointer to device information * * Functional Description: * Here we assume that an incoming skb transmit request * is contained in a single physically contiguous buffer * in which the virtual address of the start of packet * (skb->data) can be converted to a physical address * by using pci_map_single(). * * Since the adapter architecture requires a three byte * packet request header to prepend the start of packet, * we'll write the three byte field immediately prior to * the FC byte. This assumption is valid because we've * ensured that dev->hard_header_len includes three pad * bytes. By posting a single fragment to the adapter, * we'll reduce the number of descriptor fetches and * bus traffic needed to send the request. * * Also, we can't free the skb until after it's been DMA'd * out by the adapter, so we'll queue it in the driver and * return it in dfx_xmt_done. * * Return Codes: * 0 - driver queued packet, link is unavailable, or skbuff was bad * 1 - caller should requeue the sk_buff for later transmission * * Assumptions: * First and foremost, we assume the incoming skb pointer * is NOT NULL and is pointing to a valid sk_buff structure. * * The outgoing packet is complete, starting with the * frame control byte including the last byte of data, * but NOT including the 4 byte CRC. We'll let the * adapter hardware generate and append the CRC. * * The entire packet is stored in one physically * contiguous buffer which is not cached and whose * 32-bit physical address can be determined. * * It's vital that this routine is NOT reentered for the * same board and that the OS is not in another section of * code (eg. dfx_int_common) for the same board on a * different thread. * * Side Effects: * None */ static netdev_tx_t dfx_xmt_queue_pkt(struct sk_buff *skb, struct net_device *dev) { DFX_board_t *bp = netdev_priv(dev); u8 prod; /* local transmit producer index */ PI_XMT_DESCR *p_xmt_descr; /* ptr to transmit descriptor block entry */ XMT_DRIVER_DESCR *p_xmt_drv_descr; /* ptr to transmit driver descriptor */ dma_addr_t dma_addr; unsigned long flags; netif_stop_queue(dev); /* * Verify that incoming transmit request is OK * * Note: The packet size check is consistent with other * Linux device drivers, although the correct packet * size should be verified before calling the * transmit routine. */ if (!IN_RANGE(skb->len, FDDI_K_LLC_ZLEN, FDDI_K_LLC_LEN)) { printk("%s: Invalid packet length - %u bytes\n", dev->name, skb->len); bp->xmt_length_errors++; /* bump error counter */ netif_wake_queue(dev); dev_kfree_skb(skb); return NETDEV_TX_OK; /* return "success" */ } /* * See if adapter link is available, if not, free buffer * * Note: If the link isn't available, free buffer and return 0 * rather than tell the upper layer to requeue the packet. * The methodology here is that by the time the link * becomes available, the packet to be sent will be * fairly stale. By simply dropping the packet, the * higher layer protocols will eventually time out * waiting for response packets which it won't receive. */ if (bp->link_available == PI_K_FALSE) { if (dfx_hw_adap_state_rd(bp) == PI_STATE_K_LINK_AVAIL) /* is link really available? */ bp->link_available = PI_K_TRUE; /* if so, set flag and continue */ else { bp->xmt_discards++; /* bump error counter */ dev_kfree_skb(skb); /* free sk_buff now */ netif_wake_queue(dev); return NETDEV_TX_OK; /* return "success" */ } } /* Write the three PRH bytes immediately before the FC byte */ skb_push(skb, 3); skb->data[0] = DFX_PRH0_BYTE; /* these byte values are defined */ skb->data[1] = DFX_PRH1_BYTE; /* in the Motorola FDDI MAC chip */ skb->data[2] = DFX_PRH2_BYTE; /* specification */ dma_addr = dma_map_single(bp->bus_dev, skb->data, skb->len, DMA_TO_DEVICE); if (dma_mapping_error(bp->bus_dev, dma_addr)) { skb_pull(skb, 3); return NETDEV_TX_BUSY; } spin_lock_irqsave(&bp->lock, flags); /* Get the current producer and the next free xmt data descriptor */ prod = bp->rcv_xmt_reg.index.xmt_prod; p_xmt_descr = &(bp->descr_block_virt->xmt_data[prod]); /* * Get pointer to auxiliary queue entry to contain information * for this packet. * * Note: The current xmt producer index will become the * current xmt completion index when we complete this * packet later on. So, we'll get the pointer to the * next auxiliary queue entry now before we bump the * producer index. */ p_xmt_drv_descr = &(bp->xmt_drv_descr_blk[prod++]); /* also bump producer index */ /* * Write the descriptor with buffer info and bump producer * * Note: Since we need to start DMA from the packet request * header, we'll add 3 bytes to the DMA buffer length, * and we'll determine the physical address of the * buffer from the PRH, not skb->data. * * Assumptions: * 1. Packet starts with the frame control (FC) byte * at skb->data. * 2. The 4-byte CRC is not appended to the buffer or * included in the length. * 3. Packet length (skb->len) is from FC to end of * data, inclusive. * 4. The packet length does not exceed the maximum * FDDI LLC frame length of 4491 bytes. * 5. The entire packet is contained in a physically * contiguous, non-cached, locked memory space * comprised of a single buffer pointed to by * skb->data. * 6. The physical address of the start of packet * can be determined from the virtual address * by using pci_map_single() and is only 32-bits * wide. */ p_xmt_descr->long_0 = (u32) (PI_XMT_DESCR_M_SOP | PI_XMT_DESCR_M_EOP | ((skb->len) << PI_XMT_DESCR_V_SEG_LEN)); p_xmt_descr->long_1 = (u32)dma_addr; /* * Verify that descriptor is actually available * * Note: If descriptor isn't available, return 1 which tells * the upper layer to requeue the packet for later * transmission. * * We need to ensure that the producer never reaches the * completion, except to indicate that the queue is empty. */ if (prod == bp->rcv_xmt_reg.index.xmt_comp) { skb_pull(skb,3); spin_unlock_irqrestore(&bp->lock, flags); return NETDEV_TX_BUSY; /* requeue packet for later */ } /* * Save info for this packet for xmt done indication routine * * Normally, we'd save the producer index in the p_xmt_drv_descr * structure so that we'd have it handy when we complete this * packet later (in dfx_xmt_done). However, since the current * transmit architecture guarantees a single fragment for the * entire packet, we can simply bump the completion index by * one (1) for each completed packet. * * Note: If this assumption changes and we're presented with * an inconsistent number of transmit fragments for packet * data, we'll need to modify this code to save the current * transmit producer index. */ p_xmt_drv_descr->p_skb = skb; /* Update Type 2 register */ bp->rcv_xmt_reg.index.xmt_prod = prod; dfx_port_write_long(bp, PI_PDQ_K_REG_TYPE_2_PROD, bp->rcv_xmt_reg.lword); spin_unlock_irqrestore(&bp->lock, flags); netif_wake_queue(dev); return NETDEV_TX_OK; /* packet queued to adapter */ } /* * ================ * = dfx_xmt_done = * ================ * * Overview: * Processes all frames that have been transmitted. * * Returns: * None * * Arguments: * bp - pointer to board information * * Functional Description: * For all consumed transmit descriptors that have not * yet been completed, we'll free the skb we were holding * onto using dev_kfree_skb and bump the appropriate * counters. * * Return Codes: * None * * Assumptions: * The Type 2 register is not updated in this routine. It is * assumed that it will be updated in the ISR when dfx_xmt_done * returns. * * Side Effects: * None */ static int dfx_xmt_done(DFX_board_t *bp) { XMT_DRIVER_DESCR *p_xmt_drv_descr; /* ptr to transmit driver descriptor */ PI_TYPE_2_CONSUMER *p_type_2_cons; /* ptr to rcv/xmt consumer block register */ u8 comp; /* local transmit completion index */ int freed = 0; /* buffers freed */ /* Service all consumed transmit frames */ p_type_2_cons = (PI_TYPE_2_CONSUMER *)(&bp->cons_block_virt->xmt_rcv_data); while (bp->rcv_xmt_reg.index.xmt_comp != p_type_2_cons->index.xmt_cons) { /* Get pointer to the transmit driver descriptor block information */ p_xmt_drv_descr = &(bp->xmt_drv_descr_blk[bp->rcv_xmt_reg.index.xmt_comp]); /* Increment transmit counters */ bp->xmt_total_frames++; bp->xmt_total_bytes += p_xmt_drv_descr->p_skb->len; /* Return skb to operating system */ comp = bp->rcv_xmt_reg.index.xmt_comp; dma_unmap_single(bp->bus_dev, bp->descr_block_virt->xmt_data[comp].long_1, p_xmt_drv_descr->p_skb->len, DMA_TO_DEVICE); dev_kfree_skb_irq(p_xmt_drv_descr->p_skb); /* * Move to start of next packet by updating completion index * * Here we assume that a transmit packet request is always * serviced by posting one fragment. We can therefore * simplify the completion code by incrementing the * completion index by one. This code will need to be * modified if this assumption changes. See comments * in dfx_xmt_queue_pkt for more details. */ bp->rcv_xmt_reg.index.xmt_comp += 1; freed++; } return freed; } /* * ================= * = dfx_rcv_flush = * ================= * * Overview: * Remove all skb's in the receive ring. * * Returns: * None * * Arguments: * bp - pointer to board information * * Functional Description: * Free's all the dynamically allocated skb's that are * currently attached to the device receive ring. This * function is typically only used when the device is * initialized or reinitialized. * * Return Codes: * None * * Side Effects: * None */ #ifdef DYNAMIC_BUFFERS static void dfx_rcv_flush( DFX_board_t *bp ) { int i, j; for (i = 0; i < (int)(bp->rcv_bufs_to_post); i++) for (j = 0; (i + j) < (int)PI_RCV_DATA_K_NUM_ENTRIES; j += bp->rcv_bufs_to_post) { struct sk_buff *skb; skb = (struct sk_buff *)bp->p_rcv_buff_va[i+j]; if (skb) { dma_unmap_single(bp->bus_dev, bp->descr_block_virt->rcv_data[i+j].long_1, PI_RCV_DATA_K_SIZE_MAX, DMA_FROM_DEVICE); dev_kfree_skb(skb); } bp->p_rcv_buff_va[i+j] = NULL; } } #endif /* DYNAMIC_BUFFERS */ /* * ================= * = dfx_xmt_flush = * ================= * * Overview: * Processes all frames whether they've been transmitted * or not. * * Returns: * None * * Arguments: * bp - pointer to board information * * Functional Description: * For all produced transmit descriptors that have not * yet been completed, we'll free the skb we were holding * onto using dev_kfree_skb and bump the appropriate * counters. Of course, it's possible that some of * these transmit requests actually did go out, but we * won't make that distinction here. Finally, we'll * update the consumer index to match the producer. * * Return Codes: * None * * Assumptions: * This routine does NOT update the Type 2 register. It * is assumed that this routine is being called during a * transmit flush interrupt, or a shutdown or close routine. * * Side Effects: * None */ static void dfx_xmt_flush( DFX_board_t *bp ) { u32 prod_cons; /* rcv/xmt consumer block longword */ XMT_DRIVER_DESCR *p_xmt_drv_descr; /* ptr to transmit driver descriptor */ u8 comp; /* local transmit completion index */ /* Flush all outstanding transmit frames */ while (bp->rcv_xmt_reg.index.xmt_comp != bp->rcv_xmt_reg.index.xmt_prod) { /* Get pointer to the transmit driver descriptor block information */ p_xmt_drv_descr = &(bp->xmt_drv_descr_blk[bp->rcv_xmt_reg.index.xmt_comp]); /* Return skb to operating system */ comp = bp->rcv_xmt_reg.index.xmt_comp; dma_unmap_single(bp->bus_dev, bp->descr_block_virt->xmt_data[comp].long_1, p_xmt_drv_descr->p_skb->len, DMA_TO_DEVICE); dev_kfree_skb(p_xmt_drv_descr->p_skb); /* Increment transmit error counter */ bp->xmt_discards++; /* * Move to start of next packet by updating completion index * * Here we assume that a transmit packet request is always * serviced by posting one fragment. We can therefore * simplify the completion code by incrementing the * completion index by one. This code will need to be * modified if this assumption changes. See comments * in dfx_xmt_queue_pkt for more details. */ bp->rcv_xmt_reg.index.xmt_comp += 1; } /* Update the transmit consumer index in the consumer block */ prod_cons = (u32)(bp->cons_block_virt->xmt_rcv_data & ~PI_CONS_M_XMT_INDEX); prod_cons |= (u32)(bp->rcv_xmt_reg.index.xmt_prod << PI_CONS_V_XMT_INDEX); bp->cons_block_virt->xmt_rcv_data = prod_cons; } /* * ================== * = dfx_unregister = * ================== * * Overview: * Shuts down an FDDI controller * * Returns: * Condition code * * Arguments: * bdev - pointer to device information * * Functional Description: * * Return Codes: * None * * Assumptions: * It compiles so it should work :-( (PCI cards do :-) * * Side Effects: * Device structures for FDDI adapters (fddi0, fddi1, etc) are * freed. */ static void dfx_unregister(struct device *bdev) { struct net_device *dev = dev_get_drvdata(bdev); DFX_board_t *bp = netdev_priv(dev); int dfx_bus_pci = dev_is_pci(bdev); int dfx_bus_tc = DFX_BUS_TC(bdev); int dfx_use_mmio = DFX_MMIO || dfx_bus_tc; resource_size_t bar_start[3]; /* pointers to ports */ resource_size_t bar_len[3]; /* resource lengths */ int alloc_size; /* total buffer size used */ unregister_netdev(dev); alloc_size = sizeof(PI_DESCR_BLOCK) + PI_CMD_REQ_K_SIZE_MAX + PI_CMD_RSP_K_SIZE_MAX + #ifndef DYNAMIC_BUFFERS (bp->rcv_bufs_to_post * PI_RCV_DATA_K_SIZE_MAX) + #endif sizeof(PI_CONSUMER_BLOCK) + (PI_ALIGN_K_DESC_BLK - 1); if (bp->kmalloced) dma_free_coherent(bdev, alloc_size, bp->kmalloced, bp->kmalloced_dma); dfx_bus_uninit(dev); dfx_get_bars(bdev, bar_start, bar_len); if (bar_start[2] != 0) release_region(bar_start[2], bar_len[2]); if (bar_start[1] != 0) release_region(bar_start[1], bar_len[1]); if (dfx_use_mmio) { iounmap(bp->base.mem); release_mem_region(bar_start[0], bar_len[0]); } else release_region(bar_start[0], bar_len[0]); if (dfx_bus_pci) pci_disable_device(to_pci_dev(bdev)); free_netdev(dev); } static int __maybe_unused dfx_dev_register(struct device *); static int __maybe_unused dfx_dev_unregister(struct device *); #ifdef CONFIG_PCI static int dfx_pci_register(struct pci_dev *, const struct pci_device_id *); static void dfx_pci_unregister(struct pci_dev *); static const struct pci_device_id dfx_pci_table[] = { { PCI_DEVICE(PCI_VENDOR_ID_DEC, PCI_DEVICE_ID_DEC_FDDI) }, { } }; MODULE_DEVICE_TABLE(pci, dfx_pci_table); static struct pci_driver dfx_pci_driver = { .name = "defxx", .id_table = dfx_pci_table, .probe = dfx_pci_register, .remove = dfx_pci_unregister, }; static int dfx_pci_register(struct pci_dev *pdev, const struct pci_device_id *ent) { return dfx_register(&pdev->dev); } static void dfx_pci_unregister(struct pci_dev *pdev) { dfx_unregister(&pdev->dev); } #endif /* CONFIG_PCI */ #ifdef CONFIG_EISA static struct eisa_device_id dfx_eisa_table[] = { { "DEC3001", DEFEA_PROD_ID_1 }, { "DEC3002", DEFEA_PROD_ID_2 }, { "DEC3003", DEFEA_PROD_ID_3 }, { "DEC3004", DEFEA_PROD_ID_4 }, { } }; MODULE_DEVICE_TABLE(eisa, dfx_eisa_table); static struct eisa_driver dfx_eisa_driver = { .id_table = dfx_eisa_table, .driver = { .name = "defxx", .bus = &eisa_bus_type, .probe = dfx_dev_register, .remove = dfx_dev_unregister, }, }; #endif /* CONFIG_EISA */ #ifdef CONFIG_TC static struct tc_device_id const dfx_tc_table[] = { { "DEC ", "PMAF-FA " }, { "DEC ", "PMAF-FD " }, { "DEC ", "PMAF-FS " }, { "DEC ", "PMAF-FU " }, { } }; MODULE_DEVICE_TABLE(tc, dfx_tc_table); static struct tc_driver dfx_tc_driver = { .id_table = dfx_tc_table, .driver = { .name = "defxx", .bus = &tc_bus_type, .probe = dfx_dev_register, .remove = dfx_dev_unregister, }, }; #endif /* CONFIG_TC */ static int __maybe_unused dfx_dev_register(struct device *dev) { int status; status = dfx_register(dev); if (!status) get_device(dev); return status; } static int __maybe_unused dfx_dev_unregister(struct device *dev) { put_device(dev); dfx_unregister(dev); return 0; } static int dfx_init(void) { int status; status = pci_register_driver(&dfx_pci_driver); if (!status) status = eisa_driver_register(&dfx_eisa_driver); if (!status) status = tc_register_driver(&dfx_tc_driver); return status; } static void dfx_cleanup(void) { tc_unregister_driver(&dfx_tc_driver); eisa_driver_unregister(&dfx_eisa_driver); pci_unregister_driver(&dfx_pci_driver); } module_init(dfx_init); module_exit(dfx_cleanup); MODULE_AUTHOR("Lawrence V. Stefani"); MODULE_DESCRIPTION("DEC FDDIcontroller TC/EISA/PCI (DEFTA/DEFEA/DEFPA) driver " DRV_VERSION " " DRV_RELDATE); MODULE_LICENSE("GPL");
30.860145
147
0.698903
[ "object", "vector", "model" ]
7f9b161c1d6ee417e58fdd2586da8801b3de9de4
2,309
h
C
ns-allinone-3.22/ns-3.22/src/mesh/model/mesh-wifi-beacon.h
gustavo978/helpful
59e3fd062cff4451c9bf8268df78a24f93ff67b7
[ "Unlicense" ]
null
null
null
ns-allinone-3.22/ns-3.22/src/mesh/model/mesh-wifi-beacon.h
gustavo978/helpful
59e3fd062cff4451c9bf8268df78a24f93ff67b7
[ "Unlicense" ]
null
null
null
ns-allinone-3.22/ns-3.22/src/mesh/model/mesh-wifi-beacon.h
gustavo978/helpful
59e3fd062cff4451c9bf8268df78a24f93ff67b7
[ "Unlicense" ]
2
2018-06-06T14:10:23.000Z
2020-04-07T17:20:55.000Z
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2009 IITP RAS * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Pavel Boyko <boyko@iitp.ru> */ #ifndef MESH_WIFI_BEACON_H #define MESH_WIFI_BEACON_H #include "ns3/object.h" #include "ns3/packet.h" #include "ns3/mgt-headers.h" // from wifi module #include "ns3/wifi-mac-header.h" #include "ns3/mesh-information-element-vector.h" namespace ns3 { /** * \brief Beacon is beacon header + list of arbitrary information elements * * It is supposed that distinct mesh protocols can use beacons to transport * their own information elements. */ class MeshWifiBeacon { public: /** * C-tor * * \param ssid is SSID for beacon header * \param rates is a set of supported rates * \param us beacon interval in microseconds */ MeshWifiBeacon (Ssid ssid, SupportedRates rates, uint64_t us); /// Read standard Wifi beacon header MgtBeaconHeader BeaconHeader () const { return m_header; } /// Add information element void AddInformationElement (Ptr<WifiInformationElement> ie); /** * Create wifi header for beacon frame. * * \param address is sender address * \param mpAddress is mesh point address */ WifiMacHeader CreateHeader (Mac48Address address, Mac48Address mpAddress); /// Returns a beacon interval of wifi beacon Time GetBeaconInterval () const; /// Create frame = { beacon header + all information elements sorted by ElementId () } Ptr<Packet> CreatePacket (); private: /// Beacon header MgtBeaconHeader m_header; /// List of information elements added WifiInformationElementVector m_elements; }; } #endif /* MESH_WIFI_BEACON_H */
30.381579
88
0.721958
[ "mesh", "object", "vector" ]
7f9cbd338fc56c10920dfdb8b07d230e0387e809
649
h
C
ScratchProject/pch.h
SuperNic333/XivAlexander
8b0371e5f8473014a8aa39a22f93579b7de13f4f
[ "Apache-2.0" ]
345
2021-02-08T18:11:24.000Z
2022-03-25T04:01:23.000Z
ScratchProject/pch.h
SuperNic333/XivAlexander
8b0371e5f8473014a8aa39a22f93579b7de13f4f
[ "Apache-2.0" ]
376
2021-02-12T07:23:57.000Z
2022-03-31T00:05:35.000Z
ScratchProject/pch.h
SuperNic333/XivAlexander
8b0371e5f8473014a8aa39a22f93579b7de13f4f
[ "Apache-2.0" ]
65
2021-02-12T05:47:14.000Z
2022-03-25T03:08:23.000Z
#pragma once #include <filesystem> #include <vector> #include <ranges> #include <span> #include <cstdio> #include <format> #include <iostream> #include <fstream> #include <numeric> #include <regex> #include <set> #define NOMINMAX #include <Windows.h> #include <cryptopp/sha.h> #include <zlib.h> #include <ogg/ogg.h> #include <vorbis/codec.h> #include <vorbis/vorbisenc.h> #include <srell.hpp> #include <ft2build.h> #include FT_FREETYPE_H #include FT_BITMAP_H #include FT_OUTLINE_H #include FT_GLYPH_H #include <mmreg.h> #include <comdef.h> #include <dwrite_3.h> #include <XivAlexanderCommon/XaFormat.h> #include <XivAlexanderCommon/XaMisc.h>
17.540541
40
0.747304
[ "vector" ]
7f9de17e006fea9b541bc05509dd1064f8352b3a
1,928
h
C
src/services/pcn-loadbalancer-rp/src/interface/ServiceInterface.h
francescomessina/polycube
38f2fb4ffa13cf51313b3cab9994be738ba367be
[ "ECL-2.0", "Apache-2.0" ]
337
2018-12-12T11:50:15.000Z
2022-03-15T00:24:35.000Z
src/services/pcn-loadbalancer-rp/src/interface/ServiceInterface.h
l1b0k/polycube
7af919245c131fa9fe24c5d39d10039cbb81e825
[ "ECL-2.0", "Apache-2.0" ]
253
2018-12-17T21:36:15.000Z
2022-01-17T09:30:42.000Z
src/services/pcn-loadbalancer-rp/src/interface/ServiceInterface.h
l1b0k/polycube
7af919245c131fa9fe24c5d39d10039cbb81e825
[ "ECL-2.0", "Apache-2.0" ]
90
2018-12-19T15:49:38.000Z
2022-03-27T03:56:07.000Z
/** * lbrp API * lbrp API generated from lbrp.yang * * OpenAPI spec version: 1.0.0 * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/polycube-network/swagger-codegen.git * branch polycube */ /* Do not edit this file manually */ /* * ServiceInterface.h * * */ #pragma once #include "../serializer/ServiceJsonObject.h" #include "../ServiceBackend.h" using namespace io::swagger::server::model; class ServiceInterface { public: virtual void update(const ServiceJsonObject &conf) = 0; virtual ServiceJsonObject toJsonObject() = 0; /// <summary> /// Service name related to the backend server of the pool is connected to /// </summary> virtual std::string getName() = 0; virtual void setName(const std::string &value) = 0; /// <summary> /// Virtual IP (vip) of the service where clients connect to /// </summary> virtual std::string getVip() = 0; /// <summary> /// Port of the virtual server where clients connect to (this value is ignored in case of ICMP) /// </summary> virtual uint16_t getVport() = 0; /// <summary> /// Upper-layer protocol associated with a loadbalancing service instance. &#39;ALL&#39; creates an entry for all the supported protocols /// </summary> virtual ServiceProtoEnum getProto() = 0; /// <summary> /// Pool of backend servers that actually serve requests /// </summary> virtual std::shared_ptr<ServiceBackend> getBackend(const std::string &ip) = 0; virtual std::vector<std::shared_ptr<ServiceBackend>> getBackendList() = 0; virtual void addBackend(const std::string &ip, const ServiceBackendJsonObject &conf) = 0; virtual void addBackendList(const std::vector<ServiceBackendJsonObject> &conf) = 0; virtual void replaceBackend(const std::string &ip, const ServiceBackendJsonObject &conf) = 0; virtual void delBackend(const std::string &ip) = 0; virtual void delBackendList() = 0; };
28.352941
139
0.707988
[ "vector", "model" ]
7f9e5ed55c1f2affcbcaaf0ef4b81f266e3a6983
385
h
C
CloneCraft/world/chunkData.h
goldos24/CloneCraft-Legacy
666bfd297ce0d00f28457d151a47ddf724d26488
[ "BSD-3-Clause" ]
null
null
null
CloneCraft/world/chunkData.h
goldos24/CloneCraft-Legacy
666bfd297ce0d00f28457d151a47ddf724d26488
[ "BSD-3-Clause" ]
null
null
null
CloneCraft/world/chunkData.h
goldos24/CloneCraft-Legacy
666bfd297ce0d00f28457d151a47ddf724d26488
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <cstdint> #include "../maths/maths.h" namespace chunks { const int size = 16; union chunkKey { chunkKey(); uint64_t num; maths::Vec3<uint16_t> vector; }; chunkKey createKeyFromPosition(maths::Vec3<int> chunkPos); maths::Vec3<int> convertToChunkPos(maths::Vec3<int> position); maths::Vec3<int> convertToChunkPos(maths::Vec3<float> position); }
16.041667
65
0.714286
[ "vector" ]
7fa4faa3e37e2b7db94c0605e109e89f6d180651
2,665
h
C
kern/inc/feral/kern/krnlfirmware.h
bSchnepp/Feral
8931c89da418076c15205f03e93b664504fb29ff
[ "BSL-1.0" ]
13
2018-04-27T00:04:09.000Z
2022-01-06T15:00:24.000Z
kern/inc/feral/kern/krnlfirmware.h
bSchnepp/Feral
8931c89da418076c15205f03e93b664504fb29ff
[ "BSL-1.0" ]
44
2018-09-01T04:05:21.000Z
2021-02-21T22:02:57.000Z
kern/inc/feral/kern/krnlfirmware.h
bSchnepp/feral-next
8931c89da418076c15205f03e93b664504fb29ff
[ "BSL-1.0" ]
2
2018-04-28T12:54:41.000Z
2021-03-17T14:18:28.000Z
/* Copyright (c) 2019, Brian Schnepp Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <feral/stdtypes.h> #ifndef _FERAL_KRNL_FIRMWARE_H_ #define _FERAL_KRNL_FIRMWARE_H_ /* Single character */ typedef VOID (*PutCharFunc)(CHAR); /* String, length */ typedef VOID (*PrintlnFunc)(STRING, UINT64); /* The name of the underlying firmware (EFI, BIOS, etc.) */ typedef STRING (*GetFirmwareNameFunc)(VOID); /* Implementation of backspace visually. * It simply needs to clear the previous cell, then decrement * the current index in the video buffer. */ typedef VOID (*BackspaceFunc)(VOID); /* String, length */ typedef UINT_PTR (*GetMaxPhysicalAddressFunc)(VOID); /* TODO: Remove */ typedef VOID *(*GetNativeFirmwareMemoryMapFunc)(VOID); typedef struct KrnlCharMap { UINT16 CharMapWidth; UINT16 CharMapHeight; UINT16 NumNumerals; UINT16 NumLowerCase; UINT16 NumUpperCase; /* Should be numerals, lowercase, uppercase. In order. */ UINT8 **CharMap; /* Bytemap for now. */ } KrnlCharMap; typedef struct KrnlFirmwareFunctions { GetFirmwareNameFunc GetFirmwareName; PutCharFunc PutChar; PrintlnFunc Println; GetNativeFirmwareMemoryMapFunc GetNativeFirmwareMemoryMap; GetMaxPhysicalAddressFunc GetMaxPhysicalAddress; BackspaceFunc Backspace; /* Add more functions as needed. */ } KrnlFirmwareFunctions; FERALSTATUS KiUpdateFirmwareFunctions( KrnlFirmwareFunctions *Table, KrnlCharMap *CharMap); #endif
32.5
79
0.790244
[ "object" ]
7fa8396149b67f100d40c589c82f478665b5e7d4
1,740
h
C
Descending Europa/Temp/StagingArea/Data/il2cppOutput/UnityEngine_UnityEngine_Events_InvokableCall_1_gen2157144114MethodDeclarations.h
screwylightbulb/europa
3dcc98369c8066cb2310143329535206751c8846
[ "MIT" ]
11
2016-07-22T19:58:09.000Z
2021-09-21T12:51:40.000Z
Descending Europa/Temp/StagingArea/Data/il2cppOutput/UnityEngine_UnityEngine_Events_InvokableCall_1_gen2157144114MethodDeclarations.h
screwylightbulb/europa
3dcc98369c8066cb2310143329535206751c8846
[ "MIT" ]
1
2018-05-07T14:32:13.000Z
2018-05-08T09:15:30.000Z
iOS/Classes/Native/UnityEngine_UnityEngine_Events_InvokableCall_1_gen2157144114MethodDeclarations.h
mopsicus/unity-share-plugin-ios-android
3ee99aef36034a1e4d7b156172953f9b4dfa696f
[ "MIT" ]
null
null
null
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include <assert.h> #include <exception> #include "codegen/il2cpp-codegen.h" #include "UnityEngine_UnityEngine_Events_InvokableCall_1_gen2025761632MethodDeclarations.h" // System.Void UnityEngine.Events.InvokableCall`1<System.String>::.ctor(System.Object,System.Reflection.MethodInfo) #define InvokableCall_1__ctor_m1252173359(__this, ___target0, ___theFunction1, method) (( void (*) (InvokableCall_1_t2157144114 *, Il2CppObject *, MethodInfo_t *, const MethodInfo*))InvokableCall_1__ctor_m3494792797_gshared)(__this, ___target0, ___theFunction1, method) // System.Void UnityEngine.Events.InvokableCall`1<System.String>::.ctor(UnityEngine.Events.UnityAction`1<T1>) #define InvokableCall_1__ctor_m782084045(__this, ___action0, method) (( void (*) (InvokableCall_1_t2157144114 *, UnityAction_1_t4196378856 *, const MethodInfo*))InvokableCall_1__ctor_m2810088059_gshared)(__this, ___action0, method) // System.Void UnityEngine.Events.InvokableCall`1<System.String>::Invoke(System.Object[]) #define InvokableCall_1_Invoke_m3703560070(__this, ___args0, method) (( void (*) (InvokableCall_1_t2157144114 *, ObjectU5BU5D_t1108656482*, const MethodInfo*))InvokableCall_1_Invoke_m689855796_gshared)(__this, ___args0, method) // System.Boolean UnityEngine.Events.InvokableCall`1<System.String>::Find(System.Object,System.Reflection.MethodInfo) #define InvokableCall_1_Find_m1831324518(__this, ___targetObj0, ___method1, method) (( bool (*) (InvokableCall_1_t2157144114 *, Il2CppObject *, MethodInfo_t *, const MethodInfo*))InvokableCall_1_Find_m1349477752_gshared)(__this, ___targetObj0, ___method1, method)
64.444444
270
0.814943
[ "object" ]
7fb27d104df9db3f6f93a7a068cf184c412ed89c
344
h
C
RuiHaoTalents/RuiHaoTalents/Public/Components/LeftMenuAbout/HZTMenuListCell.h
wxw962530118/RuiHaoTalents
9a1115d658d61f68ed668a2b656bdc7acd99f3c1
[ "MIT" ]
null
null
null
RuiHaoTalents/RuiHaoTalents/Public/Components/LeftMenuAbout/HZTMenuListCell.h
wxw962530118/RuiHaoTalents
9a1115d658d61f68ed668a2b656bdc7acd99f3c1
[ "MIT" ]
null
null
null
RuiHaoTalents/RuiHaoTalents/Public/Components/LeftMenuAbout/HZTMenuListCell.h
wxw962530118/RuiHaoTalents
9a1115d658d61f68ed668a2b656bdc7acd99f3c1
[ "MIT" ]
null
null
null
// // HZTMenuListCell.h // RuiHaoTalents // // Created by 王新伟 on 2019/3/13. // Copyright © 2019年 王新伟. All rights reserved. // #import <UIKit/UIKit.h> #import "HZTMenuListModel.h" NS_ASSUME_NONNULL_BEGIN @interface HZTMenuListCell : UITableViewCell /***/ @property (nonatomic, strong) HZTMenuListModel * model; @end NS_ASSUME_NONNULL_END
18.105263
55
0.738372
[ "model" ]