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
aae6285182fe3868077a98a0ad07afb8263caf48
4,114
h
C
src/chrono/geometry/ChRoundedBox.h
Benatti1991/chrono
d927a7fae8ed2f4e6695cacaef28c605fcd9ffaf
[ "BSD-3-Clause" ]
1,383
2015-02-04T14:17:40.000Z
2022-03-30T04:58:16.000Z
src/chrono/geometry/ChRoundedBox.h
Benatti1991/chrono
d927a7fae8ed2f4e6695cacaef28c605fcd9ffaf
[ "BSD-3-Clause" ]
245
2015-01-11T15:30:51.000Z
2022-03-30T21:28:54.000Z
src/chrono/geometry/ChRoundedBox.h
Benatti1991/chrono
d927a7fae8ed2f4e6695cacaef28c605fcd9ffaf
[ "BSD-3-Clause" ]
351
2015-02-04T14:17:47.000Z
2022-03-30T04:42:52.000Z
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Alessandro Tasora, Radu Serban // ============================================================================= #ifndef CHC_ROUNDEDBOX_H #define CHC_ROUNDEDBOX_H #include <cmath> #include "chrono/geometry/ChVolume.h" namespace chrono { namespace geometry { /// A rounded box (sphere-swept box) geometric object for collisions and visualization. class ChApi ChRoundedBox : public ChVolume { public: ChMatrix33<> Rot; /// rotation of box ChVector<> Pos; /// position of center ChVector<> Size; /// box halflengths double radsphere; ///< radius of sweeping sphere public: ChRoundedBox() : Pos(VNULL), Size(VNULL), Rot(1), radsphere(0) {} ChRoundedBox(const ChVector<>& mpos, const ChMatrix33<>& mrot, const ChVector<>& mlengths, double mradsphere) : Pos(mpos), Size(0.5 * mlengths), Rot(mrot), radsphere(mradsphere) {} ChRoundedBox(const ChVector<>& mC0, const ChVector<>& mC1, const ChVector<>& mC2, const ChVector<>& mC3); ChRoundedBox(const ChRoundedBox& source); ~ChRoundedBox() {} /// "Virtual" copy constructor (covariant return type). virtual ChRoundedBox* Clone() const override { return new ChRoundedBox(*this); } virtual GeometryType GetClassType() const override { return ROUNDED_BOX; } virtual void GetBoundingBox(double& xmin, double& xmax, double& ymin, double& ymax, double& zmin, double& zmax, ChMatrix33<>* bbRot = NULL) const override; /// Computes the baricenter of the box virtual ChVector<> Baricenter() const override { return Pos; } /// Computes the covariance matrix for the box virtual void CovarianceMatrix(ChMatrix33<>& C) const override; /// Evaluate position in cube volume virtual void Evaluate(ChVector<>& pos, const double parU, const double parV, const double parW) const override; /// This is a solid virtual int GetManifoldDimension() const override { return 3; } /// Access the rotation of the box ChMatrix33<>* GetRotm() { return &Rot; } /// Access the position of the barycenter of the box ChVector<>& GetPos() { return Pos; } /// Access the size of the box: a vector with the /// three hemi-lengths (lengths divided by two!) ChVector<>& GetSize() { return Size; } /// Get the x y z lengths of this box (that is, double /// the Size values) ChVector<> GetLengths() { return 2.0 * Size; } /// Set the x y z lengths of this box (that is, double /// the Size values) void SetLengths(ChVector<>& mlen) { Size = 0.5 * mlen; } // Get the 8 corner points, translated and rotated ChVector<> GetP1() const; ChVector<> GetP2() const; ChVector<> GetP3() const; ChVector<> GetP4() const; ChVector<> GetP5() const; ChVector<> GetP6() const; ChVector<> GetP7() const; ChVector<> GetP8() const; /// Get the n-th corner point, with ipoint = 1...8 ChVector<> GetPn(int ipoint) const; /// Get the volume (assuming no scaling in Rot matrix) double GetVolume() { return Size.x() * Size.y() * Size.z() * 8.0; }; /// Method to allow serialization of transient data to archives. virtual void ArchiveOUT(ChArchiveOut& marchive) override; /// Method to allow de-serialization of transient data from archives. virtual void ArchiveIN(ChArchiveIn& marchive) override; }; } // end namespace geometry CH_CLASS_VERSION(geometry::ChRoundedBox, 0) } // end namespace chrono #endif
36.087719
115
0.609869
[ "geometry", "object", "vector", "solid" ]
aae65429b725693d5a761765b4142e58d1bd1066
4,763
c
C
src/conv/g5-g4.c
dservin/brlcad
34b72d3efd24ac2c84abbccf9452323231751cd1
[ "BSD-4-Clause", "BSD-3-Clause" ]
null
null
null
src/conv/g5-g4.c
dservin/brlcad
34b72d3efd24ac2c84abbccf9452323231751cd1
[ "BSD-4-Clause", "BSD-3-Clause" ]
null
null
null
src/conv/g5-g4.c
dservin/brlcad
34b72d3efd24ac2c84abbccf9452323231751cd1
[ "BSD-4-Clause", "BSD-3-Clause" ]
null
null
null
/* G 5 - G 4 . C * BRL-CAD * * Copyright (c) 2004-2022 United States Government as represented by * the U.S. Army Research Laboratory. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this file; see the file named COPYING for more * information. * */ /** @file conv/g5-g4.c * g5-g4: program to convert version 5 databases to version 4 * * USAGE * g5-g4 v5_input_database v4_output_database * * DESCRIPTION * Imports version 5 database objects and writes out the equivalent v4 database * objects as best it can. Note that some v5 objects cannot be represented in a * version 4 database. * * AUTHOR * John R. Anderson * * EXAMPLE * g5-g4 model_v5.g model_v4.g */ #include "common.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "vmath.h" #include "bu/app.h" #include "bu/debug.h" #include "bu/units.h" #include "bn.h" #include "raytrace.h" #include "rt/geom.h" #include "wdb.h" int main(int argc, char **argv) { struct rt_wdb *fp; struct db_i *dbip, *dbip4; struct directory *dp; long errors = 0, skipped = 0; struct bn_tol tol; bu_setprogname(argv[0]); /* FIXME: These need to be improved */ tol.magic = BN_TOL_MAGIC; tol.dist = BN_TOL_DIST; tol.dist_sq = tol.dist * tol.dist; tol.perp = 1e-6; tol.para = 1 - tol.perp; bu_debug = BU_DEBUG_COREDUMP; if ( argc != 3 ) { bu_log( "Usage: %s v5.g v4.g\n", argv[0]); return 1; } if ( (dbip = db_open(argv[1], DB_OPEN_READONLY)) == DBI_NULL ) { perror( argv[1] ); return 2; } if ( (dbip4 = db_create( argv[2], 4 )) == DBI_NULL ) { bu_log( "Failed to create output database (%s)\n", argv[2] ); return 3; } if ( (fp = wdb_dbopen( dbip4, RT_WDB_TYPE_DB_DISK )) == RT_WDB_NULL ) { bu_log( "db_dbopen() failed for %s\n", argv[2] ); return 4; } if ( db_version(dbip) != 5 ) { bu_log( "Input database must be a version 5 database!!!!\n" ); return 5; } RT_CK_DBI(dbip); if ( db_dirbuild( dbip ) ) bu_exit(1, "db_dirbuild failed\n" ); mk_id_units( fp, dbip->dbi_title, bu_units_string( dbip->dbi_local2base ) ); /* Retrieve every item in the input database */ FOR_ALL_DIRECTORY_START(dp, dbip) { struct rt_db_internal intern; int id; int ret; bu_log( "%s\n", dp->d_namep ); if ( dp->d_major_type != DB5_MAJORTYPE_BRLCAD ) { bu_log( "\tThis object not supported in version4 databases, not converted\n" ); skipped++; continue; } id = rt_db_get_internal( &intern, dp, dbip, NULL, &rt_uniresource ); if ( id < 0 ) { bu_log( "%s: rt_db_get_internal(%s) failure, skipping\n", argv[0], dp->d_namep); errors++; continue; } if ( id == ID_COMBINATION ) { struct rt_comb_internal *comb; char *ptr; comb = (struct rt_comb_internal *)intern.idb_ptr; RT_CK_COMB( comb ); /* Convert "plastic" to "phong" in the shader string */ while ( (ptr=strstr( bu_vls_addr( &comb->shader), "plastic" )) != NULL ) { ptr[0] = 'p'; /* p */ ptr[1] = 'h'; /* l */ ptr[2] = 'o'; /* a */ ptr[3] = 'n'; /* s */ ptr[4] = 'g'; /* t */ ptr[5] = ' '; /* i */ ptr[6] = ' '; /* c */ } } if ( id == ID_HF ) { if (rt_hf_to_dsp( &intern )) { bu_log( "%s: Conversion from HF to DSP failed for solid %s\n", argv[0], dp->d_namep ); errors++; continue; } } if ( id == ID_POLY) { if ( rt_pg_to_bot( &intern, &tol, &rt_uniresource ) ) { bu_log( "%s: Conversion from polysolid to BOT failed for solid %s\n", argv[0], dp->d_namep ); errors++; continue; } } ret = wdb_put_internal( fp, dp->d_namep, &intern, 1.0 ); if ( ret < 0 ) { bu_log( "%s: wdb_put_internal(%s) failure, skipping\n", argv[0], dp->d_namep); rt_db_free_internal(&intern); errors++; continue; } rt_db_free_internal(&intern); } FOR_ALL_DIRECTORY_END wdb_close( fp ); db_close( dbip ); bu_log( "%ld database version 5 specific objects not attempted to convert\n", skipped ); bu_log( "%ld attempted objects failed to convert\n", errors); return 0; } /* * Local Variables: * mode: C * tab-width: 8 * indent-tabs-mode: t * c-file-style: "stroustrup" * End: * ex: shiftwidth=4 tabstop=8 */
24.678756
92
0.621247
[ "cad", "object", "solid" ]
aae65845714974e5ea118450e01b59d7b94032d8
1,422
h
C
graphics/cgal/Arrangement_on_surface_2/doc/Arrangement_on_surface_2/Concepts/ArrangementWithHistoryInputFormatter.h
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
4
2016-03-30T14:31:52.000Z
2019-02-02T05:01:32.000Z
graphics/cgal/Arrangement_on_surface_2/doc/Arrangement_on_surface_2/Concepts/ArrangementWithHistoryInputFormatter.h
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
null
null
null
graphics/cgal/Arrangement_on_surface_2/doc/Arrangement_on_surface_2/Concepts/ArrangementWithHistoryInputFormatter.h
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
null
null
null
/*! \ingroup PkgArrangement2Concepts \cgalConcept A model for the `ArrangementWithHistoryInputFormatter` concept supports a set of functions that enable reading an arrangement-with-history instance from an input stream using a specific format. \cgalRefines `ArrangementInputFormatter` \cgalHasModel `CGAL::Arr_with_history_text_formatter<ArrFormatter>` */ class ArrangementWithHistoryInputFormatter { public: /// \name Types /// @{ /*! the type of arrangement to input. */ typedef unspecified_type Arr_with_history_2; /*! the inducing curve type. */ typedef typename Arrangement_2::Curve_2 Curve_2; /// @} /// \name Formatted Input Functions /// @{ /*! reads a message indicating the beginning of the inducing curves. */ void read_curves_begin(); /*! reads a message indicating the end of the inducing curves. */ void read_curves_end(); /*! reads a message indicating the beginning of a single curve record. */ void read_curve_begin(); /*! reads a message indicating the end of a single curve record. */ void read_curve_end(); /*! reads a curve. */ void read_curve (Curve_2& c); /*! reads a message indicating the beginning of the set of edges induced by the current curve. */ void read_induced_edges_begin(); /*! reads a message indicating the end of the induced edges set. */ void read_induced_edges_end(); /// @} }; /* end ArrangementWithHistoryInputFormatter */
18.467532
103
0.735584
[ "model" ]
aae7c4611c6d13489ae7fa142a6c5a084c4c447c
5,292
h
C
google/cloud/storage/internal/storage_logging_decorator.h
martinzink/google-cloud-cpp
d49751dc42bb5f7b4a716618e016a27e650377bd
[ "Apache-2.0" ]
null
null
null
google/cloud/storage/internal/storage_logging_decorator.h
martinzink/google-cloud-cpp
d49751dc42bb5f7b4a716618e016a27e650377bd
[ "Apache-2.0" ]
null
null
null
google/cloud/storage/internal/storage_logging_decorator.h
martinzink/google-cloud-cpp
d49751dc42bb5f7b4a716618e016a27e650377bd
[ "Apache-2.0" ]
null
null
null
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/storage/v2/storage.proto #ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_STORAGE_LOGGING_DECORATOR_H #define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_STORAGE_LOGGING_DECORATOR_H #include "google/cloud/storage/internal/storage_stub.h" #include "google/cloud/tracing_options.h" #include "google/cloud/version.h" #include <memory> #include <set> #include <string> namespace google { namespace cloud { namespace storage_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN class StorageLogging : public StorageStub { public: ~StorageLogging() override = default; StorageLogging(std::shared_ptr<StorageStub> child, TracingOptions tracing_options, std::set<std::string> components); Status DeleteBucket( grpc::ClientContext& context, google::storage::v2::DeleteBucketRequest const& request) override; StatusOr<google::storage::v2::Bucket> GetBucket( grpc::ClientContext& context, google::storage::v2::GetBucketRequest const& request) override; StatusOr<google::storage::v2::Bucket> CreateBucket( grpc::ClientContext& context, google::storage::v2::CreateBucketRequest const& request) override; StatusOr<google::storage::v2::ListBucketsResponse> ListBuckets( grpc::ClientContext& context, google::storage::v2::ListBucketsRequest const& request) override; StatusOr<google::storage::v2::Bucket> LockBucketRetentionPolicy( grpc::ClientContext& context, google::storage::v2::LockBucketRetentionPolicyRequest const& request) override; StatusOr<google::iam::v1::Policy> GetIamPolicy( grpc::ClientContext& context, google::iam::v1::GetIamPolicyRequest const& request) override; StatusOr<google::iam::v1::Policy> SetIamPolicy( grpc::ClientContext& context, google::iam::v1::SetIamPolicyRequest const& request) override; StatusOr<google::iam::v1::TestIamPermissionsResponse> TestIamPermissions( grpc::ClientContext& context, google::iam::v1::TestIamPermissionsRequest const& request) override; StatusOr<google::storage::v2::Bucket> UpdateBucket( grpc::ClientContext& context, google::storage::v2::UpdateBucketRequest const& request) override; StatusOr<google::storage::v2::Object> ComposeObject( grpc::ClientContext& context, google::storage::v2::ComposeObjectRequest const& request) override; Status DeleteObject( grpc::ClientContext& context, google::storage::v2::DeleteObjectRequest const& request) override; StatusOr<google::storage::v2::Object> GetObject( grpc::ClientContext& context, google::storage::v2::GetObjectRequest const& request) override; std::unique_ptr<google::cloud::internal::StreamingReadRpc< google::storage::v2::ReadObjectResponse>> ReadObject(std::unique_ptr<grpc::ClientContext> context, google::storage::v2::ReadObjectRequest const& request) override; StatusOr<google::storage::v2::Object> UpdateObject( grpc::ClientContext& context, google::storage::v2::UpdateObjectRequest const& request) override; std::unique_ptr<::google::cloud::internal::StreamingWriteRpc< google::storage::v2::WriteObjectRequest, google::storage::v2::WriteObjectResponse>> WriteObject(std::unique_ptr<grpc::ClientContext> context) override; StatusOr<google::storage::v2::ListObjectsResponse> ListObjects( grpc::ClientContext& context, google::storage::v2::ListObjectsRequest const& request) override; StatusOr<google::storage::v2::RewriteResponse> RewriteObject( grpc::ClientContext& context, google::storage::v2::RewriteObjectRequest const& request) override; StatusOr<google::storage::v2::StartResumableWriteResponse> StartResumableWrite( grpc::ClientContext& context, google::storage::v2::StartResumableWriteRequest const& request) override; StatusOr<google::storage::v2::QueryWriteStatusResponse> QueryWriteStatus( grpc::ClientContext& context, google::storage::v2::QueryWriteStatusRequest const& request) override; StatusOr<google::storage::v2::ServiceAccount> GetServiceAccount( grpc::ClientContext& context, google::storage::v2::GetServiceAccountRequest const& request) override; private: std::shared_ptr<StorageStub> child_; TracingOptions tracing_options_; std::set<std::string> components_; }; // StorageLogging GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage_internal } // namespace cloud } // namespace google #endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_STORAGE_LOGGING_DECORATOR_H
38.627737
85
0.748677
[ "object" ]
aae7f2dfdd73431dfe23bef7ee57d6e5de7ce270
6,216
h
C
src/irr/asset/CMeshManipulator.h
qbasa12/IrrlichtBAW
6473f1dcd440eddaaacee9c33c782697a262f7ac
[ "Apache-2.0" ]
null
null
null
src/irr/asset/CMeshManipulator.h
qbasa12/IrrlichtBAW
6473f1dcd440eddaaacee9c33c782697a262f7ac
[ "Apache-2.0" ]
2
2019-05-20T12:28:51.000Z
2019-05-24T10:33:41.000Z
src/irr/asset/CMeshManipulator.h
manhnt9/IrrlichtBAW
502f2200070d8181f235294403a7de63782e9dcc
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2002-2012 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #ifndef __C_MESH_MANIPULATOR_H_INCLUDED__ #define __C_MESH_MANIPULATOR_H_INCLUDED__ #include "irr/asset/IMeshManipulator.h" namespace irr { namespace asset { //! An interface for easy manipulation of meshes. /** Scale, set alpha value, flip surfaces, and so on. This exists for fixing problems with wrong imported or exported meshes quickly after loading. It is not intended for doing mesh modifications and/or animations during runtime. */ class CMeshManipulator : public IMeshManipulator { struct SAttrib { asset::E_FORMAT type; asset::E_FORMAT prevType; size_t size; asset::E_VERTEX_ATTRIBUTE_ID vaid; size_t offset; SAttrib() : type(asset::EF_UNKNOWN), size(0), vaid(asset::EVAI_COUNT) {} friend bool operator>(const SAttrib& _a, const SAttrib& _b) { return _a.size > _b.size; } }; struct SAttribTypeChoice { asset::E_FORMAT type; }; public: //! Flips the direction of surfaces. /** Changes backfacing triangles to frontfacing triangles and vice versa. \param mesh: Mesh on which the operation is performed. */ virtual void flipSurfaces(asset::ICPUMeshBuffer* inbuffer) const; #ifndef NEW_MESHES //! Recalculates all normals of the mesh. /** \param mesh: Mesh on which the operation is performed. \param smooth: Whether to use smoothed normals. */ virtual void recalculateNormals(scene::IMesh* mesh, bool smooth = false, bool angleWeighted = false) const; //! Recalculates all normals of the mesh buffer. /** \param buffer: Mesh buffer on which the operation is performed. \param smooth: Whether to use smoothed normals. */ virtual void recalculateNormals(IMeshBuffer* buffer, bool smooth = false, bool angleWeighted = false) const; //! Recalculates tangents, requires a tangent mesh buffer virtual void recalculateTangents(IMeshBuffer* buffer, bool recalculateNormals=false, bool smooth=false, bool angleWeighted=false) const; //! Recalculates tangents, requires a tangent mesh virtual void recalculateTangents(IMesh* mesh, bool recalculateNormals=false, bool smooth=false, bool angleWeighted=false) const; #endif // NEW_MESHES virtual asset::ICPUMeshBuffer* createMeshBufferFetchOptimized(const asset::ICPUMeshBuffer* _inbuffer) const; //! Creates a copy of the mesh, which will only consist of unique triangles, i.e. no vertices are shared. virtual asset::ICPUMeshBuffer* createMeshBufferUniquePrimitives(asset::ICPUMeshBuffer* inbuffer) const; //! Creates a copy of the mesh, which will have all duplicated vertices removed, i.e. maximal amount of vertices are shared via indexing. virtual asset::ICPUMeshBuffer* createMeshBufferWelded(asset::ICPUMeshBuffer *inbuffer, const SErrorMetric* _errMetrics, const bool& optimIndexType = true, const bool& makeNewMesh=false) const; virtual asset::ICPUMeshBuffer* createOptimizedMeshBuffer(const asset::ICPUMeshBuffer* inbuffer, const SErrorMetric* _errMetric) const; virtual void requantizeMeshBuffer(asset::ICPUMeshBuffer* _meshbuffer, const SErrorMetric* _errMetric) const; virtual asset::ICPUMeshBuffer* createMeshBufferDuplicate(const asset::ICPUMeshBuffer* _src) const; virtual void filterInvalidTriangles(asset::ICPUMeshBuffer* _input) const; virtual asset::ICPUBuffer* idxBufferFromTriangleStripsToTriangles(const void* _input, size_t _idxCount, asset::E_INDEX_TYPE _idxType) const; virtual asset::ICPUBuffer* idxBufferFromTrianglesFanToTriangles(const void* _input, size_t _idxCount, asset::E_INDEX_TYPE _idxType) const; virtual bool compareFloatingPointAttribute(const core::vectorSIMDf& _a, const core::vectorSIMDf& _b, size_t _cpa, const SErrorMetric& _errMetric) const; private: //! Copies only member variables not being pointers to another dynamically allocated irr::IReferenceCounted derivatives. //! Purely helper function. Not really meant to be used outside createMeshBufferDuplicate(). template<typename T> void copyMeshBufferMemberVars(T* _dst, const T* _src) const; template<typename IdxT> void priv_filterInvalidTriangles(asset::ICPUMeshBuffer* _input) const; //! Meant to create 32bit index buffer from subrange of index buffer containing 16bit indices. Remember to set to index buffer offset to 0 after mapping buffer resulting from this function. asset::ICPUBuffer* create32BitFrom16BitIdxBufferSubrange(const uint16_t* _in, size_t _idxCount) const; core::vector<core::vectorSIMDf> findBetterFormatF(asset::E_FORMAT* _outType, size_t* _outSize, asset::E_FORMAT* _outPrevType, const asset::ICPUMeshBuffer* _meshbuffer, asset::E_VERTEX_ATTRIBUTE_ID _attrId, const SErrorMetric& _errMetric) const; struct SIntegerAttr { uint32_t pointer[4]; }; core::vector<SIntegerAttr> findBetterFormatI(asset::E_FORMAT* _outType, size_t* _outSize, asset::E_FORMAT* _outPrevType, const asset::ICPUMeshBuffer* _meshbuffer, asset::E_VERTEX_ATTRIBUTE_ID _attrId, const SErrorMetric& _errMetric) const; //E_COMPONENT_TYPE getBestTypeF(bool _normalized, E_COMPONENTS_PER_ATTRIBUTE _cpa, size_t* _outSize, E_COMPONENTS_PER_ATTRIBUTE* _outCpa, const float* _min, const float* _max) const; asset::E_FORMAT getBestTypeI(asset::E_FORMAT _originalType, size_t* _outSize, const uint32_t* _min, const uint32_t* _max) const; core::vector<SAttribTypeChoice> findTypesOfProperRangeF(asset::E_FORMAT _type, size_t _sizeThreshold, const float* _min, const float* _max, const SErrorMetric& _errMetric) const; //! Calculates quantization errors and compares them with given epsilon. /** @returns false when first of calculated errors goes above epsilon or true if reached end without such. */ bool calcMaxQuantizationError(const SAttribTypeChoice& _srcType, const SAttribTypeChoice& _dstType, const core::vector<core::vectorSIMDf>& _data, const SErrorMetric& _errMetric) const; template<typename T> asset::ICPUBuffer* triangleStripsToTriangles(const void* _input, size_t _idxCount) const; template<typename T> asset::ICPUBuffer* trianglesFanToTriangles(const void* _input, size_t _idxCount) const; }; } // end namespace scene } // end namespace irr #endif
49.728
245
0.789254
[ "mesh", "vector" ]
aae820806721e95b42471fb7238f566427d2937f
24,333
c
C
source/TR-181/middle_layer_src/cosa_x_cisco_com_diagnostics_dml.c
rdkcmf/rdkb-CcspPandM
2fd5a50ab432dabb835b13007686b2e632fca85e
[ "Apache-2.0" ]
2
2020-03-11T16:46:48.000Z
2022-02-16T23:14:26.000Z
source/TR-181/middle_layer_src/cosa_x_cisco_com_diagnostics_dml.c
lgirdk/ccsp-p-and-m
343fd4017bc7bee00da065d1bbad73d2044f6d5c
[ "Apache-2.0" ]
null
null
null
source/TR-181/middle_layer_src/cosa_x_cisco_com_diagnostics_dml.c
lgirdk/ccsp-p-and-m
343fd4017bc7bee00da065d1bbad73d2044f6d5c
[ "Apache-2.0" ]
4
2017-07-30T15:38:43.000Z
2020-08-18T20:52:18.000Z
/* * If not stated otherwise in this file or this component's Licenses.txt file the * following copyright and licenses apply: * * Copyright 2015 RDK Management * * 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 [2014] [Cisco Systems, 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. **********************************************************************/ /************************************************************************** module: cosa_apis_x_cisco_com_mld_dml.c For COSA Data Model Library Development ------------------------------------------------------------------- description: This file implementes back-end apis for the COSA Data Model Library ------------------------------------------------------------------- environment: platform independent ------------------------------------------------------------------- author: COSA XML TOOL CODE GENERATOR 1.0 ------------------------------------------------------------------- revision: 08/12/2011 initial revision. **************************************************************************/ #include "ansc_platform.h" #include "cosa_x_cisco_com_diagnostics_dml.h" #include "safec_lib_common.h" /*********************************************************************** IMPORTANT NOTE: According to TR69 spec: On successful receipt of a SetParameterValues RPC, the CPE MUST apply the changes to all of the specified Parameters atomically. That is, either all of the value changes are applied together, or none of the changes are applied at all. In the latter case, the CPE MUST return a fault response indicating the reason for the failure to apply the changes. The CPE MUST NOT apply any of the specified changes without applying all of them. In order to set parameter values correctly, the back-end is required to hold the updated values until "Validate" and "Commit" are called. Only after all the "Validate" passed in different objects, the "Commit" will be called. Otherwise, "Rollback" will be called instead. The sequence in COSA Data Model will be: SetParamBoolValue/SetParamIntValue/SetParamUlongValue/SetParamStringValue -- Backup the updated values; if( Validate_XXX()) { Commit_XXX(); -- Commit the update all together in the same object } else { Rollback_XXX(); -- Remove the update at backup; } ***********************************************************************/ ULONG Entry_GetEntryCount ( ANSC_HANDLE hInsContext ) { UNREFERENCED_PARAMETER(hInsContext); PCOSA_DATAMODEL_DIAGNOSTICS pDiag = (PCOSA_DATAMODEL_DIAGNOSTICS)g_pCosaBEManager->hDiag; return pDiag->ulDiagEntryNumber; } ANSC_HANDLE Entry_GetEntry ( ANSC_HANDLE hInsContext, ULONG nIndex, ULONG* pInsNumber ) { UNREFERENCED_PARAMETER(hInsContext); PCOSA_DATAMODEL_DIAGNOSTICS pDiag = (PCOSA_DATAMODEL_DIAGNOSTICS)g_pCosaBEManager->hDiag; *pInsNumber = nIndex + 1; if ( pDiag->pDiagEntry ) { return &(pDiag->pDiagEntry[nIndex]); } return NULL; } static ULONG last_tick; #define REFRESH_INTERVAL 30 #define TIME_NO_NEGATIVE(x) ((long)(x) < 0 ? 0 : (x)) BOOL Entry_IsUpdated ( ANSC_HANDLE hInsContext ) { UNREFERENCED_PARAMETER(hInsContext); if ( !last_tick ) { last_tick = AnscGetTickInSeconds(); return TRUE; } if ( last_tick >= TIME_NO_NEGATIVE(AnscGetTickInSeconds() - REFRESH_INTERVAL) ) { return FALSE; } else { last_tick = AnscGetTickInSeconds(); return TRUE; } } /********************************************************************** caller: owner of this object prototype: ULONG Group_Synchronize ( ANSC_HANDLE hInsContext ); description: This function is called to synchronize the table. argument: ANSC_HANDLE hInsContext, The instance handle; return: The status of the operation. **********************************************************************/ ULONG Entry_Synchronize ( ANSC_HANDLE hInsContext ) { UNREFERENCED_PARAMETER(hInsContext); static int first = 1; PCOSA_DATAMODEL_DIAGNOSTICS pMyObject = (PCOSA_DATAMODEL_DIAGNOSTICS)g_pCosaBEManager->hDiag; ULONG index = 0; if (first) { first =0; return 0; } if ( pMyObject->pDiagEntry ) { for( index = 0; index < pMyObject->ulDiagEntryNumber; index++ ) { if ( pMyObject->pDiagEntry[index].pMessage ) { /* We must use free() here. */ free(pMyObject->pDiagEntry[index].pMessage); } } AnscFreeMemory(pMyObject->pDiagEntry); pMyObject->pDiagEntry = NULL; pMyObject->ulDiagEntryNumber = 0; } CosaDmlDiagnosticsGetEntry ( (ANSC_HANDLE)NULL, &pMyObject->ulDiagEntryNumber, &pMyObject->pDiagEntry ); return 0; } /********************************************************************** caller: owner of this object prototype: BOOL Group_GetParamBoolValue ( ANSC_HANDLE hInsContext, char* ParamName, BOOL* pBool ); description: This function is called to retrieve Boolean parameter value; argument: ANSC_HANDLE hInsContext, The instance handle; char* ParamName, The parameter name; BOOL* pBool The buffer of returned boolean value; return: TRUE if succeeded. **********************************************************************/ BOOL Entry_GetParamBoolValue ( ANSC_HANDLE hInsContext, char* ParamName, BOOL* pBool ) { UNREFERENCED_PARAMETER(hInsContext); UNREFERENCED_PARAMETER(ParamName); UNREFERENCED_PARAMETER(pBool); /* check the parameter name and return the corresponding value */ /* CcspTraceWarning(("Unsupported parameter '%s'\n", ParamName)); */ return FALSE; } /********************************************************************** caller: owner of this object prototype: BOOL Group_GetParamIntValue ( ANSC_HANDLE hInsContext, char* ParamName, int* pInt ); description: This function is called to retrieve integer parameter value; argument: ANSC_HANDLE hInsContext, The instance handle; char* ParamName, The parameter name; int* pInt The buffer of returned integer value; return: TRUE if succeeded. **********************************************************************/ BOOL Entry_GetParamIntValue ( ANSC_HANDLE hInsContext, char* ParamName, int* pInt ) { UNREFERENCED_PARAMETER(hInsContext); UNREFERENCED_PARAMETER(ParamName); UNREFERENCED_PARAMETER(pInt); /* check the parameter name and return the corresponding value */ /* CcspTraceWarning(("Unsupported parameter '%s'\n", ParamName)); */ return FALSE; } /********************************************************************** caller: owner of this object prototype: BOOL Group_GetParamUlongValue ( ANSC_HANDLE hInsContext, char* ParamName, ULONG* puLong ); description: This function is called to retrieve ULONG parameter value; argument: ANSC_HANDLE hInsContext, The instance handle; char* ParamName, The parameter name; ULONG* puLong The buffer of returned ULONG value; return: TRUE if succeeded. **********************************************************************/ BOOL Entry_GetParamUlongValue ( ANSC_HANDLE hInsContext, char* ParamName, ULONG* puLong ) { PCOSA_DML_DIAGNOSTICS_ENTRY pDiagGroupEntry = (PCOSA_DML_DIAGNOSTICS_ENTRY)hInsContext; /* check the parameter name and return the corresponding value */ if( AnscEqualString(ParamName, "Level", TRUE)) { /* collect value */ *puLong = pDiagGroupEntry->Level; return TRUE; } /* check the parameter name and return the corresponding value */ return FALSE; } /********************************************************************** caller: owner of this object prototype: ULONG Group_GetParamStringValue ( ANSC_HANDLE hInsContext, char* ParamName, char* pValue, ULONG* pUlSize ); description: This function is called to retrieve string parameter value; argument: ANSC_HANDLE hInsContext, The instance handle; char* ParamName, The parameter name; char* pValue, The string value buffer; ULONG* pUlSize The buffer of length of string value; Usually size of 4095 will be used. If it's not big enough, put required size here and return 1; return: 0 if succeeded; 1 if short of buffer size; (*pUlSize = required size) -1 if not supported. **********************************************************************/ ULONG Entry_GetParamStringValue ( ANSC_HANDLE hInsContext, char* ParamName, char* pValue, ULONG* pUlSize ) { PCOSA_DML_DIAGNOSTICS_ENTRY pDiagEntry = (PCOSA_DML_DIAGNOSTICS_ENTRY)hInsContext; errno_t rc = -1; /* check the parameter name and return the corresponding value */ if( AnscEqualString(ParamName, "Time", TRUE)) { /* collect value */ rc = strcpy_s(pValue, *pUlSize, pDiagEntry->Time); if ( rc != EOK) { ERR_CHK(rc); return -1; } return 0; } if( AnscEqualString(ParamName, "Tag", TRUE)) { /* collect value */ rc = strcpy_s(pValue, *pUlSize, pDiagEntry->Tag); if ( rc != EOK) { ERR_CHK(rc); return -1; } return 0; } if( AnscEqualString(ParamName, "Message", TRUE)) { /* collect value */ if ( (_ansc_strlen(pDiagEntry->pMessage)+1) < *pUlSize ) { rc = strcpy_s(pValue, *pUlSize, pDiagEntry->pMessage); if ( rc != EOK) { ERR_CHK(rc); return -1; } } else { *pUlSize = _ansc_strlen(pDiagEntry->pMessage) + 1; return 1; } return 0; } /* CcspTraceWarning(("Unsupported parameter '%s'\n", ParamName)); */ return -1; } ULONG Eventlog_GetEntryCount ( ANSC_HANDLE hInsContext ) { UNREFERENCED_PARAMETER(hInsContext); PCOSA_DATAMODEL_DIAGNOSTICS pDiag = (PCOSA_DATAMODEL_DIAGNOSTICS)g_pCosaBEManager->hDiag; return pDiag->ulDiagEventlogNumber; } ANSC_HANDLE Eventlog_GetEntry ( ANSC_HANDLE hInsContext, ULONG nIndex, ULONG* pInsNumber ) { UNREFERENCED_PARAMETER(hInsContext); PCOSA_DATAMODEL_DIAGNOSTICS pDiag = (PCOSA_DATAMODEL_DIAGNOSTICS)g_pCosaBEManager->hDiag; *pInsNumber = nIndex + 1; if ( pDiag->pDiagEventlog ) { return &(pDiag->pDiagEventlog[nIndex]); } return NULL; } static ULONG eventlog_last_tick = 0; BOOL Eventlog_IsUpdated ( ANSC_HANDLE hInsContext ) { UNREFERENCED_PARAMETER(hInsContext); if ( !eventlog_last_tick ) { eventlog_last_tick = AnscGetTickInSeconds(); return TRUE; } if ( eventlog_last_tick >= TIME_NO_NEGATIVE(AnscGetTickInSeconds() - REFRESH_INTERVAL) ) { return FALSE; } else { eventlog_last_tick = AnscGetTickInSeconds(); return TRUE; } } /********************************************************************** caller: owner of this object prototype: ULONG Group_Synchronize ( ANSC_HANDLE hInsContext ); description: This function is called to synchronize the table. argument: ANSC_HANDLE hInsContext, The instance handle; return: The status of the operation. **********************************************************************/ ULONG Eventlog_Synchronize ( ANSC_HANDLE hInsContext ) { PCOSA_DATAMODEL_DIAGNOSTICS pMyObject = (PCOSA_DATAMODEL_DIAGNOSTICS)g_pCosaBEManager->hDiag; ULONG index = 0; static int first = 1; UNREFERENCED_PARAMETER(hInsContext); if (first) { first =0; return 0; } if ( pMyObject->pDiagEventlog ) { for( index = 0; index < pMyObject->ulDiagEventlogNumber; index++ ) { if ( pMyObject->pDiagEventlog[index].pMessage ) { /* We must use free() here. */ free(pMyObject->pDiagEventlog[index].pMessage); } } AnscFreeMemory(pMyObject->pDiagEventlog); pMyObject->pDiagEventlog = NULL; pMyObject->ulDiagEventlogNumber = 0; } CosaDmlDiagnosticsGetEventlog ( (ANSC_HANDLE)NULL, &pMyObject->ulDiagEventlogNumber, &pMyObject->pDiagEventlog ); return 0; } /********************************************************************** caller: owner of this object prototype: BOOL Group_GetParamBoolValue ( ANSC_HANDLE hInsContext, char* ParamName, BOOL* pBool ); description: This function is called to retrieve Boolean parameter value; argument: ANSC_HANDLE hInsContext, The instance handle; char* ParamName, The parameter name; BOOL* pBool The buffer of returned boolean value; return: TRUE if succeeded. **********************************************************************/ BOOL Eventlog_GetParamBoolValue ( ANSC_HANDLE hInsContext, char* ParamName, BOOL* pBool ) { UNREFERENCED_PARAMETER(hInsContext); UNREFERENCED_PARAMETER(ParamName); UNREFERENCED_PARAMETER(pBool); /* check the parameter name and return the corresponding value */ /* CcspTraceWarning(("Unsupported parameter '%s'\n", ParamName)); */ return FALSE; } /********************************************************************** caller: owner of this object prototype: BOOL Group_GetParamIntValue ( ANSC_HANDLE hInsContext, char* ParamName, int* pInt ); description: This function is called to retrieve integer parameter value; argument: ANSC_HANDLE hInsContext, The instance handle; char* ParamName, The parameter name; int* pInt The buffer of returned integer value; return: TRUE if succeeded. **********************************************************************/ BOOL Eventlog_GetParamIntValue ( ANSC_HANDLE hInsContext, char* ParamName, int* pInt ) { UNREFERENCED_PARAMETER(hInsContext); UNREFERENCED_PARAMETER(ParamName); UNREFERENCED_PARAMETER(pInt); /* check the parameter name and return the corresponding value */ /* CcspTraceWarning(("Unsupported parameter '%s'\n", ParamName)); */ return FALSE; } /********************************************************************** caller: owner of this object prototype: BOOL Group_GetParamUlongValue ( ANSC_HANDLE hInsContext, char* ParamName, ULONG* puLong ); description: This function is called to retrieve ULONG parameter value; argument: ANSC_HANDLE hInsContext, The instance handle; char* ParamName, The parameter name; ULONG* puLong The buffer of returned ULONG value; return: TRUE if succeeded. **********************************************************************/ BOOL Eventlog_GetParamUlongValue ( ANSC_HANDLE hInsContext, char* ParamName, ULONG* puLong ) { PCOSA_DML_DIAGNOSTICS_ENTRY pDiagGroupEventlog = (PCOSA_DML_DIAGNOSTICS_ENTRY)hInsContext; /* check the parameter name and return the corresponding value */ if( AnscEqualString(ParamName, "Level", TRUE)) { /* collect value */ *puLong = pDiagGroupEventlog->Level; return TRUE; } /* check the parameter name and return the corresponding value */ return FALSE; } /********************************************************************** caller: owner of this object prototype: ULONG Group_GetParamStringValue ( ANSC_HANDLE hInsContext, char* ParamName, char* pValue, ULONG* pUlSize ); description: This function is called to retrieve string parameter value; argument: ANSC_HANDLE hInsContext, The instance handle; char* ParamName, The parameter name; char* pValue, The string value buffer; ULONG* pUlSize The buffer of length of string value; Usually size of 4095 will be used. If it's not big enough, put required size here and return 1; return: 0 if succeeded; 1 if short of buffer size; (*pUlSize = required size) -1 if not supported. **********************************************************************/ ULONG Eventlog_GetParamStringValue ( ANSC_HANDLE hInsContext, char* ParamName, char* pValue, ULONG* pUlSize ) { PCOSA_DML_DIAGNOSTICS_ENTRY pDiagEventlog = (PCOSA_DML_DIAGNOSTICS_ENTRY)hInsContext; errno_t rc = -1; /* check the parameter name and return the corresponding value */ if( AnscEqualString(ParamName, "Time", TRUE)) { /* collect value */ rc = strcpy_s(pValue, *pUlSize, pDiagEventlog->Time); if ( rc != EOK) { ERR_CHK(rc); return -1; } return 0; } if( AnscEqualString(ParamName, "Tag", TRUE)) { /* collect value */ rc = strcpy_s(pValue, *pUlSize, pDiagEventlog->Tag); if ( rc != EOK) { ERR_CHK(rc); return -1; } return 0; } if( AnscEqualString(ParamName, "Message", TRUE)) { /* collect value */ if ( (_ansc_strlen(pDiagEventlog->pMessage)+1) < *pUlSize ) { rc = strcpy_s(pValue, *pUlSize, pDiagEventlog->pMessage); if ( rc != EOK) { ERR_CHK(rc); return -1; } } else { *pUlSize = _ansc_strlen(pDiagEventlog->pMessage) + 1; return 1; } return 0; } /* CcspTraceWarning(("Unsupported parameter '%s'\n", ParamName)); */ return -1; } ULONG X_CISCO_COM_Diagnostics_GetParamStringValue ( ANSC_HANDLE hInsContext, char* ParamName, char* pValue, ULONG* pUlSize ) { UNREFERENCED_PARAMETER(hInsContext); ULONG logSize = *pUlSize; if( AnscEqualString(ParamName, "DumpAllSyslog", TRUE)) { if((ANSC_STATUS_FAILURE == CosaDmlDiagnosticsGetAllSyslog(pValue, &logSize)) != ANSC_STATUS_SUCCESS) { if(logSize > *pUlSize){ *pUlSize = logSize; return 1; } else return -1; } return 0; } if( AnscEqualString(ParamName, "DumpAllEventlog", TRUE)) { if((ANSC_STATUS_FAILURE == CosaDmlDiagnosticsGetAllEventlog(pValue, &logSize)) != ANSC_STATUS_SUCCESS) { if(logSize > *pUlSize){ *pUlSize = logSize; return 1; } else return -1; } return 0; } /* CcspTraceWarning(("Unsupported parameter '%s'\n", ParamName)); */ return -1; }
27.309764
111
0.481774
[ "object", "model" ]
aaeaa5ddf1b02ed8cfd2644f13d33abcb3514948
415
h
C
libraries/libsystem/json/Json.h
Kaushal1011/skift
bc25d9642e4bcd74ece1d1668e1f66a80100bbf2
[ "MIT" ]
2
2021-08-14T16:03:48.000Z
2021-11-09T10:29:36.000Z
libraries/libsystem/json/Json.h
optimisticside/skift
3d59b222d686c83e370e8075506d129f8ff1fdac
[ "MIT" ]
null
null
null
libraries/libsystem/json/Json.h
optimisticside/skift
3d59b222d686c83e370e8075506d129f8ff1fdac
[ "MIT" ]
null
null
null
#pragma once #include <libutils/Scanner.h> #include <libutils/String.h> #include <libsystem/json/Array.h> #include <libsystem/json/Object.h> #include <libsystem/json/Value.h> #include <libutils/Prettifier.h> namespace json { Value parse(Scanner &scan); Value parse(const char *str, size_t size); Value parse_file(const char *path); void prettify(Prettifier &pretty, const Value &value); } // namespace json
18.043478
54
0.746988
[ "object" ]
aaef45c0df7c78c2ac531b9caba42fd6ef415df6
12,392
h
C
include/jemalloc/internal/arena_inlines_b.h
Sonicadvance1/jemalloc
2e3104ba07da1df4c04586231ff9266a1e35094d
[ "BSD-2-Clause" ]
null
null
null
include/jemalloc/internal/arena_inlines_b.h
Sonicadvance1/jemalloc
2e3104ba07da1df4c04586231ff9266a1e35094d
[ "BSD-2-Clause" ]
null
null
null
include/jemalloc/internal/arena_inlines_b.h
Sonicadvance1/jemalloc
2e3104ba07da1df4c04586231ff9266a1e35094d
[ "BSD-2-Clause" ]
null
null
null
#ifndef JEMALLOC_INTERNAL_ARENA_INLINES_B_H #define JEMALLOC_INTERNAL_ARENA_INLINES_B_H #include "jemalloc/internal/emap.h" #include "jemalloc/internal/jemalloc_internal_types.h" #include "jemalloc/internal/mutex.h" #include "jemalloc/internal/rtree.h" #include "jemalloc/internal/safety_check.h" #include "jemalloc/internal/sc.h" #include "jemalloc/internal/sz.h" #include "jemalloc/internal/ticker.h" static inline arena_t * arena_get_from_edata(edata_t *edata) { return (arena_t *)atomic_load_p(&arenas[edata_arena_ind_get(edata)], ATOMIC_RELAXED); } JEMALLOC_ALWAYS_INLINE arena_t * arena_choose_maybe_huge(tsd_t *tsd, arena_t *arena, size_t size) { if (arena != NULL) { return arena; } /* * For huge allocations, use the dedicated huge arena if both are true: * 1) is using auto arena selection (i.e. arena == NULL), and 2) the * thread is not assigned to a manual arena. */ if (unlikely(size >= oversize_threshold)) { arena_t *tsd_arena = tsd_arena_get(tsd); if (tsd_arena == NULL || arena_is_auto(tsd_arena)) { return arena_choose_huge(tsd); } } return arena_choose(tsd, NULL); } JEMALLOC_ALWAYS_INLINE void arena_prof_info_get(tsd_t *tsd, const void *ptr, emap_alloc_ctx_t *alloc_ctx, prof_info_t *prof_info, bool reset_recent) { cassert(config_prof); assert(ptr != NULL); assert(prof_info != NULL); edata_t *edata = NULL; bool is_slab; /* Static check. */ if (alloc_ctx == NULL) { edata = emap_edata_lookup(tsd_tsdn(tsd), &arena_emap_global, ptr); is_slab = edata_slab_get(edata); } else if (unlikely(!(is_slab = alloc_ctx->slab))) { edata = emap_edata_lookup(tsd_tsdn(tsd), &arena_emap_global, ptr); } if (unlikely(!is_slab)) { /* edata must have been initialized at this point. */ assert(edata != NULL); large_prof_info_get(tsd, edata, prof_info, reset_recent); } else { prof_info->alloc_tctx = (prof_tctx_t *)(uintptr_t)1U; /* * No need to set other fields in prof_info; they will never be * accessed if (uintptr_t)alloc_tctx == (uintptr_t)1U. */ } } JEMALLOC_ALWAYS_INLINE void arena_prof_tctx_reset(tsd_t *tsd, const void *ptr, emap_alloc_ctx_t *alloc_ctx) { cassert(config_prof); assert(ptr != NULL); /* Static check. */ if (alloc_ctx == NULL) { edata_t *edata = emap_edata_lookup(tsd_tsdn(tsd), &arena_emap_global, ptr); if (unlikely(!edata_slab_get(edata))) { large_prof_tctx_reset(edata); } } else { if (unlikely(!alloc_ctx->slab)) { edata_t *edata = emap_edata_lookup(tsd_tsdn(tsd), &arena_emap_global, ptr); large_prof_tctx_reset(edata); } } } JEMALLOC_ALWAYS_INLINE void arena_prof_tctx_reset_sampled(tsd_t *tsd, const void *ptr) { cassert(config_prof); assert(ptr != NULL); edata_t *edata = emap_edata_lookup(tsd_tsdn(tsd), &arena_emap_global, ptr); assert(!edata_slab_get(edata)); large_prof_tctx_reset(edata); } JEMALLOC_ALWAYS_INLINE void arena_prof_info_set(tsd_t *tsd, edata_t *edata, prof_tctx_t *tctx, size_t size) { cassert(config_prof); assert(!edata_slab_get(edata)); large_prof_info_set(edata, tctx, size); } JEMALLOC_ALWAYS_INLINE void arena_decay_ticks(tsdn_t *tsdn, arena_t *arena, unsigned nticks) { tsd_t *tsd; ticker_t *decay_ticker; if (unlikely(tsdn_null(tsdn))) { return; } tsd = tsdn_tsd(tsdn); decay_ticker = decay_ticker_get(tsd, arena_ind_get(arena)); if (unlikely(decay_ticker == NULL)) { return; } if (unlikely(ticker_ticks(decay_ticker, nticks))) { arena_decay(tsdn, arena, false, false); } } JEMALLOC_ALWAYS_INLINE void arena_decay_tick(tsdn_t *tsdn, arena_t *arena) { arena_decay_ticks(tsdn, arena, 1); } JEMALLOC_ALWAYS_INLINE void * arena_malloc(tsdn_t *tsdn, arena_t *arena, size_t size, szind_t ind, bool zero, tcache_t *tcache, bool slow_path) { assert(!tsdn_null(tsdn) || tcache == NULL); if (likely(tcache != NULL)) { if (likely(size <= SC_SMALL_MAXCLASS)) { return tcache_alloc_small(tsdn_tsd(tsdn), arena, tcache, size, ind, zero, slow_path); } if (likely(size <= tcache_maxclass)) { return tcache_alloc_large(tsdn_tsd(tsdn), arena, tcache, size, ind, zero, slow_path); } /* (size > tcache_maxclass) case falls through. */ assert(size > tcache_maxclass); } return arena_malloc_hard(tsdn, arena, size, ind, zero); } JEMALLOC_ALWAYS_INLINE arena_t * arena_aalloc(tsdn_t *tsdn, const void *ptr) { edata_t *edata = emap_edata_lookup(tsdn, &arena_emap_global, ptr); unsigned arena_ind = edata_arena_ind_get(edata); return (arena_t *)atomic_load_p(&arenas[arena_ind], ATOMIC_RELAXED); } JEMALLOC_ALWAYS_INLINE size_t arena_salloc(tsdn_t *tsdn, const void *ptr) { assert(ptr != NULL); emap_alloc_ctx_t alloc_ctx; emap_alloc_ctx_lookup(tsdn, &arena_emap_global, ptr, &alloc_ctx); assert(alloc_ctx.szind != SC_NSIZES); return sz_index2size(alloc_ctx.szind); } JEMALLOC_ALWAYS_INLINE size_t arena_vsalloc(tsdn_t *tsdn, const void *ptr) { /* * Return 0 if ptr is not within an extent managed by jemalloc. This * function has two extra costs relative to isalloc(): * - The rtree calls cannot claim to be dependent lookups, which induces * rtree lookup load dependencies. * - The lookup may fail, so there is an extra branch to check for * failure. */ emap_full_alloc_ctx_t full_alloc_ctx; bool missing = emap_full_alloc_ctx_try_lookup(tsdn, &arena_emap_global, ptr, &full_alloc_ctx); if (missing) { return 0; } if (full_alloc_ctx.edata == NULL) { return 0; } assert(edata_state_get(full_alloc_ctx.edata) == extent_state_active); /* Only slab members should be looked up via interior pointers. */ assert(edata_addr_get(full_alloc_ctx.edata) == ptr || edata_slab_get(full_alloc_ctx.edata)); assert(full_alloc_ctx.szind != SC_NSIZES); return sz_index2size(full_alloc_ctx.szind); } JEMALLOC_ALWAYS_INLINE bool large_dalloc_safety_checks(edata_t *edata, szind_t szind) { if (!config_opt_safety_checks) { return false; } /* * Eagerly detect double free and sized dealloc bugs for large sizes. * The cost is low enough (as edata will be accessed anyway) to be * enabled all the time. */ if (unlikely(edata_state_get(edata) != extent_state_active)) { safety_check_fail("Invalid deallocation detected: " "pages being freed (%p) not currently active, " "possibly caused by double free bugs.", (uintptr_t)edata_addr_get(edata)); return true; } if (unlikely(sz_index2size(szind) != edata_usize_get(edata))) { safety_check_fail_sized_dealloc(/* current_dealloc */ true); return true; } return false; } static inline void arena_dalloc_large_no_tcache(tsdn_t *tsdn, void *ptr, szind_t szind) { if (config_prof && unlikely(szind < SC_NBINS)) { arena_dalloc_promoted(tsdn, ptr, NULL, true); } else { edata_t *edata = emap_edata_lookup(tsdn, &arena_emap_global, ptr); if (large_dalloc_safety_checks(edata, szind)) { /* See the comment in isfree. */ return; } large_dalloc(tsdn, edata); } } static inline void arena_dalloc_no_tcache(tsdn_t *tsdn, void *ptr) { assert(ptr != NULL); emap_alloc_ctx_t alloc_ctx; emap_alloc_ctx_lookup(tsdn, &arena_emap_global, ptr, &alloc_ctx); if (config_debug) { edata_t *edata = emap_edata_lookup(tsdn, &arena_emap_global, ptr); assert(alloc_ctx.szind == edata_szind_get(edata)); assert(alloc_ctx.szind < SC_NSIZES); assert(alloc_ctx.slab == edata_slab_get(edata)); } if (likely(alloc_ctx.slab)) { /* Small allocation. */ arena_dalloc_small(tsdn, ptr); } else { arena_dalloc_large_no_tcache(tsdn, ptr, alloc_ctx.szind); } } JEMALLOC_ALWAYS_INLINE void arena_dalloc_large(tsdn_t *tsdn, void *ptr, tcache_t *tcache, szind_t szind, bool slow_path) { if (szind < nhbins) { if (config_prof && unlikely(szind < SC_NBINS)) { arena_dalloc_promoted(tsdn, ptr, tcache, slow_path); } else { tcache_dalloc_large(tsdn_tsd(tsdn), tcache, ptr, szind, slow_path); } } else { edata_t *edata = emap_edata_lookup(tsdn, &arena_emap_global, ptr); if (large_dalloc_safety_checks(edata, szind)) { /* See the comment in isfree. */ return; } large_dalloc(tsdn, edata); } } JEMALLOC_ALWAYS_INLINE void arena_dalloc(tsdn_t *tsdn, void *ptr, tcache_t *tcache, emap_alloc_ctx_t *caller_alloc_ctx, bool slow_path) { assert(!tsdn_null(tsdn) || tcache == NULL); assert(ptr != NULL); if (unlikely(tcache == NULL)) { arena_dalloc_no_tcache(tsdn, ptr); return; } emap_alloc_ctx_t alloc_ctx; if (caller_alloc_ctx != NULL) { alloc_ctx = *caller_alloc_ctx; } else { util_assume(!tsdn_null(tsdn)); emap_alloc_ctx_lookup(tsdn, &arena_emap_global, ptr, &alloc_ctx); } if (config_debug) { edata_t *edata = emap_edata_lookup(tsdn, &arena_emap_global, ptr); assert(alloc_ctx.szind == edata_szind_get(edata)); assert(alloc_ctx.szind < SC_NSIZES); assert(alloc_ctx.slab == edata_slab_get(edata)); } if (likely(alloc_ctx.slab)) { /* Small allocation. */ tcache_dalloc_small(tsdn_tsd(tsdn), tcache, ptr, alloc_ctx.szind, slow_path); } else { arena_dalloc_large(tsdn, ptr, tcache, alloc_ctx.szind, slow_path); } } static inline void arena_sdalloc_no_tcache(tsdn_t *tsdn, void *ptr, size_t size) { assert(ptr != NULL); assert(size <= SC_LARGE_MAXCLASS); emap_alloc_ctx_t alloc_ctx; if (!config_prof || !opt_prof) { /* * There is no risk of being confused by a promoted sampled * object, so base szind and slab on the given size. */ alloc_ctx.szind = sz_size2index(size); alloc_ctx.slab = (alloc_ctx.szind < SC_NBINS); } if ((config_prof && opt_prof) || config_debug) { emap_alloc_ctx_lookup(tsdn, &arena_emap_global, ptr, &alloc_ctx); assert(alloc_ctx.szind == sz_size2index(size)); assert((config_prof && opt_prof) || alloc_ctx.slab == (alloc_ctx.szind < SC_NBINS)); if (config_debug) { edata_t *edata = emap_edata_lookup(tsdn, &arena_emap_global, ptr); assert(alloc_ctx.szind == edata_szind_get(edata)); assert(alloc_ctx.slab == edata_slab_get(edata)); } } if (likely(alloc_ctx.slab)) { /* Small allocation. */ arena_dalloc_small(tsdn, ptr); } else { arena_dalloc_large_no_tcache(tsdn, ptr, alloc_ctx.szind); } } JEMALLOC_ALWAYS_INLINE void arena_sdalloc(tsdn_t *tsdn, void *ptr, size_t size, tcache_t *tcache, emap_alloc_ctx_t *caller_alloc_ctx, bool slow_path) { assert(!tsdn_null(tsdn) || tcache == NULL); assert(ptr != NULL); assert(size <= SC_LARGE_MAXCLASS); if (unlikely(tcache == NULL)) { arena_sdalloc_no_tcache(tsdn, ptr, size); return; } emap_alloc_ctx_t alloc_ctx; if (config_prof && opt_prof) { if (caller_alloc_ctx == NULL) { /* Uncommon case and should be a static check. */ emap_alloc_ctx_lookup(tsdn, &arena_emap_global, ptr, &alloc_ctx); assert(alloc_ctx.szind == sz_size2index(size)); } else { alloc_ctx = *caller_alloc_ctx; } } else { /* * There is no risk of being confused by a promoted sampled * object, so base szind and slab on the given size. */ alloc_ctx.szind = sz_size2index(size); alloc_ctx.slab = (alloc_ctx.szind < SC_NBINS); } if (config_debug) { edata_t *edata = emap_edata_lookup(tsdn, &arena_emap_global, ptr); assert(alloc_ctx.szind == edata_szind_get(edata)); assert(alloc_ctx.slab == edata_slab_get(edata)); } if (likely(alloc_ctx.slab)) { /* Small allocation. */ tcache_dalloc_small(tsdn_tsd(tsdn), tcache, ptr, alloc_ctx.szind, slow_path); } else { arena_dalloc_large(tsdn, ptr, tcache, alloc_ctx.szind, slow_path); } } static inline void arena_cache_oblivious_randomize(tsdn_t *tsdn, arena_t *arena, edata_t *edata, size_t alignment) { assert(edata_base_get(edata) == edata_addr_get(edata)); if (alignment < PAGE) { unsigned lg_range = LG_PAGE - lg_floor(CACHELINE_CEILING(alignment)); size_t r; if (!tsdn_null(tsdn)) { tsd_t *tsd = tsdn_tsd(tsdn); r = (size_t)prng_lg_range_u64( tsd_prng_statep_get(tsd), lg_range); } else { uint64_t stack_value = (uint64_t)(uintptr_t)&r; r = (size_t)prng_lg_range_u64(&stack_value, lg_range); } uintptr_t random_offset = ((uintptr_t)r) << (LG_PAGE - lg_range); edata->e_addr = (void *)((uintptr_t)edata->e_addr + random_offset); assert(ALIGNMENT_ADDR2BASE(edata->e_addr, alignment) == edata->e_addr); } } #endif /* JEMALLOC_INTERNAL_ARENA_INLINES_B_H */
27.847191
79
0.714413
[ "object" ]
aaf4f8f9e7b2a8aee683c4a3527575d523c2fa9e
799
h
C
UltraSolver/UltraSolver/TableCT.h
cpresearchers/UltraSolver
6f63b63ede67ca4f5a42272368525fd32cc20dc0
[ "MIT" ]
null
null
null
UltraSolver/UltraSolver/TableCT.h
cpresearchers/UltraSolver
6f63b63ede67ca4f5a42272368525fd32cc20dc0
[ "MIT" ]
null
null
null
UltraSolver/UltraSolver/TableCT.h
cpresearchers/UltraSolver
6f63b63ede67ca4f5a42272368525fd32cc20dc0
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include "RSBitSet.h" #include "Propagator.h" #include "Var.h" #include "SearchHelper.h" namespace cp { using namespace std; class TableCT : public Propagator { public: vector<vector<int>> tuples; TableCT(const int id, const int arity, const int num_vars, vector<Var*> scope, vector<vector<int>>& tuples, shared_ptr<SearchHelper>&& helper); //检查变量 bool InitGAC(); bool UpdateTable(); bool FilterDomains(vector<Var*>& y); bool propagate(vector<Var*>& x_evt) override; void NewLevel() override; void BackLevel() override; private: int num_bit_; unique_ptr<RSBitSet> curr_table_; vector<vector<vector<u64>>> supports_; vector<vector<int>> residues_; vector<int> Ssup_; vector<int> Sval_; vector<int> last_size_; vector<int> old_size_; }; }
19.02381
108
0.724656
[ "vector" ]
aaf547a4393d4a85db89b3380f2c9a499b4d19b3
4,579
h
C
include/tool-humdiff.h
humdrum-tools/minHumdrum
1f1e6a1281b40a6d6c9fed6666d96221cd619dc0
[ "BSD-2-Clause" ]
null
null
null
include/tool-humdiff.h
humdrum-tools/minHumdrum
1f1e6a1281b40a6d6c9fed6666d96221cd619dc0
[ "BSD-2-Clause" ]
null
null
null
include/tool-humdiff.h
humdrum-tools/minHumdrum
1f1e6a1281b40a6d6c9fed6666d96221cd619dc0
[ "BSD-2-Clause" ]
null
null
null
// // Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu> // Creation Date: Mon Jul 29 11:38:01 CEST 2019 // Last Modified: Sat Aug 3 17:48:04 EDT 2019 // Filename: tool-humdiff.h // URL: https://github.com/craigsapp/humlib/blob/master/include/tool-humdiff.h // Syntax: C++11; humlib // vim: syntax=cpp ts=3 noexpandtab nowrap // // Description: Interface for humdiff (similarity matrix) tool. // #ifndef _TOOL_HUMDIFF_H_INCLUDED #define _TOOL_HUMDIFF_H_INCLUDED #include "HumTool.h" #include "HumdrumFile.h" #include "HumdrumFileSet.h" #include <iostream> namespace hum { // START_MERGE // A TimePoint records the event times in a file. These are positions of note attacks // in the file. The "index" variable keeps track of the line in the original file // (for the first position in index), and other positions in index keep track of the // equivalent line position of the timepoint in other file(s) that are being compared. class TimePoint { public: // file: pointers to the file in which the index refers to vector<HumdrumFile*> file; // index :: A list of indexes for the lines at which the given timestamp // occurs in each file. The first index is for the reference work. vector<int> index; // timestamp :: The duration from the start of the score to given time in score. HumNum timestamp = -1; // measure :: The measure number in which the timestamp occurs. int measure = -1; void clear(void) { file.clear(); index.clear(); timestamp = -1; measure = -1; } }; // NotePoint is a note from a score that will be matches hopefully to an // equivalent note in another score. class NotePoint { public: HTp token = NULL; // Humdrum token that contains note string subtoken; // string that represents not (token may be chord) int subindex = -1; // subtoken index of note (in chord) int measure = -1; // measure number that note is found HumNum measurequarter = -1; // distance from start of measure to note int track = -1; // track that note is from int layer = -1; // layer that note is in HumNum duration = -1; // duration (tied) of note int b40 = -1; // b40 pitch of note int processed = 0; // has note been processed/matched int sourceindex = -1; // source file index for note int tpindex = -1; // timepoint index of note in source vector<int> matched; // indexes to the location of the note in TimePoint list. // the index indicate which score the match is related to, // and a value of -1 means there is no equivalent timepoint. void clear(void) { token = NULL; subtoken = ""; subindex = -1; measure = -1; measurequarter = -1; track = -1; layer = -1; duration = -1; b40 = -1; processed = 0; sourceindex = -1; tpindex = -1; matched.clear(); } }; // Function declarations: class Tool_humdiff : public HumTool { public: Tool_humdiff (void); bool run (HumdrumFileSet& infiles); bool run (const string& indata1, const string& indata2, ostream& out); bool run (HumdrumFile& infile1, HumdrumFile& infile2, ostream& out); bool run (HumdrumFile& infile1, HumdrumFile& infile2); void processFile (HumdrumFile& infile1, HumdrumFile& infile2); void compareFiles (HumdrumFileSet& humset); ostream& compareTimePoints (ostream& out, vector<vector<TimePoint>>& timepoints, HumdrumFileSet& humset); void extractTimePoints (vector<TimePoint>& points, HumdrumFile& infile); ostream& printTimePoints (ostream& out, vector<TimePoint>& timepoints); void compareLines (HumNum minval, vector<int>& indexes, vector<vector<TimePoint>>& timepoints, HumdrumFileSet& humset); void getNoteList (vector<NotePoint>& notelist, HumdrumFile& infile, int line, int measure, int sourceindex, int tpindex); int findNoteInList (NotePoint& np, vector<NotePoint>& nps); void printNotePoints (vector<NotePoint>& notelist); void markNote (NotePoint& np); int m_marked = 0; }; ostream& operator<<(ostream& out, TimePoint& tp); ostream& operator<<(ostream& out, NotePoint& np); // END_MERGE } // end namespace hum #endif /* _TOOL_HUMDIFF_H_INCLUDED */
34.689394
134
0.632671
[ "vector" ]
aafb7349aaf066261d4235428f1ecc0bfe590799
22,807
c
C
ext/json/json.c
johannes/php-src
f8a2407655c29caf65f726a2cd4ad85e90bf3e08
[ "PHP-3.01" ]
null
null
null
ext/json/json.c
johannes/php-src
f8a2407655c29caf65f726a2cd4ad85e90bf3e08
[ "PHP-3.01" ]
null
null
null
ext/json/json.c
johannes/php-src
f8a2407655c29caf65f726a2cd4ad85e90bf3e08
[ "PHP-3.01" ]
null
null
null
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2012 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Omar Kilani <omar@php.net> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/html.h" #include "ext/standard/php_smart_str.h" #include "JSON_parser.h" #include "php_json.h" #include <zend_exceptions.h> static PHP_MINFO_FUNCTION(json); static PHP_FUNCTION(json_encode); static PHP_FUNCTION(json_decode); static PHP_FUNCTION(json_last_error); static PHP_FUNCTION(json_last_error_msg); static const char digits[] = "0123456789abcdef"; zend_class_entry *php_json_serializable_ce; ZEND_DECLARE_MODULE_GLOBALS(json) /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_json_encode, 0, 0, 1) ZEND_ARG_INFO(0, value) ZEND_ARG_INFO(0, options) ZEND_ARG_INFO(0, depth) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_json_decode, 0, 0, 1) ZEND_ARG_INFO(0, json) ZEND_ARG_INFO(0, assoc) ZEND_ARG_INFO(0, depth) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_json_last_error, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_json_last_error_msg, 0) ZEND_END_ARG_INFO() /* }}} */ /* {{{ json_functions[] */ static const zend_function_entry json_functions[] = { PHP_FE(json_encode, arginfo_json_encode) PHP_FE(json_decode, arginfo_json_decode) PHP_FE(json_last_error, arginfo_json_last_error) PHP_FE(json_last_error_msg, arginfo_json_last_error_msg) PHP_FE_END }; /* }}} */ /* {{{ JsonSerializable methods */ ZEND_BEGIN_ARG_INFO(json_serialize_arginfo, 0) /* No arguments */ ZEND_END_ARG_INFO(); static const zend_function_entry json_serializable_interface[] = { PHP_ABSTRACT_ME(JsonSerializable, jsonSerialize, json_serialize_arginfo) PHP_FE_END }; /* }}} */ /* {{{ MINIT */ static PHP_MINIT_FUNCTION(json) { zend_class_entry ce; INIT_CLASS_ENTRY(ce, "JsonSerializable", json_serializable_interface); php_json_serializable_ce = zend_register_internal_interface(&ce TSRMLS_CC); REGISTER_LONG_CONSTANT("JSON_HEX_TAG", PHP_JSON_HEX_TAG, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_HEX_AMP", PHP_JSON_HEX_AMP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_HEX_APOS", PHP_JSON_HEX_APOS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_HEX_QUOT", PHP_JSON_HEX_QUOT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_FORCE_OBJECT", PHP_JSON_FORCE_OBJECT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_NUMERIC_CHECK", PHP_JSON_NUMERIC_CHECK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_UNESCAPED_SLASHES", PHP_JSON_UNESCAPED_SLASHES, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_PRETTY_PRINT", PHP_JSON_PRETTY_PRINT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_UNESCAPED_UNICODE", PHP_JSON_UNESCAPED_UNICODE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_PARTIAL_OUTPUT_ON_ERROR", PHP_JSON_PARTIAL_OUTPUT_ON_ERROR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_ERROR_NONE", PHP_JSON_ERROR_NONE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_ERROR_DEPTH", PHP_JSON_ERROR_DEPTH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_ERROR_STATE_MISMATCH", PHP_JSON_ERROR_STATE_MISMATCH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_ERROR_CTRL_CHAR", PHP_JSON_ERROR_CTRL_CHAR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_ERROR_SYNTAX", PHP_JSON_ERROR_SYNTAX, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_ERROR_UTF8", PHP_JSON_ERROR_UTF8, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_ERROR_RECURSION", PHP_JSON_ERROR_RECURSION, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_ERROR_INF_OR_NAN", PHP_JSON_ERROR_INF_OR_NAN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_ERROR_UNSUPPORTED_TYPE", PHP_JSON_ERROR_UNSUPPORTED_TYPE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_OBJECT_AS_ARRAY", PHP_JSON_OBJECT_AS_ARRAY, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("JSON_BIGINT_AS_STRING", PHP_JSON_BIGINT_AS_STRING, CONST_CS | CONST_PERSISTENT); return SUCCESS; } /* }}} */ /* {{{ PHP_GINIT_FUNCTION */ static PHP_GINIT_FUNCTION(json) { json_globals->encoder_depth = 0; json_globals->error_code = 0; json_globals->encode_max_depth = 0; } /* }}} */ /* {{{ json_module_entry */ zend_module_entry json_module_entry = { STANDARD_MODULE_HEADER, "json", json_functions, PHP_MINIT(json), NULL, NULL, NULL, PHP_MINFO(json), PHP_JSON_VERSION, PHP_MODULE_GLOBALS(json), PHP_GINIT(json), NULL, NULL, STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ #ifdef COMPILE_DL_JSON ZEND_GET_MODULE(json) #endif /* {{{ PHP_MINFO_FUNCTION */ static PHP_MINFO_FUNCTION(json) { php_info_print_table_start(); php_info_print_table_row(2, "json support", "enabled"); php_info_print_table_row(2, "json version", PHP_JSON_VERSION); php_info_print_table_end(); } /* }}} */ static void json_escape_string(smart_str *buf, char *s, int len, int options TSRMLS_DC); static int json_determine_array_type(zval **val TSRMLS_DC) /* {{{ */ { int i; HashTable *myht = HASH_OF(*val); i = myht ? zend_hash_num_elements(myht) : 0; if (i > 0) { char *key; ulong index, idx; uint key_len; HashPosition pos; zend_hash_internal_pointer_reset_ex(myht, &pos); idx = 0; for (;; zend_hash_move_forward_ex(myht, &pos)) { i = zend_hash_get_current_key_ex(myht, &key, &key_len, &index, 0, &pos); if (i == HASH_KEY_NON_EXISTANT) { break; } if (i == HASH_KEY_IS_STRING) { return 1; } else { if (index != idx) { return 1; } } idx++; } } return PHP_JSON_OUTPUT_ARRAY; } /* }}} */ /* {{{ Pretty printing support functions */ static inline void json_pretty_print_char(smart_str *buf, int options, char c TSRMLS_DC) /* {{{ */ { if (options & PHP_JSON_PRETTY_PRINT) { smart_str_appendc(buf, c); } } /* }}} */ static inline void json_pretty_print_indent(smart_str *buf, int options TSRMLS_DC) /* {{{ */ { int i; if (options & PHP_JSON_PRETTY_PRINT) { for (i = 0; i < JSON_G(encoder_depth); ++i) { smart_str_appendl(buf, " ", 4); } } } /* }}} */ /* }}} */ static void json_encode_array(smart_str *buf, zval **val, int options TSRMLS_DC) /* {{{ */ { int i, r; HashTable *myht; if (Z_TYPE_PP(val) == IS_ARRAY) { myht = HASH_OF(*val); r = (options & PHP_JSON_FORCE_OBJECT) ? PHP_JSON_OUTPUT_OBJECT : json_determine_array_type(val TSRMLS_CC); } else { myht = Z_OBJPROP_PP(val); r = PHP_JSON_OUTPUT_OBJECT; } if (myht && myht->nApplyCount > 1) { JSON_G(error_code) = PHP_JSON_ERROR_RECURSION; smart_str_appendl(buf, "null", 4); return; } if (r == PHP_JSON_OUTPUT_ARRAY) { smart_str_appendc(buf, '['); } else { smart_str_appendc(buf, '{'); } json_pretty_print_char(buf, options, '\n' TSRMLS_CC); ++JSON_G(encoder_depth); i = myht ? zend_hash_num_elements(myht) : 0; if (i > 0) { char *key; zval **data; ulong index; uint key_len; HashPosition pos; HashTable *tmp_ht; int need_comma = 0; zend_hash_internal_pointer_reset_ex(myht, &pos); for (;; zend_hash_move_forward_ex(myht, &pos)) { i = zend_hash_get_current_key_ex(myht, &key, &key_len, &index, 0, &pos); if (i == HASH_KEY_NON_EXISTANT) break; if (zend_hash_get_current_data_ex(myht, (void **) &data, &pos) == SUCCESS) { tmp_ht = HASH_OF(*data); if (tmp_ht) { tmp_ht->nApplyCount++; } if (r == PHP_JSON_OUTPUT_ARRAY) { if (need_comma) { smart_str_appendc(buf, ','); json_pretty_print_char(buf, options, '\n' TSRMLS_CC); } else { need_comma = 1; } json_pretty_print_indent(buf, options TSRMLS_CC); php_json_encode(buf, *data, options TSRMLS_CC); } else if (r == PHP_JSON_OUTPUT_OBJECT) { if (i == HASH_KEY_IS_STRING) { if (key[0] == '\0' && Z_TYPE_PP(val) == IS_OBJECT) { /* Skip protected and private members. */ if (tmp_ht) { tmp_ht->nApplyCount--; } continue; } if (need_comma) { smart_str_appendc(buf, ','); json_pretty_print_char(buf, options, '\n' TSRMLS_CC); } else { need_comma = 1; } json_pretty_print_indent(buf, options TSRMLS_CC); json_escape_string(buf, key, key_len - 1, options & ~PHP_JSON_NUMERIC_CHECK TSRMLS_CC); smart_str_appendc(buf, ':'); json_pretty_print_char(buf, options, ' ' TSRMLS_CC); php_json_encode(buf, *data, options TSRMLS_CC); } else { if (need_comma) { smart_str_appendc(buf, ','); json_pretty_print_char(buf, options, '\n' TSRMLS_CC); } else { need_comma = 1; } json_pretty_print_indent(buf, options TSRMLS_CC); smart_str_appendc(buf, '"'); smart_str_append_long(buf, (long) index); smart_str_appendc(buf, '"'); smart_str_appendc(buf, ':'); json_pretty_print_char(buf, options, ' ' TSRMLS_CC); php_json_encode(buf, *data, options TSRMLS_CC); } } if (tmp_ht) { tmp_ht->nApplyCount--; } } } } if (JSON_G(encoder_depth) > JSON_G(encode_max_depth)) { JSON_G(error_code) = PHP_JSON_ERROR_DEPTH; } --JSON_G(encoder_depth); json_pretty_print_char(buf, options, '\n' TSRMLS_CC); json_pretty_print_indent(buf, options TSRMLS_CC); if (r == PHP_JSON_OUTPUT_ARRAY) { smart_str_appendc(buf, ']'); } else { smart_str_appendc(buf, '}'); } } /* }}} */ static int json_utf8_to_utf16(unsigned short *utf16, char utf8[], int len) /* {{{ */ { size_t pos = 0, us; int j, status; if (utf16) { /* really convert the utf8 string */ for (j=0 ; pos < len ; j++) { us = php_next_utf8_char((const unsigned char *)utf8, len, &pos, &status); if (status != SUCCESS) { return -1; } /* From http://en.wikipedia.org/wiki/UTF16 */ if (us >= 0x10000) { us -= 0x10000; utf16[j++] = (unsigned short)((us >> 10) | 0xd800); utf16[j] = (unsigned short)((us & 0x3ff) | 0xdc00); } else { utf16[j] = (unsigned short)us; } } } else { /* Only check if utf8 string is valid, and compute utf16 lenght */ for (j=0 ; pos < len ; j++) { us = php_next_utf8_char((const unsigned char *)utf8, len, &pos, &status); if (status != SUCCESS) { return -1; } if (us >= 0x10000) { j++; } } } return j; } /* }}} */ static void json_escape_string(smart_str *buf, char *s, int len, int options TSRMLS_DC) /* {{{ */ { int pos = 0, ulen = 0; unsigned short us; unsigned short *utf16; size_t newlen; if (len == 0) { smart_str_appendl(buf, "\"\"", 2); return; } if (options & PHP_JSON_NUMERIC_CHECK) { double d; int type; long p; if ((type = is_numeric_string(s, len, &p, &d, 0)) != 0) { if (type == IS_LONG) { smart_str_append_long(buf, p); } else if (type == IS_DOUBLE) { if (!zend_isinf(d) && !zend_isnan(d)) { char *tmp; int l = spprintf(&tmp, 0, "%.*k", (int) EG(precision), d); smart_str_appendl(buf, tmp, l); efree(tmp); } else { JSON_G(error_code) = PHP_JSON_ERROR_INF_OR_NAN; smart_str_appendc(buf, '0'); } } return; } } utf16 = (options & PHP_JSON_UNESCAPED_UNICODE) ? NULL : (unsigned short *) safe_emalloc(len, sizeof(unsigned short), 0); ulen = json_utf8_to_utf16(utf16, s, len); if (ulen <= 0) { if (utf16) { efree(utf16); } if (ulen < 0) { JSON_G(error_code) = PHP_JSON_ERROR_UTF8; smart_str_appendl(buf, "null", 4); } else { smart_str_appendl(buf, "\"\"", 2); } return; } if (!(options & PHP_JSON_UNESCAPED_UNICODE)) { len = ulen; } /* pre-allocate for string length plus 2 quotes */ smart_str_alloc(buf, len+2, 0); smart_str_appendc(buf, '"'); while (pos < len) { us = (options & PHP_JSON_UNESCAPED_UNICODE) ? s[pos++] : utf16[pos++]; switch (us) { case '"': if (options & PHP_JSON_HEX_QUOT) { smart_str_appendl(buf, "\\u0022", 6); } else { smart_str_appendl(buf, "\\\"", 2); } break; case '\\': smart_str_appendl(buf, "\\\\", 2); break; case '/': if (options & PHP_JSON_UNESCAPED_SLASHES) { smart_str_appendc(buf, '/'); } else { smart_str_appendl(buf, "\\/", 2); } break; case '\b': smart_str_appendl(buf, "\\b", 2); break; case '\f': smart_str_appendl(buf, "\\f", 2); break; case '\n': smart_str_appendl(buf, "\\n", 2); break; case '\r': smart_str_appendl(buf, "\\r", 2); break; case '\t': smart_str_appendl(buf, "\\t", 2); break; case '<': if (options & PHP_JSON_HEX_TAG) { smart_str_appendl(buf, "\\u003C", 6); } else { smart_str_appendc(buf, '<'); } break; case '>': if (options & PHP_JSON_HEX_TAG) { smart_str_appendl(buf, "\\u003E", 6); } else { smart_str_appendc(buf, '>'); } break; case '&': if (options & PHP_JSON_HEX_AMP) { smart_str_appendl(buf, "\\u0026", 6); } else { smart_str_appendc(buf, '&'); } break; case '\'': if (options & PHP_JSON_HEX_APOS) { smart_str_appendl(buf, "\\u0027", 6); } else { smart_str_appendc(buf, '\''); } break; default: if (us >= ' ' && ((options & PHP_JSON_UNESCAPED_UNICODE) || (us & 127) == us)) { smart_str_appendc(buf, (unsigned char) us); } else { smart_str_appendl(buf, "\\u", 2); smart_str_appendc(buf, digits[(us & 0xf000) >> 12]); smart_str_appendc(buf, digits[(us & 0xf00) >> 8]); smart_str_appendc(buf, digits[(us & 0xf0) >> 4]); smart_str_appendc(buf, digits[(us & 0xf)]); } break; } } smart_str_appendc(buf, '"'); if (utf16) { efree(utf16); } } /* }}} */ static void json_encode_serializable_object(smart_str *buf, zval *val, int options TSRMLS_DC) /* {{{ */ { zend_class_entry *ce = Z_OBJCE_P(val); zval *retval = NULL, fname; HashTable* myht; if (Z_TYPE_P(val) == IS_ARRAY) { myht = HASH_OF(val); } else { myht = Z_OBJPROP_P(val); } if (myht && myht->nApplyCount > 1) { JSON_G(error_code) = PHP_JSON_ERROR_RECURSION; smart_str_appendl(buf, "null", 4); return; } ZVAL_STRING(&fname, "jsonSerialize", 0); if (FAILURE == call_user_function_ex(EG(function_table), &val, &fname, &retval, 0, NULL, 1, NULL TSRMLS_CC) || !retval) { zend_throw_exception_ex(NULL, 0 TSRMLS_CC, "Failed calling %s::jsonSerialize()", ce->name); smart_str_appendl(buf, "null", sizeof("null") - 1); return; } if (EG(exception)) { /* Error already raised */ zval_ptr_dtor(&retval); smart_str_appendl(buf, "null", sizeof("null") - 1); return; } if ((Z_TYPE_P(retval) == IS_OBJECT) && (Z_OBJ_HANDLE_P(retval) == Z_OBJ_HANDLE_P(val))) { /* Handle the case where jsonSerialize does: return $this; by going straight to encode array */ json_encode_array(buf, &retval, options TSRMLS_CC); } else { /* All other types, encode as normal */ php_json_encode(buf, retval, options TSRMLS_CC); } zval_ptr_dtor(&retval); } /* }}} */ PHP_JSON_API void php_json_encode(smart_str *buf, zval *val, int options TSRMLS_DC) /* {{{ */ { switch (Z_TYPE_P(val)) { case IS_NULL: smart_str_appendl(buf, "null", 4); break; case IS_BOOL: if (Z_BVAL_P(val)) { smart_str_appendl(buf, "true", 4); } else { smart_str_appendl(buf, "false", 5); } break; case IS_LONG: smart_str_append_long(buf, Z_LVAL_P(val)); break; case IS_DOUBLE: { char *d = NULL; int len; double dbl = Z_DVAL_P(val); if (!zend_isinf(dbl) && !zend_isnan(dbl)) { len = spprintf(&d, 0, "%.*k", (int) EG(precision), dbl); smart_str_appendl(buf, d, len); efree(d); } else { JSON_G(error_code) = PHP_JSON_ERROR_INF_OR_NAN; smart_str_appendc(buf, '0'); } } break; case IS_STRING: json_escape_string(buf, Z_STRVAL_P(val), Z_STRLEN_P(val), options TSRMLS_CC); break; case IS_OBJECT: if (instanceof_function(Z_OBJCE_P(val), php_json_serializable_ce TSRMLS_CC)) { json_encode_serializable_object(buf, val, options TSRMLS_CC); break; } /* fallthrough -- Non-serializable object */ case IS_ARRAY: json_encode_array(buf, &val, options TSRMLS_CC); break; default: JSON_G(error_code) = PHP_JSON_ERROR_UNSUPPORTED_TYPE; smart_str_appendl(buf, "null", 4); break; } return; } /* }}} */ PHP_JSON_API void php_json_decode_ex(zval *return_value, char *str, int str_len, int options, long depth TSRMLS_DC) /* {{{ */ { int utf16_len; zval *z; unsigned short *utf16; JSON_parser jp; utf16 = (unsigned short *) safe_emalloc((str_len+1), sizeof(unsigned short), 1); utf16_len = json_utf8_to_utf16(utf16, str, str_len); if (utf16_len <= 0) { if (utf16) { efree(utf16); } JSON_G(error_code) = PHP_JSON_ERROR_UTF8; RETURN_NULL(); } if (depth <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Depth must be greater than zero"); efree(utf16); RETURN_NULL(); } ALLOC_INIT_ZVAL(z); jp = new_JSON_parser(depth); if (parse_JSON_ex(jp, z, utf16, utf16_len, options TSRMLS_CC)) { *return_value = *z; } else { double d; int type, overflow_info; long p; RETVAL_NULL(); if (str_len == 4) { if (!strcasecmp(str, "null")) { /* We need to explicitly clear the error because its an actual NULL and not an error */ jp->error_code = PHP_JSON_ERROR_NONE; RETVAL_NULL(); } else if (!strcasecmp(str, "true")) { RETVAL_BOOL(1); } } else if (str_len == 5 && !strcasecmp(str, "false")) { RETVAL_BOOL(0); } if ((type = is_numeric_string_ex(str, str_len, &p, &d, 0, &overflow_info)) != 0) { if (type == IS_LONG) { RETVAL_LONG(p); } else if (type == IS_DOUBLE) { if (options & PHP_JSON_BIGINT_AS_STRING && overflow_info) { /* Within an object or array, a numeric literal is assumed * to be an integer if and only if it's entirely made up of * digits (exponent notation will result in the number * being treated as a double). We'll match that behaviour * here. */ int i; zend_bool is_float = 0; for (i = (str[0] == '-' ? 1 : 0); i < str_len; i++) { /* Not using isdigit() because it's locale specific, * but we expect JSON input to always be UTF-8. */ if (str[i] < '0' || str[i] > '9') { is_float = 1; break; } } if (is_float) { RETVAL_DOUBLE(d); } else { RETVAL_STRINGL(str, str_len, 1); } } else { RETVAL_DOUBLE(d); } } } if (Z_TYPE_P(return_value) != IS_NULL) { jp->error_code = PHP_JSON_ERROR_NONE; } zval_dtor(z); } FREE_ZVAL(z); efree(utf16); JSON_G(error_code) = jp->error_code; free_JSON_parser(jp); } /* }}} */ /* {{{ proto string json_encode(mixed data [, int options[, int depth]]) Returns the JSON representation of a value */ static PHP_FUNCTION(json_encode) { zval *parameter; smart_str buf = {0}; long options = 0; long depth = JSON_PARSER_DEFAULT_DEPTH; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|ll", &parameter, &options, &depth) == FAILURE) { return; } JSON_G(error_code) = PHP_JSON_ERROR_NONE; JSON_G(encode_max_depth) = depth; php_json_encode(&buf, parameter, options TSRMLS_CC); if (JSON_G(error_code) != PHP_JSON_ERROR_NONE && !(options & PHP_JSON_PARTIAL_OUTPUT_ON_ERROR)) { ZVAL_FALSE(return_value); } else { ZVAL_STRINGL(return_value, buf.c, buf.len, 1); } smart_str_free(&buf); } /* }}} */ /* {{{ proto mixed json_decode(string json [, bool assoc [, long depth]]) Decodes the JSON representation into a PHP value */ static PHP_FUNCTION(json_decode) { char *str; int str_len; zend_bool assoc = 0; /* return JS objects as PHP objects by default */ long depth = JSON_PARSER_DEFAULT_DEPTH; long options = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|bll", &str, &str_len, &assoc, &depth, &options) == FAILURE) { return; } JSON_G(error_code) = 0; if (!str_len) { RETURN_NULL(); } /* For BC reasons, the bool $assoc overrides the long $options bit for PHP_JSON_OBJECT_AS_ARRAY */ if (assoc) { options |= PHP_JSON_OBJECT_AS_ARRAY; } else { options &= ~PHP_JSON_OBJECT_AS_ARRAY; } php_json_decode_ex(return_value, str, str_len, options, depth TSRMLS_CC); } /* }}} */ /* {{{ proto int json_last_error() Returns the error code of the last json_encode() or json_decode() call. */ static PHP_FUNCTION(json_last_error) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(JSON_G(error_code)); } /* }}} */ /* {{{ proto string json_last_error_msg() Returns the error string of the last json_encode() or json_decode() call. */ static PHP_FUNCTION(json_last_error_msg) { if (zend_parse_parameters_none() == FAILURE) { return; } switch(JSON_G(error_code)) { case PHP_JSON_ERROR_NONE: RETURN_STRING("No error", 1); case PHP_JSON_ERROR_DEPTH: RETURN_STRING("Maximum stack depth exceeded", 1); case PHP_JSON_ERROR_STATE_MISMATCH: RETURN_STRING("State mismatch (invalid or malformed JSON)", 1); case PHP_JSON_ERROR_CTRL_CHAR: RETURN_STRING("Control character error, possibly incorrectly encoded", 1); case PHP_JSON_ERROR_SYNTAX: RETURN_STRING("Syntax error", 1); case PHP_JSON_ERROR_UTF8: RETURN_STRING("Malformed UTF-8 characters, possibly incorrectly encoded", 1); case PHP_JSON_ERROR_RECURSION: RETURN_STRING("Recursion detected", 1); case PHP_JSON_ERROR_INF_OR_NAN: RETURN_STRING("Inf and NaN cannot be JSON encoded", 1); case PHP_JSON_ERROR_UNSUPPORTED_TYPE: RETURN_STRING("Type is not supported", 1); default: RETURN_STRING("Unknown error", 1); } } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
26.124857
125
0.653001
[ "object" ]
aafd0c8726b299126c4aaa4584a109a043fadcf3
5,563
h
C
DEVELOPER/core/Element.h
steva44/OpenSees
417c3be117992a108c6bbbcf5c9b63806b9362ab
[ "TCL" ]
8
2019-03-05T16:25:10.000Z
2020-04-17T14:12:03.000Z
DEVELOPER/core/Element.h
steva44/OpenSees
417c3be117992a108c6bbbcf5c9b63806b9362ab
[ "TCL" ]
null
null
null
DEVELOPER/core/Element.h
steva44/OpenSees
417c3be117992a108c6bbbcf5c9b63806b9362ab
[ "TCL" ]
3
2019-09-21T03:11:11.000Z
2020-01-19T07:29:37.000Z
/* ****************************************************************** ** ** OpenSees - Open System for Earthquake Engineering Simulation ** ** Pacific Earthquake Engineering Research Center ** ** ** ** ** ** (C) Copyright 1999, The Regents of the University of California ** ** All Rights Reserved. ** ** ** ** Commercial use of this program without express permission of the ** ** University of California, Berkeley, is strictly prohibited. See ** ** file 'COPYRIGHT' in main directory for information on usage and ** ** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. ** ** ** ** Developed by: ** ** Frank McKenna (fmckenna@ce.berkeley.edu) ** ** Gregory L. Fenves (fenves@ce.berkeley.edu) ** ** Filip C. Filippou (filippou@ce.berkeley.edu) ** ** ** ** ****************************************************************** */ // $Revision: 1.19 $ // $Date: 2009-08-25 22:32:08 $ // $Source: /usr/local/cvs/OpenSees/SRC/element/Element.h,v $ // Written: fmk // Created: 11/96 // Revision: A // // Description: This file contains the class definition for Element. // Element is an abstract base class and thus no objects of it's type // can be instantiated. It has pure virtual functions which must be // implemented in it's derived classes. // // What: "@(#) Element.h, revA" #ifndef Element_h #define Element_h #include <DomainComponent.h> #include <ID.h> class Matrix; class Vector; class Info; class Response; class ElementalLoad; class Node; class Element : public DomainComponent { public: Element(int tag, int classTag); virtual ~Element(); // methods dealing with nodes and number of external dof virtual int getNumExternalNodes(void) const =0; virtual const ID &getExternalNodes(void) =0; virtual Node **getNodePtrs(void) =0; virtual int getNumDOF(void) =0; virtual double getCharacteristicLength(void); // methods dealing with committed state and update virtual int commitState(void); virtual int revertToLastCommit(void) = 0; virtual int revertToStart(void); virtual int update(void); virtual bool isSubdomain(void); // methods to return the current linearized stiffness, // damping and mass matrices virtual const Matrix &getTangentStiff(void) =0; virtual const Matrix &getInitialStiff(void) =0; virtual const Matrix &getDamp(void); virtual const Matrix &getMass(void); virtual const Matrix &getGeometricTangentStiff(); // methods for applying loads virtual void zeroLoad(void); virtual int addLoad(ElementalLoad *theLoad, double loadFactor); virtual int addLoad(ElementalLoad *theLoad, const Vector &loadFactors); virtual int addInertiaLoadToUnbalance(const Vector &accel); virtual int setRayleighDampingFactors(double alphaM, double betaK, double betaK0, double betaKc); // methods for obtaining resisting force (force includes elemental loads) virtual const Vector &getResistingForce(void) =0; virtual const Vector &getResistingForceIncInertia(void); // method for obtaining information specific to an element virtual Response *setResponse(const char **argv, int argc, OPS_Stream &theHandler); virtual int getResponse(int responseID, Information &eleInformation); virtual int getResponseSensitivity(int responseID, int gradIndex, Information &eleInformation); virtual int displaySelf(Renderer &, int mode, float fact, const char **displayModes=0, int numModes=0); // AddingSensitivity:BEGIN ////////////////////////////////////////// virtual int addInertiaLoadSensitivityToUnbalance(const Vector &accel, bool tag); virtual const Vector & getResistingForceSensitivity(int gradIndex); virtual const Matrix & getTangentStiffSensitivity(int gradIndex); virtual const Matrix & getInitialStiffSensitivity(int gradIndex); virtual const Matrix & getCommittedStiffSensitivity(int gradIndex); virtual const Matrix & getDampSensitivity(int gradIndex); virtual const Matrix & getMassSensitivity(int gradIndex); virtual int commitSensitivity(int gradIndex, int numGrads); // AddingSensitivity:END /////////////////////////////////////////// virtual int addResistingForceToNodalReaction(int flag); virtual int storePreviousK(int numK); virtual const Matrix *getPreviousK(int num); protected: const Vector &getRayleighDampingForces(void); double alphaM, betaK, betaK0, betaKc; Matrix *Kc; // pointer to hold last committed matrix if needed for rayleigh damping Matrix **previousK; int numPreviousK; int index, nodeIndex; static Matrix ** theMatrices; static Vector ** theVectors1; static Vector ** theVectors2; static int numMatrices; private: }; #endif
40.904412
107
0.591587
[ "vector" ]
c90675f7587ec8a602191968498f97f97d49f16f
9,949
c
C
system_config/sk_pic32_mx/system_init.c
pst69de/PIC32USBUSARTCtl
9176787be905f80b8f289519083d0427cac26355
[ "CC0-1.0" ]
null
null
null
system_config/sk_pic32_mx/system_init.c
pst69de/PIC32USBUSARTCtl
9176787be905f80b8f289519083d0427cac26355
[ "CC0-1.0" ]
null
null
null
system_config/sk_pic32_mx/system_init.c
pst69de/PIC32USBUSARTCtl
9176787be905f80b8f289519083d0427cac26355
[ "CC0-1.0" ]
null
null
null
/* * File: system_init.c * Author: patrick * * Created on 2014-09-13 */ // PIC32MX250F128B Configuration Bit Settings // 'C' source line config statements #include <xc.h> /* see configuration_bits.cpp #ifndef __cplusplus // DEVCFG3 // USERID = No Setting #pragma config PMDL1WAY = OFF // Peripheral Module Disable Configuration (Allow multiple reconfigurations) #pragma config IOL1WAY = OFF // Peripheral Pin Select Configuration (Allow multiple reconfigurations) #pragma config FUSBIDIO = OFF // USB USID Selection (Controlled by Port Function) #pragma config FVBUSONIO = OFF // USB VBUS ON Selection (Controlled by Port Function) // DEVCFG2 #pragma config FPLLIDIV = DIV_2 // PLL Input Divider (2x Divider) #pragma config FPLLMUL = MUL_24 // PLL Multiplier (24x Multiplier) #pragma config UPLLIDIV = DIV_2 // USB PLL Input Divider (2x Divider) #pragma config UPLLEN = ON // USB PLL Enable (Enabled) #pragma config FPLLODIV = DIV_4 // System PLL Output Clock Divider (PLL Divide by 4) // DEVCFG1 #pragma config FNOSC = PRIPLL // Oscillator Selection Bits (Primary Osc (XT,HS,EC)) #pragma config FSOSCEN = OFF // Secondary Oscillator Enable (Disabled) #pragma config IESO = ON // Internal/External Switch Over (Enabled) #pragma config POSCMOD = XT // Primary Oscillator Configuration (XT osc mode) #pragma config OSCIOFNC = OFF // CLKO Output Signal Active on the OSCO Pin (Disabled) #pragma config FPBDIV = DIV_1 // Peripheral Clock Divisor (Pb_Clk is Sys_Clk/1) #pragma config FCKSM = CSDCMD // Clock Switching and Monitor Selection (Clock Switch Disable, FSCM Disabled) #pragma config WDTPS = PS1048576 // Watchdog Timer Postscaler (1:1048576) #pragma config WINDIS = OFF // Watchdog Timer Window Enable (Watchdog Timer is in Non-Window Mode) #pragma config FWDTEN = OFF // Watchdog Timer Enable (WDT Enabled) #pragma config FWDTWINSZ = WINSZ_25 // Watchdog Timer Window Size (Window Size is 25%) // DEVCFG0 #pragma config JTAGEN = OFF // JTAG Enable (JTAG Disabled) #pragma config ICESEL = ICS_PGx1 // ICE/ICD Comm Channel Select (Communicate on PGEC1/PGED1) #pragma config PWP = OFF // Program Flash Write Protect (Disable) #pragma config BWP = OFF // Boot Flash Write Protect bit (Protection Disabled) #pragma config CP = OFF // Code Protect (Protection Disabled) #endif // ifndef __cplusplus */ #include "system_init.h" #include "system_config.h" #ifdef APP_USE_USB //#include "usb/usb_device.h" #include "../../POEusb.h" #endif // -> only needed for USB migrated as usbDevObject to POEusb // Global allocation of structure to hold system objects handles //SYSTEM_OBJECTS sysObjects; // -> USB stuff migrated to POEusb void TMR_Initialize(void) { // Timer1 System Clock // Stop the timer PLIB_TMR_Stop(APP_TMR_CLOCK); // Set the prescaler, and set the clock source as internal PLIB_TMR_PrescaleSelect(APP_TMR_CLOCK, APP_TMR_CLKPRESCALE); PLIB_TMR_ClockSourceSelect(APP_TMR_CLOCK, TMR_CLOCK_SOURCE_PERIPHERAL_CLOCK); // Clear the timer PLIB_TMR_Counter16BitClear(APP_TMR_CLOCK); // and preset interval PLIB_TMR_Period16BitSet(APP_TMR_CLOCK, APP_TMR_CLKINTERVAL); } void LEDS_Initialize(void) { // red LED LEDR_Clear; LEDR_Direction; LEDR_Mode; LEDR_Remap; LEDR_OD; // yellow LED LEDY_Clear; LEDY_Direction; LEDY_Mode; LEDY_Remap; LEDY_OD; // green LED LEDG_Clear; LEDG_Direction; LEDG_Mode; LEDG_Remap; LEDG_OD; // blue LED LEDB_Clear; LEDB_Direction; LEDB_Mode; LEDB_Remap; LEDB_OD; // white LED LEDW_Clear; LEDW_Direction; LEDW_Mode; LEDW_Remap; LEDW_OD; } #ifdef APP_USE_UART void UART_Initialize(void) { // UART 2 RX PLIB_USART_Disable(APP_UART_RX_ID); // Prepare Port PLIB_PORTS_PinClear(APP_UART_RX_PORTS_ID, APP_UART_RX_PORT_CHANNEL, APP_UART_RX_PORT_PIN); PLIB_PORTS_PinDirectionInputSet(APP_UART_RX_PORTS_ID, APP_UART_RX_PORT_CHANNEL, APP_UART_RX_PORT_PIN); PLIB_PORTS_RemapInput(APP_UART_RX_PORTS_ID, APP_UART_RX_REMAP_FUNC, APP_UART_RX_REMAP_PIN); // vv TX on same UART // UART 2 TX // Prepare Port PLIB_PORTS_PinClear(APP_UART_TX_PORTS_ID, APP_UART_TX_PORT_CHANNEL, APP_UART_TX_PORT_PIN); PLIB_PORTS_PinDirectionOutputSet(APP_UART_TX_PORTS_ID, APP_UART_TX_PORT_CHANNEL, APP_UART_TX_PORT_PIN); PLIB_PORTS_RemapOutput(APP_UART_TX_PORTS_ID, APP_UART_TX_REMAP_FUNC, APP_UART_TX_REMAP_PIN); PLIB_PORTS_PinSet(APP_UART_TX_PORTS_ID, APP_UART_TX_PORT_CHANNEL, APP_UART_TX_PORT_PIN); // ^^ TX on same UART // UART (RX/TX) Config PLIB_USART_OperationModeSelect(APP_UART_RX_ID, APP_UART_RX_OPER); PLIB_USART_HandshakeModeSelect(APP_UART_RX_ID, APP_UART_RX_HAND); PLIB_USART_BaudRateSet(APP_UART_RX_ID, APP_PBCLK_FREQ, APP_UART_RX_BAUD); // Select 8 data bits, No parity and one stop bit PLIB_USART_LineControlModeSelect(APP_UART_RX_ID, APP_UART_RX_MODE); // vv TX on same UART PLIB_USART_TransmitterInterruptModeSelect(APP_UART_TX_ID, USART_TRANSMIT_FIFO_EMPTY); // ^^ TX on same UART PLIB_USART_ReceiverInterruptModeSelect(APP_UART_RX_ID, USART_RECEIVE_FIFO_ONE_CHAR); //// UART 1 TX //PLIB_USART_Disable(APP_UART_TX_ID); //// Prepare Port //PLIB_PORTS_PinClear(APP_UART_TX_PORTS_ID, APP_UART_TX_PORT_CHANNEL, APP_UART_TX_PORT_PIN); //PLIB_PORTS_PinDirectionOutputSet(APP_UART_TX_PORTS_ID, APP_UART_TX_PORT_CHANNEL, APP_UART_TX_PORT_PIN); //PLIB_PORTS_RemapOutput(APP_UART_TX_PORTS_ID, APP_UART_TX_REMAP_FUNC, APP_UART_TX_REMAP_PIN); //// UART (TX) Config //PLIB_USART_OperationModeSelect(APP_UART_TX_ID, APP_UART_TX_OPER); //PLIB_USART_HandshakeModeSelect(APP_UART_TX_ID, APP_UART_TX_HAND); //PLIB_USART_BaudRateSet(APP_UART_TX_ID, APP_PBCLK_FREQ, APP_UART_TX_BAUD); //// Select 8 data bits, No parity and one stop bit //PLIB_USART_LineControlModeSelect(APP_UART_TX_ID, APP_UART_TX_MODE); //PLIB_USART_TransmitterInterruptModeSelect(APP_UART_TX_ID, UART_TRANSMIT_FIFO_EMPTY); // enabling UARTs in SYS_Startup } #endif // of ifdef APP_USE_UART void INT_Initialize(void) { // enable the multi vector PLIB_INT_MultiVectorSelect( APP_INT_ID ); #ifdef APP_USE_USB // set priority and enable USB1 PLIB_INT_VectorPrioritySet(APP_INT_ID, INT_VECTOR_USB1, INT_PRIORITY_LEVEL5); PLIB_INT_VectorSubPrioritySet(APP_INT_ID, INT_VECTOR_USB1, INT_SUBPRIORITY_LEVEL0); #endif // of ifdef APP_USE_USB // set priority LCD APP_LCD_InterruptPriority(APP_INT_ID); // set priority and enable Timer1 PLIB_INT_VectorPrioritySet(APP_INT_ID, INT_VECTOR_T1, INT_PRIORITY_LEVEL3); PLIB_INT_VectorSubPrioritySet(APP_INT_ID, INT_VECTOR_T1, INT_SUBPRIORITY_LEVEL0); #ifdef APP_USE_UART // set priority and enable UART RX PLIB_INT_VectorPrioritySet(APP_INT_ID, INT_VECTOR_UART2, INT_PRIORITY_LEVEL2); PLIB_INT_VectorSubPrioritySet(APP_INT_ID, INT_VECTOR_UART2, INT_SUBPRIORITY_LEVEL0); // set priority and enable UART TX PLIB_INT_VectorPrioritySet(APP_INT_ID, INT_VECTOR_UART1, INT_PRIORITY_LEVEL1); PLIB_INT_VectorSubPrioritySet(APP_INT_ID, INT_VECTOR_UART1, INT_SUBPRIORITY_LEVEL0); #endif // of ifdef APP_USE_UART // Enable the global interrupts PLIB_INT_Enable(APP_INT_ID); #ifdef APP_USE_USB PLIB_INT_SourceEnable(APP_INT_ID, INT_SOURCE_USB_1); #endif APP_LCD_InterruptEnable(APP_INT_ID); PLIB_INT_SourceEnable(APP_INT_ID, INT_SOURCE_TIMER_1); #ifdef APP_USE_UART PLIB_INT_SourceEnable(APP_INT_ID, INT_SOURCE_USART_2_ERROR); // vv TX on same UART PLIB_INT_SourceEnable(APP_INT_ID, INT_SOURCE_USART_2_TRANSMIT); // ^^ TX on same UART PLIB_INT_SourceEnable(APP_INT_ID, INT_SOURCE_USART_2_RECEIVE); //PLIB_INT_SourceEnable(APP_INT_ID, INT_SOURCE_UART_1_ERROR); //PLIB_INT_SourceEnable(APP_INT_ID, INT_SOURCE_UART_1_TRANSMIT); #endif } void SYS_Startup(void) { // LCD I2C com APP_LCD_SYS_Startup(APP_INT_ID); // system clock PLIB_INT_SourceFlagClear(APP_INT_ID, INT_SOURCE_TIMER_1); PLIB_TMR_Start(APP_TMR_CLOCK); #ifdef APP_USE_UART // enable UARTs //PLIB_INT_SourceFlagClear(APP_INT_ID, INT_SOURCE_UART_1_ERROR); //PLIB_INT_SourceFlagClear(APP_INT_ID, INT_SOURCE_UART_1_TRANSMIT); //PLIB_UART_Enable(APP_UART_TX_ID); //PLIB_UART_TransmitterEnable(APP_UART_TX_ID); // if there is a hardware shortcut Transmitter should be ready before Receiver PLIB_INT_SourceFlagClear(APP_INT_ID, INT_SOURCE_USART_2_ERROR); // vv TX on same UART PLIB_INT_SourceFlagClear(APP_INT_ID, INT_SOURCE_USART_2_TRANSMIT); // ^^ TX on same UART PLIB_INT_SourceFlagClear(APP_INT_ID, INT_SOURCE_USART_2_RECEIVE); // Transmitter should be disabled as long there is no data to send // this also keeps the TX under PORT control, // which should provide a high signal for the line PLIB_USART_TransmitterDisable(APP_UART_TX_ID); PLIB_USART_Enable(APP_UART_RX_ID); //PLIB_UART_ReceiverEnable(APP_UART_RX_ID); #endif } /* Initialize the System */ void SYS_Initialize ( void *data ) { // Initialize all modules and the application // Timer initializations TMR_Initialize(); // Set outputting Ports to Output (default is Input), clear analog Input LEDS_Initialize(); #ifdef APP_USE_USB USB_SYS_Init(); #endif // init LCD APP_LCD_Initialize(APP_PBCLK_FREQ); #ifdef APP_USE_UART // init UART UART_Initialize(); #endif #ifdef APP_USE_ADC ADC_Initialize(); #endif // Initialize the Application APP_Initialize(); // Initialize the interrupt system (after all other init's) INT_Initialize(); // startup system SYS_Startup(); }
39.796
118
0.742688
[ "vector" ]
c906fc5b2dfc1c0d134f7136fa2f309d4bbbef9c
2,958
h
C
Libs/AudioFile/libaudiofile/modules/Module.h
drunkfly/retrotoolkit
38fc08ce931339948d697a4dcf6f2441bccef7d6
[ "MIT", "Unlicense" ]
3
2021-04-17T11:32:36.000Z
2022-01-03T17:51:27.000Z
Libs/AudioFile/libaudiofile/modules/Module.h
drunkfly/retrotoolkit
38fc08ce931339948d697a4dcf6f2441bccef7d6
[ "MIT", "Unlicense" ]
null
null
null
Libs/AudioFile/libaudiofile/modules/Module.h
drunkfly/retrotoolkit
38fc08ce931339948d697a4dcf6f2441bccef7d6
[ "MIT", "Unlicense" ]
null
null
null
/* Audio File Library Copyright (C) 2000, Silicon Graphics, Inc. Copyright (C) 2010, Michael Pruett <michael@68k.org> 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 Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef MODULE_H #define MODULE_H #include "AudioFormat.h" #include "Shared.h" #include "afinternal.h" #include <vector> enum FormatCode { kUndefined = -1, kInt8, kInt16, kInt24, kInt32, kFloat, kDouble, }; class Chunk : public Shared<Chunk> { public: void *buffer; size_t frameCount; AudioFormat f; bool ownsMemory; Chunk() : buffer(NULL), frameCount(0), ownsMemory(false) { } ~Chunk() { deallocate(); } void allocate(size_t capacity) { deallocate(); ownsMemory = true; buffer = ::operator new(capacity); } void deallocate() { if (ownsMemory) ::operator delete(buffer); ownsMemory = false; buffer = NULL; } }; class Module : public Shared<Module> { public: Module(); virtual ~Module(); void setSink(Module *); void setSource(Module *); Chunk *inChunk() const { return m_inChunk.get(); } void setInChunk(Chunk *chunk) { m_inChunk = chunk; } Chunk *outChunk() const { return m_outChunk.get(); } void setOutChunk(Chunk *chunk) { m_outChunk = chunk; } virtual const char *name() const; /* Set format of m_outChunk based on how this module transforms m_inChunk. */ virtual void describe(); /* Set frame count of m_inChunk to the maximum number of frames needed to produce frame count of m_outChunk. */ virtual void maxPull(); /* Set frame count of m_outChunk to the maximum number of frames needed to produce frame count of m_inChunk. */ virtual void maxPush(); virtual void runPull(); virtual void reset1() { } virtual void reset2() { } virtual void runPush(); virtual void sync1() { } virtual void sync2() { } protected: SharedPtr<Chunk> m_inChunk, m_outChunk; union { Module *m_sink; Module *m_source; }; void pull(size_t frames); void push(size_t frames); }; /* _AF_ATOMIC_NVFRAMES is NOT the maximum number of frames a module can be requested to produce. This IS the maximum number of virtual (user) frames that will be produced or processed per run of the modules. Modules can be requested more frames than this because of rate conversion and rebuffering. */ #define _AF_ATOMIC_NVFRAMES 1024 #endif // MODULE_H
22.580153
73
0.724476
[ "vector" ]
c909e2d44d4cf2bc0fa620a5f5429081120a6371
10,641
c
C
toolbox/mex/gen_matrices_2d.c
brennengreen/NIRFAST-Parallel
9ee2a40d039cbfcaf03acea82e91e25d350cc0a5
[ "BSD-3-Clause" ]
22
2017-03-30T06:41:50.000Z
2021-09-23T08:17:37.000Z
toolbox/mex/gen_matrices_2d.c
brennengreen/NIRFAST-Parallel
9ee2a40d039cbfcaf03acea82e91e25d350cc0a5
[ "BSD-3-Clause" ]
12
2016-02-24T20:20:01.000Z
2021-03-15T13:21:33.000Z
toolbox/mex/gen_matrices_2d.c
brennengreen/NIRFAST-Parallel
9ee2a40d039cbfcaf03acea82e91e25d350cc0a5
[ "BSD-3-Clause" ]
17
2017-01-06T07:11:33.000Z
2021-08-10T07:15:24.000Z
#include <stdio.h> #include <math.h> #include <mex.h> /* Calculates local matrices for FEM process to make overall matrix * * Part of NIRFAST package * H Dehghani * Last Updated - 7/13/09 M Jermyn */ double gradphi(double g[3][2], double kappa[3], double val[3][3]); double phidotphi(double g[3][2], double mua[3], double val[3][3]); double boundary_int(double g[3][2], double bnd_index[3], \ double ksir[3], double valr[2][2]); double bound2(double g[2][2], int il, int im, double ksir[2], double *val); /* -------- Heart of the mex file----------- */ void mainloop(double *nodes, double *elements, double *bndvtx, double *mua, double *kappa, double *ksir, double *c, double *omega, int nodem, int noden, int elemm, int elemn, double *I, double *J, double *Sr, double *Si) { int ele, i, j, index[3], k; double indextmp, tri_vtx[3][2]; double bnd_index[3], kappa_index[3], mua_index[3], c_index[3]; double k_val[3][3], c_val[3][3], b_val[3][3], f_valr[2][2]; double ksir_index[3]; k = 0; for (ele=0; ele<elemm; ++ele){ for (i=0; i<elemn; ++i){ indextmp = *(elements+(ele+(i*elemm))); index[i] = indextmp; } for (i=0; i<elemn; ++i){ kappa_index[i] = *(kappa+(index[i]-1)); mua_index[i] = *(mua+(index[i]-1)); c_index[i] = *omega / *(c+(index[i]-1)) * -1; bnd_index[i] = *(bndvtx+(index[i]-1)); ksir_index[i] = *(ksir+(index[i]-1)); for (j=0; j<noden; ++j){ tri_vtx[i][j] = *(nodes+(index[i]-1+(j*nodem))); } } gradphi(tri_vtx,kappa_index,k_val); phidotphi(tri_vtx,mua_index,c_val); phidotphi(tri_vtx,c_index,b_val); for (i=0; i<3; ++i){ for (j=0; j<3; ++j){ I[k] = index[i]; J[k] = index[j]; Sr[k] = k_val[j][i]+c_val[j][i]; Si[k] = b_val[j][i]; ++k; } } if (bnd_index[0]+bnd_index[1]+bnd_index[2] != 0){ boundary_int(tri_vtx, bnd_index, ksir_index, f_valr); if (bnd_index[0]==1 && bnd_index[2]==1){ int index1[2]; index1[0] = index[0]; index1[1] = index[2]; for (i=0; i<2; ++i){ for (j=0; j<=i; ++j){ I[k] = index1[i]; J[k] = index1[j]; Sr[k] = f_valr[i][j]; Si[k] = 0.0; ++k; } } } else if (bnd_index[0]==1 && bnd_index[1]==1){ int index1[2]; index1[0] = index[0]; index1[1] = index[1]; for (i=0; i<2; ++i){ for (j=0; j<=i; ++j){ I[k] = index1[i]; J[k] = index1[j]; Sr[k] = f_valr[i][j]; Si[k] = 0.0; ++k; } } } else if (bnd_index[1]==1 && bnd_index[2]==1){ int index1[2]; index1[0] = index[1]; index1[1] = index[2]; for (i=0; i<2; ++i){ for (j=0; j<=i; ++j){ I[k] = index1[i]; J[k] = index1[j]; Sr[k] = f_valr[i][j]; Si[k] = 0.0; ++k; } } } } } return; } double gradphi(double g[3][2], double kappa[3], double val[3][3]) { int ii, jj; static int L[2][3] = {{-1.0,1.0,0.0}, \ {-1.0,0.0,1.0}}; static double w[3] = {1.0/6.0,1.0/6.0,1.0/6.0}; static double ip[3][2] = {{1.0/2.0,0.0},{1.0/2.0,1.0/2.0},{0.0,1.0/2.0}}; double Jt[2][2], dJt, iJt[2][2], S[3], G[2][3], GG[3][3], tmp; double x0 = g[0][0]; double x1 = g[1][0]; double x2 = g[2][0]; double y0 = g[0][1]; double y1 = g[1][1]; double y2 = g[2][1]; double k0 = kappa[0]; double k1 = kappa[1]; double k2 = kappa[2]; Jt[0][0] = L[0][0]*x0 + L[0][1]*x1 + L[0][2]*x2; Jt[0][1] = L[0][0]*y0 + L[0][1]*y1 + L[0][2]*y2; Jt[1][0] = L[1][0]*x0 + L[1][1]*x1 + L[1][2]*x2; Jt[1][1] = L[1][0]*y0 + L[1][1]*y1 + L[1][2]*y2; dJt = (Jt[0][0]*Jt[1][1]) - (Jt[0][1]*Jt[1][0]); iJt[0][0] = +(Jt[1][1])/dJt; iJt[0][1] = -(Jt[0][1])/dJt; iJt[1][0] = -(Jt[1][0])/dJt; iJt[1][1] = +(Jt[0][0])/dJt; dJt = sqrt(dJt*dJt); G[0][0] = iJt[0][0]*L[0][0] + iJt[0][1]*L[1][0]; G[0][1] = iJt[0][0]*L[0][1] + iJt[0][1]*L[1][1]; G[0][2] = iJt[0][0]*L[0][2] + iJt[0][1]*L[1][2]; G[1][0] = iJt[1][0]*L[0][0] + iJt[1][1]*L[1][0]; G[1][1] = iJt[1][0]*L[0][1] + iJt[1][1]*L[1][1]; G[1][2] = iJt[1][0]*L[0][2] + iJt[1][1]*L[1][2]; GG[0][0] = G[0][0]*G[0][0] + G[1][0]*G[1][0]; GG[0][1] = G[0][0]*G[0][1] + G[1][0]*G[1][1]; GG[0][2] = G[0][0]*G[0][2] + G[1][0]*G[1][2]; GG[1][0] = G[0][1]*G[0][0] + G[1][1]*G[1][0]; GG[1][1] = G[0][1]*G[0][1] + G[1][1]*G[1][1]; GG[1][2] = G[0][1]*G[0][2] + G[1][1]*G[1][2]; GG[2][0] = G[0][2]*G[0][0] + G[1][2]*G[1][0]; GG[2][1] = G[0][2]*G[0][1] + G[1][2]*G[1][1]; GG[2][2] = G[0][2]*G[0][2] + G[1][2]*G[1][2]; for (ii=0; ii<3; ++ii){ for (jj=0; jj<3; ++jj){ val[ii][jj]=0; } } for (ii=0; ii<3; ++ii){ S[0] = 1-ip[ii][0]-ip[ii][1]; S[1] = ip[ii][0]; S[2] = ip[ii][1]; tmp = k0*S[0] + k1*S[1] + k2*S[2]; tmp = tmp*w[ii]; val[0][0] += GG[0][0]*tmp; val[0][1] += GG[1][0]*tmp; val[0][2] += GG[2][0]*tmp; val[1][0] += GG[0][1]*tmp; val[1][1] += GG[1][1]*tmp; val[1][2] += GG[2][1]*tmp; val[2][0] += GG[0][2]*tmp; val[2][1] += GG[1][2]*tmp; val[2][2] += GG[2][2]*tmp; } for (ii=0; ii<3; ++ii){ for (jj=0; jj<3; ++jj){ val[ii][jj] = val[ii][jj]*dJt; } } return; } double phidotphi(double g[3][2], double mua[3], double val[3][3]) { int ii, jj; static int L[2][3] = {{-1.0,1.0,0.0}, \ {-1.0,0.0,1.0}}; static double w[3] = {1.0/6.0,1.0/6.0,1.0/6.0}; static double ip[3][2] = {{1.0/2.0,0.0},{1.0/2.0,1.0/2.0},{0.0,1.0/2.0}}; double Jt[2][2], dJt, S[3], tmp; double x0 = g[0][0]; double x1 = g[1][0]; double x2 = g[2][0]; double y0 = g[0][1]; double y1 = g[1][1]; double y2 = g[2][1]; double k0 = mua[0]; double k1 = mua[1]; double k2 = mua[2]; Jt[0][0] = L[0][0]*x0 + L[0][1]*x1 + L[0][2]*x2; Jt[0][1] = L[0][0]*y0 + L[0][1]*y1 + L[0][2]*y2; Jt[1][0] = L[1][0]*x0 + L[1][1]*x1 + L[1][2]*x2; Jt[1][1] = L[1][0]*y0 + L[1][1]*y1 + L[1][2]*y2; dJt = (Jt[0][0]*Jt[1][1]) - (Jt[0][1]*Jt[1][0]); dJt = sqrt(dJt*dJt); for (ii=0; ii<3; ++ii){ for (jj=0; jj<3; ++jj){ val[ii][jj]=0; } } for (ii=0; ii<3; ++ii){ S[0] = 1-ip[ii][0]-ip[ii][1]; S[1] = ip[ii][0]; S[2] = ip[ii][1]; tmp = k0*S[0] + k1*S[1] + k2*S[2]; tmp = tmp*w[ii]; val[0][0] += S[0]*S[0]*tmp; val[0][1] += S[1]*S[0]*tmp; val[0][2] += S[2]*S[0]*tmp; val[1][0] += S[0]*S[1]*tmp; val[1][1] += S[1]*S[1]*tmp; val[1][2] += S[2]*S[1]*tmp; val[2][0] += S[0]*S[2]*tmp; val[2][1] += S[1]*S[2]*tmp; val[2][2] += S[2]*S[2]*tmp; } for (ii=0; ii<3; ++ii){ for (jj=0; jj<3; ++jj){ val[ii][jj] = val[ii][jj]*dJt; } } return; } double boundary_int(double gg[3][2], double bnd_index[3], double ksir[3], \ double valr[2][2]) { double ksirtmp[2]; int i, j; double g[2][2], val; for (i=0; i<2; ++i){ for (j=0; j<2; ++j){ valr[i][j]=0; } } if (bnd_index[0]==1 && bnd_index[2]==1){ ksirtmp[0] = ksir[0]; ksirtmp[1] = ksir[2]; g[0][0] = gg[0][0]; g[0][1] = gg[0][1]; g[1][0] = gg[2][0]; g[1][1] = gg[2][1]; for (i=0; i<2; ++i){ for (j=0; j<=i; ++j){ bound2(g, i, j, ksirtmp, &val); valr[i][j] = val; } } } else if (bnd_index[0]==1 && bnd_index[1]==1){ ksirtmp[0] = ksir[0]; ksirtmp[1] = ksir[1]; g[0][0] = gg[0][0]; g[0][1] = gg[0][1]; g[1][0] = gg[1][0]; g[1][1] = gg[1][1]; for (i=0; i<2; ++i){ for (j=0; j<=i; ++j){ bound2(g, i, j, ksirtmp, &val); valr[i][j] = val; } } } else if (bnd_index[1]==1 && bnd_index[2]==1){ ksirtmp[0] = ksir[1]; ksirtmp[1] = ksir[2]; g[0][0] = gg[1][0]; g[0][1] = gg[1][1]; g[1][0] = gg[2][0]; g[1][1] = gg[2][1]; for (i=0; i<2; ++i){ for (j=0; j<=i; ++j){ bound2(g, i, j, ksirtmp, &val); valr[i][j] = val; } } } return; } double bound2(double g[2][2], int il, int im, double ksir[2], \ double *val) { static double w[2] = {1.0/2.0,1.0/2.0}; static double ip[2] = {0.21132486540519,0.78867513459481}; double dJt, S[2], tmp, tmpval; int ii; double x0 = g[0][0]; double x1 = g[1][0]; double y0 = g[0][1]; double y1 = g[1][1]; double k0 = ksir[0]; double k1 = ksir[1]; dJt = sqrt(((g[1][0]-g[0][0])*(g[1][0]-g[0][0])) + \ ((g[1][1]-g[0][1])*(g[1][1]-g[0][1]))); tmpval = 0.0; for (ii=0; ii<2; ++ii){ S[0] = 1-ip[ii]; S[1] = ip[ii]; tmp = k0*S[0] + k1*S[1]; tmp = tmp*w[ii]; tmpval += S[il]*S[im]*tmp; } *val = tmpval*dJt; } /* -------- Gate-way to matlab ------------ */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double *nodes,*elements,*bndvtx,*mua,*kappa,*ksir,*c,*omega; int nodem,noden,elemm,elemn,nzmax; double *I,*J,*Sr,*Si; /* Error checking */ if (nrhs < 8 ) mexErrMsgTxt(" There is not enough input arguments"); if(nlhs!=3) mexErrMsgTxt("This routine requires Three ouput arguments"); nodes=mxGetPr(prhs[0]); /* nodes of mesh */ elements=mxGetPr(prhs[1]); /* elements of mesh */ bndvtx=mxGetPr(prhs[2]); /* boundary nodes */ mua=mxGetPr(prhs[3]); /* absorption, nosal */ kappa=mxGetPr(prhs[4]); /* diffusion, nodeal */ ksir=mxGetPr(prhs[5]); /* reflection parameter, nodal */ c=mxGetPr(prhs[6]); /* speed of light in tissue, nodal */ omega=mxGetPr(prhs[7]); /* frequency of excitation */ nodem=mxGetM(prhs[0]); /* Number of of nodes */ noden=mxGetN(prhs[0]); /* Number of node freedom */ elemm=mxGetM(prhs[1]); /* Number of elements */ elemn=mxGetN(prhs[1]); /* Number of nodes per elements */ nzmax = elemm*(elemn*(elemn+1)); /*nzmax = nodem*nodem*0.1;*/ /*mexPrintf("%d\n",nzmax);*/ plhs[0]=mxCreateDoubleMatrix(nzmax,1,mxREAL); /* i */ plhs[1]=mxCreateDoubleMatrix(nzmax,1,mxREAL); /* j */ plhs[2]=mxCreateDoubleMatrix(nzmax,1,mxCOMPLEX); /* s */ I=mxGetPr(plhs[0]); J=mxGetPr(plhs[1]); Sr=mxGetPr(plhs[2]); Si=mxGetPi(plhs[2]); mainloop(nodes,elements,bndvtx,mua,kappa,ksir,c,omega,nodem,noden,elemm,elemn,I,J,Sr,Si); return; }
27.354756
92
0.453059
[ "mesh" ]
c90ab85c1f82934b4cdf4fee10b2cea5b2bbd755
98,413
h
C
include/config.h
wowotech/chrome-ec
1b53782145964ec226afbf910e23b1e68c0ac8dd
[ "BSD-3-Clause" ]
1
2018-04-23T05:55:32.000Z
2018-04-23T05:55:32.000Z
include/config.h
wowotech/chrome-ec
1b53782145964ec226afbf910e23b1e68c0ac8dd
[ "BSD-3-Clause" ]
null
null
null
include/config.h
wowotech/chrome-ec
1b53782145964ec226afbf910e23b1e68c0ac8dd
[ "BSD-3-Clause" ]
null
null
null
/* Copyright 2016 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. */ /* * config.h - Top-level configuration Chrome EC * * All configuration settings (CONFIG_*) are defined in this file or in a * sub-configuration file (config_chip.h, board.h, etc.) included by this file. * * Note that this file is included by assembly (.S) files. Any C-isms such as * struct definitions or enums in a sub-configuration file MUST be guarded with * #ifndef __ASSEMBLER__ to prevent those C-isms from being evaluated by the * assembler. */ #ifndef __CROS_EC_CONFIG_H #define __CROS_EC_CONFIG_H /* * All config options are listed alphabetically and described here. * * If you add a new config option somewhere in the code, you must add a * default value here and describe what it does. * * To get a list current list, run this command: * git grep " CONFIG_" | grep -o "CONFIG_[A-Za-z0-9_]\+" | sort | uniq * * Some options are #defined here to enable them by default. Chips or boards * may override this by #undef'ing them in config_chip.h or board.h, * respectively. * * TODO(crosbug.com/p/23758): Describe all of these. Also describe the * HAS_TASK_* macro and how/when it should be used vs. a config define. And * BOARD_*, CHIP_*, and CHIP_FAMILY_*. */ /* * Add support for sensor FIFO: * define the size of the global fifo, must be a power of 2. */ #undef CONFIG_ACCEL_FIFO /* The amount of free entries that trigger an interrupt to the AP. */ #undef CONFIG_ACCEL_FIFO_THRES /* * Sensors in this mask are in forced mode: they needed to be polled * at their data rate frequency. */ #undef CONFIG_ACCEL_FORCE_MODE_MASK /* Enable accelerometer interrupts. */ #undef CONFIG_ACCEL_INTERRUPTS /* * Support "spoof" mode for sensors. This allows sensors to have their values * spoofed to any arbitrary value. This is useful for testing. */ #define CONFIG_ACCEL_SPOOF_MODE /* Specify type of accelerometers attached. */ #undef CONFIG_ACCEL_BMA255 #undef CONFIG_ACCEL_KXCJ9 #undef CONFIG_ACCEL_KX022 #undef CONFIG_ACCEL_LIS2DH #undef CONFIG_ACCELGYRO_LSM6DS0 #undef CONFIG_ACCELGYRO_BMI160 #undef CONFIG_ACCELGYRO_LSM6DSM /* Support for BMI160 hardware orientation sensor */ #undef CONFIG_BMI160_ORIENTATION_SENSOR /* Support for KIONIX KX022 hardware orientation sensor */ #undef CONFIG_KX022_ORIENTATION_SENSOR /* * Define if either CONFIG_BMI160_ORIENTATION_SUPPORT or * CONFIG_KX022_ORIENTATION_SUPPORT is set. */ #undef CONFIG_ORIENTATION_SENSOR /* Support the orientation gesture */ #undef CONFIG_GESTURE_ORIENTATION /* Specify barometer attached */ #undef CONFIG_BARO_BMP280 /* * Use the old standard reference frame for accelerometers. The old * reference frame is: * Z-axis: perpendicular to keyboard, pointing up, such that if the device * is sitting flat on a table, the accel reads +G. * X-axis: in the plane of the keyboard, pointing from the front lip to the * hinge, such that if the device is oriented with the front lip touching * the table and the hinge directly above, the accel reads +G. * Y-axis: in the plane of the keyboard, pointing to the right, such that * if the device is on it's left side, the accel reads +G. * * Also, in the old reference frame, the lid accel matches the base accel * readings when lid is closed. */ #undef CONFIG_ACCEL_STD_REF_FRAME_OLD /* * Define the event to raise when BMI160 interrupt. * Must be within TASK_EVENT_MOTION_INTERRUPT_MASK. */ #undef CONFIG_ACCELGYRO_BMI160_INT_EVENT /* Set when INT2 is an ouptut */ #undef CONFIG_ACCELGYRO_BMI160_INT2_OUTPUT /* Specify type of Gyrometers attached. */ #undef CONFIG_GYRO_L3GD20H /* * Define the event to raise when LIS2DH interrupt. * Must be within TASK_EVENT_MOTION_INTERRUPT_MASK. */ #undef CONFIG_ACCEL_LIS2DH_INT_EVENT /* Compile chip support for analog-to-digital convertor */ #undef CONFIG_ADC /* * ADC sample time selection. The value is chip-dependent. * TODO: Replace this with CONFIG_ADC_PROFILE entries. */ #undef CONFIG_ADC_SAMPLE_TIME /* Include the ADC analog watchdog feature in the ADC code */ #define CONFIG_ADC_WATCHDOG /* * Chip-dependent ADC configuration - select one. * SINGLE - Sample all inputs once when requested. * FAST_CONTINUOUS - Sample all inputs continuously using DMA, with minimal * sample time. */ #define CONFIG_ADC_PROFILE_SINGLE #undef CONFIG_ADC_PROFILE_FAST_CONTINUOUS /* * Some ALS modules may be connected to the EC. We need the command, and * specific drivers for each module. */ #ifdef HAS_TASK_ALS #define CONFIG_ALS #else #undef CONFIG_ALS #endif #undef CONFIG_ALS_AL3010 #undef CONFIG_ALS_BH1730 /* * If defined, BH1730 uses board specific lux calculation formula parameters. * If not defined, BH1730 uses default parameters to calculate lux. */ #undef CONFIG_ALS_BH1730_LUXTH_PARAMS #undef CONFIG_ALS_ISL29035 #undef CONFIG_ALS_OPT3001 /* Define the exact model ID present on the board: SI1141 = 41, SI1142 = 42, */ #undef CONFIG_ALS_SI114X /* Check if the device revision is supported */ #undef CONFIG_ALS_SI114X_CHECK_REVISION /* * Define the event to raise when BMI160 interrupt. * Must be within TASK_EVENT_MOTION_INTERRUPT_MASK. */ #undef CONFIG_ALS_SI114X_INT_EVENT /* * Enable Si114x to operate in polling mode. This config is used in conjunction * with CONFIG_ALS_SI114X_INT_EVENT. When polling is enabled, the read is * initiated in the same manner as when interrupts are used, but the event which * triggers the irq_handler is generated by deferred call using a fixed delay. */ #undef CONFIG_ALS_SI114X_POLLING /* Define which ALS sensor is used for dimming the lightbar when dark */ #undef CONFIG_ALS_LIGHTBAR_DIMMING /* Support AP hang detection host command and state machine */ #undef CONFIG_AP_HANG_DETECT /* Support AP Warm reset Interrupt. */ #undef CONFIG_AP_WARM_RESET_INTERRUPT /* Allow proprietary communication protocols' extensions. */ #undef CONFIG_EXTENSION_COMMAND /* * Support controlling the display backlight based on the state of the lid * switch. The EC will disable the backlight when the lid is closed. */ #undef CONFIG_BACKLIGHT_LID /* * If defined, EC will enable the backlight signal only if this GPIO is * asserted AND the lid is open. This supports passing the backlight-enable * signal from the AP through EC. */ #undef CONFIG_BACKLIGHT_REQ_GPIO /* Support base32 text encoding */ #undef CONFIG_BASE32 /*****************************************************************************/ /* Battery config */ /* Support a simple battery. */ #undef CONFIG_BATTERY /* * Compile battery-specific code. * * Note that some boards have their own unique battery constants / functions. * In this case, those are provided in board/(boardname)/battery.c, and none of * these are defined. * Defining one of these will automatically define CONFIG_BATTERY near the end * of this file. If you add a new config here, you'll need to update that * check. */ #undef CONFIG_BATTERY_BQ20Z453 #undef CONFIG_BATTERY_BQ27541 #undef CONFIG_BATTERY_BQ27621 #undef CONFIG_BATTERY_MAX17055 /* Compile mock battery support; used by tests. */ #undef CONFIG_BATTERY_MOCK /* Maximum time to wake a non-responsive battery, in second */ #define CONFIG_BATTERY_PRECHARGE_TIMEOUT 30 /* * If defined, the charger will check a board specific function for battery hw * presence as an additional condition to determine if power on is allowed for * factory override, where allowing booting of a bare board with no battery and * no power button press is required. */ #undef CONFIG_BATTERY_HW_PRESENT_CUSTOM /* * If defined, the charger will check for battery presence before attempting * to communicate with it. This avoids the 30 second delay when booting * without a battery present. Do not use with CONFIG_BATTERY_PRESENT_GPIO. * * Replace the default battery_is_present() function with a board-specific * implementation in board.c */ #undef CONFIG_BATTERY_PRESENT_CUSTOM /* * If defined, GPIO which is driven low when battery is present. * Charger will check for battery presence before attempting to communicate * with it. This avoids the 30 second delay when booting without a battery * present. Do not use with CONFIG_BATTERY_PRESENT_CUSTOM. */ #undef CONFIG_BATTERY_PRESENT_GPIO /* * Compile smart battery support * * For batteries which support this specification: * http://sbs-forum.org/specs/sbdat110.pdf) */ #undef CONFIG_BATTERY_SMART /* Chemistry of the battery device */ #undef CONFIG_BATTERY_DEVICE_CHEMISTRY /* * Critical battery shutdown timeout (seconds) * * If the battery is at extremely low charge (and discharging) or extremely * high temperature, the EC will shut itself down. This defines the timeout * period in seconds between the critical condition being detected and the * EC shutting itself down. Note that if the critical condition is corrected * before the timeout expiration, the EC will not shut itself down. * */ #define CONFIG_BATTERY_CRITICAL_SHUTDOWN_TIMEOUT 30 /* Perform a battery cut-off when we reach the battery critical level */ #undef CONFIG_BATTERY_CRITICAL_SHUTDOWN_CUT_OFF /* * Support battery cut-off as host command and console command. * * Once defined, you have to implement a board_cut_off_battery() function * in board/???/battery.c file. */ #undef CONFIG_BATTERY_CUT_OFF /* * The default delay is 1 second. Define this if a board prefers * different delay. */ #undef CONFIG_BATTERY_CUTOFF_DELAY_US /* * The board-specific battery.c implements get and set functions to read and * write arbirary vendor-specific parameters stored in the battery. * See include/battery.h for prototypes. */ #undef CONFIG_BATTERY_VENDOR_PARAM /* * TODO(crosbug.com/p/29467): allows charging of a dead battery that * requests nil for current and voltage. Remove this workaround when * possible. */ #undef CONFIG_BATTERY_REQUESTS_NIL_WHEN_DEAD /* * Check for battery in disconnect state (similar to cut-off state). If this * battery is found to be in disconnect state, take it out of this state by * force-applying a charge current. */ #undef CONFIG_BATTERY_REVIVE_DISCONNECT /* * Specify the battery percentage at which the host is told it is full. * If this value is not specified the default is 97% set in battery.h. */ #undef CONFIG_BATTERY_LEVEL_NEAR_FULL /* * Expose some data when it is needed. * For example, battery disconnect state */ #undef CONFIG_CHARGE_STATE_DEBUG /* Include support for Bluetooth LE */ #undef CONFIG_BLUETOOTH_LE /* Include support for testing the radio for Bluetooth LE */ #undef CONFIG_BLUETOOTH_LE_RADIO_TEST /* Include support for the HCI and link layers for Bluetooth LE */ #undef CONFIG_BLUETOOTH_LE_STACK /* Include debugging support for the Bluetooth link layer */ #undef CONFIG_BLUETOOTH_LL_DEBUG /* Include debugging support for Bluetooth HCI */ #undef CONFIG_BLUETOOTH_HCI_DEBUG /* Boot header storage offset. */ #undef CONFIG_BOOT_HEADER_STORAGE_OFF /* Size of boot header in storage. */ #undef CONFIG_BOOT_HEADER_STORAGE_SIZE /*****************************************************************************/ /* EC has GPIOs to allow board to reset RTC */ #undef CONFIG_BOARD_HAS_RTC_RESET /* * Call board_before_rsmrst(state) before passing RSMRST# to the AP. * This is for board workarounds that are required after rails are up * but before the AP is out of reset. */ #undef CONFIG_BOARD_HAS_BEFORE_RSMRST /* * Call board_config_post_gpio_init() after GPIOs are initialized. See * include/board_config.h for more information. */ #undef CONFIG_BOARD_POST_GPIO_INIT /* * Call board_config_pre_init() before any inits are called. See * include/board_config.h for more information. */ #undef CONFIG_BOARD_PRE_INIT /* EC has GPIOs attached to board version stuffing resistors */ #undef CONFIG_BOARD_VERSION /* The decoding of the GPIOs defining board version is defined in board code */ #undef CONFIG_BOARD_SPECIFIC_VERSION /* EC responses to a board defined I2C slave address */ #undef CONFIG_BOARD_I2C_SLAVE_ADDR /* Permanent LM4 boot configuration */ #undef CONFIG_BOOTCFG_VALUE /*****************************************************************************/ /* Modify the default behavior to make system bringup easier. */ #undef CONFIG_BRINGUP /* * Enable debug prints / asserts that may helpful for debugging board bring-up, * but probably shouldn't be enabled for production for performance reasons. */ #undef CONFIG_DEBUG_BRINGUP /*****************************************************************************/ /* * Support for entering recovery mode using volume buttons. You need to * list the buttons in recovery_buttons. */ #undef CONFIG_BUTTON_RECOVERY /* * Indicates there is a dedicated recovery button. */ #undef CONFIG_DEDICATED_RECOVERY_BUTTON /* * The board has volume up and volume down buttons. Note, these are *buttons* * and not keys in the keyboard matrix. */ #undef CONFIG_VOLUME_BUTTONS /* Support V1 CCD configuration */ #undef CONFIG_CASE_CLOSED_DEBUG_V1 /* Allow unsafe debugging functionality in V1 configuration */ #undef CONFIG_CASE_CLOSED_DEBUG_V1_UNSAFE /* * Capsense chip has buttons, too. */ #undef CONFIG_CAPSENSE /*****************************************************************************/ /* Compile charge manager */ #undef CONFIG_CHARGE_MANAGER /* Number of charge ports excluding type-c ports */ #define CONFIG_DEDICATED_CHARGE_PORT_COUNT 0 /* Allow charge manager to default to charging from dual-role partners */ #undef CONFIG_CHARGE_MANAGER_DRP_CHARGING /* Handle the external power limit host command in charge manager */ #undef CONFIG_CHARGE_MANAGER_EXTERNAL_POWER_LIMIT /* Initially enter safe mode, with relaxed port / current selection rules */ #define CONFIG_CHARGE_MANAGER_SAFE_MODE /* Leave safe mode when battery pct meets or exceeds this value */ #define CONFIG_CHARGE_MANAGER_BAT_PCT_SAFE_MODE_EXIT 2 /* The hardware has some input current ramping/back-off mechanism */ #undef CONFIG_CHARGE_RAMP_HW /* Compile input current ramping support using software control */ #undef CONFIG_CHARGE_RAMP_SW /*****************************************************************************/ /* Charger config */ /* Compile common charge state code. You must pick an implementation. */ #undef CONFIG_CHARGER #undef CONFIG_CHARGER_V2 /* Compile charger-specific code for these chargers (pick at most one) */ #undef CONFIG_CHARGER_BD9995X #undef CONFIG_CHARGER_BQ24707A #undef CONFIG_CHARGER_BQ24715 #undef CONFIG_CHARGER_BQ24725 #undef CONFIG_CHARGER_BQ24735 #undef CONFIG_CHARGER_BQ24738 #undef CONFIG_CHARGER_BQ24770 #undef CONFIG_CHARGER_BQ24773 #undef CONFIG_CHARGER_BQ25890 #undef CONFIG_CHARGER_BQ25892 #undef CONFIG_CHARGER_BQ25895 #undef CONFIG_CHARGER_ISL9237 #undef CONFIG_CHARGER_ISL9238 #undef CONFIG_CHARGER_RT9466 #undef CONFIG_CHARGER_RT9467 #undef CONFIG_CHARGER_SY21612 /* * Enable the CHG_EN at initialization to turn-on the BGATE which allows voltage * to be applied to the battery PACK & wakes the battery if it is in shipmode. */ #undef CONFIG_CHARGER_BD9995X_CHGEN /* * BD9995X Power Save Mode * * Which power save mode should the charger enter when VBUS is removed. Check * driver/bd9995x.h for the power save settings. By default, no power save mode * is enabled. */ #undef CONFIG_BD9995X_POWER_SAVE_MODE /* * If the battery temperature sense pin is connected to charger, * get the battery temperature from the charger. */ #undef CONFIG_CHARGER_BATTERY_TSENSE /* * BQ2589x IR Compensation settings. * Should be the combination of BQ2589X_IR_TREG_xxxC, BQ2589X_IR_VCLAMP_yyyMV * and BQ2589X_IR_BAT_COMP_zzzMOHM. */ #undef CONFIG_CHARGER_BQ2589X_IR_COMP /* * BQ2589x 5V boost current limit and voltage. * Should be the combination of BQ2589X_BOOSTV_MV(voltage) and * BQ2589X_BOOST_LIM_xxxMA. */ #undef CONFIG_CHARGER_BQ2589X_BOOST /* * Board specific charging current limit, in mA. If defined, the charge state * machine will not allow the battery to request more current than this. */ #undef CONFIG_CHARGER_CURRENT_LIMIT /* Enable/disable system power monitor PSYS function */ #undef CONFIG_CHARGER_PSYS /* * Board specific charging current termination limit, in mA. If defined and * charger supports setting termination current it should be set during charger * init. * * TODO(tbroch): Only valid for bq2589x currently. Configure defaults for other * charger ICs that support termination currents. */ #undef CONFIG_CHARGER_TERM_CURRENT_LIMIT /* * Board supports discharge mode. In this mode, the battery will discharge * even if AC is present. Used for testing. */ #undef CONFIG_CHARGER_DISCHARGE_ON_AC /* Board has a custom discharge mode. */ #undef CONFIG_CHARGER_DISCHARGE_ON_AC_CUSTOM /* * Board specific flag used to disable external ILIM pin used to determine input * current limit. When defined, the input current limit is decided only by * the software register value. */ #undef CONFIG_CHARGER_ILIM_PIN_DISABLED /* * Default input current for the board, in mA. * * This value should depend on external power adapter, designed charging * voltage, and the maximum power of the running system. For type-C chargers, * this should be set to 512 mA in order to not brown-out low-current USB * charge ports. */ #undef CONFIG_CHARGER_INPUT_CURRENT /* * Board specific maximum input current limit, in mA. */ #undef CONFIG_CHARGER_MAX_INPUT_CURRENT /* * Leave charger VBAT configured to battery-requested voltage under all * conditions, even when AC is not present. This may be necessary to work * around quirks of certain charger chips, such as the BD9995X. */ #undef CONFIG_CHARGER_MAINTAIN_VBAT /* Minimum battery percentage for power on */ #undef CONFIG_CHARGER_MIN_BAT_PCT_FOR_POWER_ON /* Narrow VDC power path */ #undef CONFIG_CHARGER_NARROW_VDC /* * Low energy thresholds - when battery level is below BAT_PCT and an external * charger provides less than CHG_MW of power, inform the AP of the situation * through the LIMIT_POWER host event. */ #undef CONFIG_CHARGER_LIMIT_POWER_THRESH_BAT_PCT #undef CONFIG_CHARGER_LIMIT_POWER_THRESH_CHG_MW /* * Charger should call battery_override_params() to limit/correct the voltage * and current requested by the battery pack before acting on the request. * * This is valid with CONFIG_CHARGER_V2 only. */ #undef CONFIG_CHARGER_PROFILE_OVERRIDE /* * Common code for charger profile override. Should be used with * CONFIG_CHARGER_PROFILE_OVERRIDE. */ #undef CONFIG_CHARGER_PROFILE_OVERRIDE_COMMON /* * Battery voltage threshold ranges for charge profile override. * Override it in board.h if battery has multiple threshold ranges. */ #define CONFIG_CHARGER_PROFILE_VOLTAGE_RANGES 2 /* Value of the charge sense resistor, in mOhms */ #undef CONFIG_CHARGER_SENSE_RESISTOR /* Value of the input current sense resistor, in mOhms */ #undef CONFIG_CHARGER_SENSE_RESISTOR_AC /* * Board has an GPIO pin to enable or disable charging. * * This GPIO should be named GPIO_CHARGER_EN, if active high. Or * GPIO_CHARGER_EN_L if active low. */ #undef CONFIG_CHARGER_EN_GPIO /* Charger enable GPIO is active low */ #undef CONFIG_CHARGER_EN_ACTIVE_LOW /* Enable trickle charging */ #undef CONFIG_TRICKLE_CHARGING /*****************************************************************************/ /* * Chip needs to do pre-init very early in main(), and provides chip_pre_init() * to do so. */ #undef CONFIG_CHIP_PRE_INIT /*****************************************************************************/ /* Chipset config */ /* AP chipset support; pick at most one */ #undef CONFIG_CHIPSET_APOLLOLAKE/* Intel Apollolake (x86) */ #undef CONFIG_CHIPSET_BRASWELL /* Intel Braswell (x86) */ #undef CONFIG_CHIPSET_CANNONLAKE /* Intel Cannonlake (x86) */ #undef CONFIG_CHIPSET_ECDRIVEN /* Dummy power module */ #undef CONFIG_CHIPSET_MEDIATEK /* MediaTek MT81xx */ #undef CONFIG_CHIPSET_RK3399 /* Rockchip rk3399 */ /* TODO: Rename below config to CONFIG_CHIPSET_RK32XX */ #undef CONFIG_CHIPSET_ROCKCHIP /* Rockchip rk32xx */ #undef CONFIG_CHIPSET_SKYLAKE /* Intel Skylake (x86) */ #undef CONFIG_CHIPSET_STONEY /* AMD Stoney (x86)*/ /* Support chipset throttling */ #undef CONFIG_CHIPSET_CAN_THROTTLE /* Enable additional chipset debugging */ #undef CONFIG_CHIPSET_DEBUG /* Enable chipset reset hook, requires a deferrable function */ #undef CONFIG_CHIPSET_RESET_HOOK /* Support power rail control */ #define CONFIG_CHIPSET_HAS_PP1350 #define CONFIG_CHIPSET_HAS_PP5000 /* Support PMIC reset(using LDO_EN) in chipset */ #undef CONFIG_CHIPSET_HAS_PLATFORM_PMIC_RESET /* Redefine when we need a different power-on sequence on the same chipset. */ #define CONFIG_CHIPSET_POWER_SEQ_VERSION 0 /*****************************************************************************/ /* * Chip config for clock circuitry * define = crystal / undef = oscillator */ #undef CONFIG_CLOCK_CRYSTAL /* Indicate if a clock source is connected to stm32f4's "HSE" specific input */ #undef CONFIG_STM32_CLOCK_HSE_HZ /* Indicate if a clock source is connected to "LSE" specific input */ #undef CONFIG_STM32_CLOCK_LSE /* * Chip config for clock source * define = external crystal oscillator / undef = internal clock source */ #undef CONFIG_CLOCK_SRC_EXTERNAL /*****************************************************************************/ /* Support curve25519 public key cryptography */ #undef CONFIG_CURVE25519 /*****************************************************************************/ /* PMIC config */ /* Support firmware long press power-off timer */ #undef CONFIG_PMIC_FW_LONG_PRESS_TIMER /* Support PMIC power control */ #undef CONFIG_PMIC /*****************************************************************************/ /* * Optional console commands * * Defining these options will enable the corresponding command on the EC * console. */ #undef CONFIG_CMD_ACCELS #undef CONFIG_CMD_ACCEL_FIFO #undef CONFIG_CMD_ACCEL_INFO #define CONFIG_CMD_ACCELSPOOF #undef CONFIG_CMD_ALS #define CONFIG_CMD_APTHROTTLE #undef CONFIG_CMD_BATDEBUG #define CONFIG_CMD_BATTFAKE #undef CONFIG_CMD_BATT_MFG_ACCESS #undef CONFIG_CMD_BUTTON #undef CONFIG_CMD_CCD_DISABLE /* 'ccd disable' subcommand */ #define CONFIG_CMD_CHARGER #undef CONFIG_CMD_CHARGER_ADC_AMON_BMON #undef CONFIG_CMD_CHARGER_PROFILE_OVERRIDE #undef CONFIG_CMD_CHARGER_PROFILE_OVERRIDE_TEST #undef CONFIG_CMD_CHARGER_PSYS #define CONFIG_CMD_CHARGE_SUPPLIER_INFO #undef CONFIG_CMD_CHGRAMP #undef CONFIG_CMD_CLOCKGATES #undef CONFIG_CMD_COMXTEST #define CONFIG_CMD_CRASH #define CONFIG_CMD_DEVICE_EVENT #undef CONFIG_CMD_ECTEMP #define CONFIG_CMD_FASTCHARGE #undef CONFIG_CMD_FLASH #define CONFIG_CMD_FLASHINFO #undef CONFIG_CMD_FLASH_TRISTATE #undef CONFIG_CMD_FORCETIME #undef CONFIG_CMD_GPIO_EXTENDED #undef CONFIG_CMD_GSV #define CONFIG_CMD_HASH #define CONFIG_CMD_HCDEBUG #undef CONFIG_CMD_HOSTCMD #undef CONFIG_CMD_I2CWEDGE #undef CONFIG_CMD_I2C_PROTECT #define CONFIG_CMD_I2C_SCAN #undef CONFIG_CMD_I2C_STRESS_TEST #undef CONFIG_CMD_I2C_STRESS_TEST_ACCEL #undef CONFIG_CMD_I2C_STRESS_TEST_ALS #undef CONFIG_CMD_I2C_STRESS_TEST_BATTERY #undef CONFIG_CMD_I2C_STRESS_TEST_CHARGER #undef CONFIG_CMD_I2C_STRESS_TEST_TCPC #define CONFIG_CMD_I2C_XFER #define CONFIG_CMD_IDLE_STATS #undef CONFIG_CMD_ILIM #define CONFIG_CMD_INA #undef CONFIG_CMD_JUMPTAGS #define CONFIG_CMD_KEYBOARD #undef CONFIG_CMD_LID_ANGLE #undef CONFIG_CMD_MCDP #define CONFIG_CMD_MD #define CONFIG_CMD_MEM #define CONFIG_CMD_MMAPINFO #define CONFIG_CMD_PD #undef CONFIG_CMD_PD_CONTROL #undef CONFIG_CMD_PD_DEV_DUMP_INFO #undef CONFIG_CMD_PD_FLASH #undef CONFIG_CMD_PLL #undef CONFIG_CMD_PMU #define CONFIG_CMD_POWERINDEBUG #undef CONFIG_CMD_POWERLED #define CONFIG_CMD_POWER_AP #undef CONFIG_CMD_PPC_DUMP #define CONFIG_CMD_REGULATOR #undef CONFIG_CMD_RTC #undef CONFIG_CMD_RTC_ALARM #define CONFIG_CMD_RW #undef CONFIG_CMD_SCRATCHPAD #define CONFIG_CMD_SHMEM #undef CONFIG_CMD_SLEEP #define CONFIG_CMD_SLEEPMASK #undef CONFIG_CMD_SPI_FLASH #undef CONFIG_CMD_SPI_NOR #undef CONFIG_CMD_SPI_XFER #undef CONFIG_CMD_STACKOVERFLOW #define CONFIG_CMD_SYSINFO #define CONFIG_CMD_SYSJUMP #define CONFIG_CMD_SYSLOCK #undef CONFIG_CMD_TASKREADY #define CONFIG_CMD_TEMP_SENSOR #define CONFIG_CMD_TIMERINFO #undef CONFIG_CMD_TPM_LOG #define CONFIG_CMD_TYPEC #undef CONFIG_CMD_USART_INFO #define CONFIG_CMD_USBMUX #undef CONFIG_CMD_USB_PD_PE #define CONFIG_CMD_WAITMS /*****************************************************************************/ /* Provide common core code to output panic information without interrupts. */ #define CONFIG_COMMON_PANIC_OUTPUT /* * Store a panic log and halt the system for a software-related reasons, such as * stack overflow or assertion failure. */ #undef CONFIG_SOFTWARE_PANIC /* * Certain platforms(e.g. eve, poppy) cannot retain panic info in data ram since * VCC is powered down on EC reset. On such platforms, panic data needs to be * saved/restored to persistent storage by using chip specific * implementations. This option can be enabled by those platforms that have and * wish to use chip-implemented panic backup/restore functions. */ #undef CONFIG_CHIP_PANIC_BACKUP /* * Provide the default GPIO abstraction layer. * You want this unless you are doing a really tiny firmware. */ #define CONFIG_COMMON_GPIO /* * Provides smaller GPIO names to reduce flash size. Instead of the 'name' * field in GPIO macro it will concat 'port' and 'pin' to reduce flash size. */ #undef CONFIG_COMMON_GPIO_SHORTNAMES /* * Provide common runtime layer code (tasks, hooks ...) * You want this unless you are doing a really tiny firmware. */ #define CONFIG_COMMON_RUNTIME /* Provide common core code to handle the operating system timers. */ #define CONFIG_COMMON_TIMER /*****************************************************************************/ /* * Provide additional help on console commands, such as the supported * options/usage. * * Boards may #undef this to reduce image size. */ #define CONFIG_CONSOLE_CMDHELP /* * Add a .flags field to the console commands data structure, to distinguish * some commands from others. The available flags bits are defined in * include/console.h */ #undef CONFIG_CONSOLE_COMMAND_FLAGS /* * One use of the .flags field is to make some console commands restricted, so * that they can be disabled or enabled at run time. */ #undef CONFIG_RESTRICTED_CONSOLE_COMMANDS /* The default .flags field value is zero, unless overridden with this. */ #undef CONFIG_CONSOLE_COMMAND_FLAGS_DEFAULT /* * Enable EC_CMD_CONSOLE_READ V1. One could disable this config to prevent * kernel from creating the `console_log` debugfs entry. */ #define CONFIG_CONSOLE_ENABLE_READ_V1 /* * Number of entries in console history buffer. * * Boards may #undef this to reduce memory usage. */ #define CONFIG_CONSOLE_HISTORY 8 /* Max length of a single line of input */ #define CONFIG_CONSOLE_INPUT_LINE_SIZE 80 /* Enable verbose output to UART console and extra timestamp print precision. */ #define CONFIG_CONSOLE_VERBOSE /* * Enable the experimental console. * * NOTE: If you enable this experimental console, you will need to run the * EC-3PO interactive console in the util directory! Otherwise, you won't be * able to enter any commands. */ #undef CONFIG_EXPERIMENTAL_CONSOLE /* Include CRC-8 utility function */ #undef CONFIG_CRC8 /* * When enabled, do not build RO image from the same set of files as the RW * image. Instead define a separate set of object files in the respective * build.mk files by adding the objects to the custom-ro_objs-y variable. */ #undef CONFIG_CUSTOMIZED_RO /* * When enabled, build in support for software & hardware crypto; * only supported on CR50. */ #undef CONFIG_DCRYPTO /* * When enabled, accelerate sha512 using the generic crypto engine; * only supported on CR50 */ #undef CONFIG_DCRYPTO_SHA512 /* * When enabled build support for SHA-384/512, requires CONFIG_DCRYPTO. */ #undef CONFIG_UPTO_SHA512 /* * When enabled ignore version et al during fw upgrade for chip/g. */ #undef CONFIG_IGNORE_G_UPDATE_CHECKS /*****************************************************************************/ /* * Debugging config * * Note that these options are enabled by default, because they're really * handy for debugging systems during bringup and even at factory time. * * A board may undefine any or all of these to reduce image size and RAM usage, * at the cost of debuggability. */ /* * ASSERT() macros are checked at runtime. See CONFIG_DEBUG_ASSERT_REBOOTS * to see what happens if one fails. * * Boards may #undef this to reduce image size. */ #define CONFIG_DEBUG_ASSERT /* * Prints a message and reboots if an ASSERT() macro fails at runtime. When * enabled, an ASSERT() which fails will produce a message of the form: * * ASSERTION FAILURE '<expr>' in function() at file:line * * If this is not defined, failing ASSERT() will trigger a BKPT instruction * instead. * * Ignored if CONFIG_DEBUG_ASSERT is not defined. * * Boards may #undef this to reduce image size. */ #define CONFIG_DEBUG_ASSERT_REBOOTS /* * On assertion failure, prints only the file name and the line number. * * Ignored if CONFIG_DEBUG_ASSERT_REBOOTS is not defined. * * Boards may define this to reduce image size. */ #undef CONFIG_DEBUG_ASSERT_BRIEF /* * Disable the write buffer used for default memory map accesses. * This turns "Imprecise data bus errors" into "Precise" errors * in exception traces at the cost of some performance. * This may help identify the offending instruction causing an * exception. Supported on cortex-m. */ #undef CONFIG_DEBUG_DISABLE_WRITE_BUFFER /* * Print additional information when exceptions are triggered, such as the * fault address, here shown as bfar. This shows the reason for the fault * and may help to determine the cause. * * === EXCEPTION: 03 ====== xPSR: 01000000 =========== * r0 :0000000b r1 :00000047 r2 :60000000 r3 :200013dd * r4 :00000000 r5 :080053f4 r6 :200013d0 r7 :00000002 * r8 :00000000 r9 :200013de r10:00000000 r11:00000000 * r12:00000000 sp :200009a0 lr :08002b85 pc :08003a8a * Precise data bus error, Forced hard fault, Vector catch, bfar = 60000000 * mmfs = 00008200, shcsr = 00000000, hfsr = 40000000, dfsr = 00000008 * * If this is not defined, only a register dump will be printed. * * Boards may #undef this to reduce image size. */ #define CONFIG_DEBUG_EXCEPTIONS /* * Print orientation when device orientation changes * (requires CONFIG_SENSOR_ORIENTATION) */ #undef CONFIG_DEBUG_ORIENTATION /* Support Synchronous UART debug printf. */ #undef CONFIG_DEBUG_PRINTF /* Check for stack overflows on every context switch */ #define CONFIG_DEBUG_STACK_OVERFLOW /*****************************************************************************/ /* Support events from devices attached to the EC */ #undef CONFIG_DEVICE_EVENT /* Monitor the states of other devices */ #undef CONFIG_DEVICE_STATE /* Support DMA transfers inside the EC */ #undef CONFIG_DMA /* Use the common interrupt handlers for DMA IRQs */ #define CONFIG_DMA_DEFAULT_HANDLERS /* Compile extra debugging and tests for the DMA module */ #undef CONFIG_DMA_HELP /* Support EC to Internal bus bridge. */ #undef CONFIG_EC2I /* Usually, EC capable of sensor speeds up to 200000 mHz */ #define CONFIG_EC_MAX_SENSOR_FREQ_DEFAULT_MILLIHZ 200000 /* Maximal EC sampling rate */ #undef CONFIG_EC_MAX_SENSOR_FREQ_MILLIHZ /* * Allow board to override the feature bitmap provided through host command * and ACPI. */ #undef CONFIG_EC_FEATURE_BOARD_OVERRIDE /* Support EC chip internal data EEPROM */ #undef CONFIG_EEPROM /* * Support for sending emulated sysrq events to AP (on designs with a keyboard, * sysrq is passed as normal key presses). */ #undef CONFIG_EMULATED_SYSRQ /* Support for eSPI for host communication */ #undef CONFIG_ESPI /* Use Virtual Wire signals instead of GPIO with eSPI interface */ #undef CONFIG_ESPI_VW_SIGNALS /* Include code for handling external power */ #define CONFIG_EXTPOWER /* Support detecting external power presence via a GPIO */ #undef CONFIG_EXTPOWER_GPIO /* Default debounce time for external power signal */ #define CONFIG_EXTPOWER_DEBOUNCE_MS 30 /*****************************************************************************/ /* Number of cooling fans. Undef if none. */ #undef CONFIG_FANS /* Percentage to which all fans are set at initiation */ #define CONFIG_FAN_INIT_SPEED 100 /* Support fan control while in low-power idle */ #undef CONFIG_FAN_DSLEEP /* * Replace the default fan_percent_to_rpm() function with a board-specific * implementation in board.c */ #undef CONFIG_FAN_RPM_CUSTOM /* * We normally check and update the fans once per second (HOOK_SECOND). If this * is #defined to a postive integer N, we will only update the fans every N * seconds instead. */ #undef CONFIG_FAN_UPDATE_PERIOD /* Send event when mode change, host read acpi memory and select DPTF table */ #undef CONFIG_DPTF_DEVICE_ORIENTATION /*****************************************************************************/ /* Flash configuration */ /* This enables console commands and higher-level features */ #define CONFIG_FLASH /* This enables chip-specific access functions */ #define CONFIG_FLASH_PHYSICAL #undef CONFIG_FLASH_BANK_SIZE #undef CONFIG_FLASH_ERASED_VALUE32 #undef CONFIG_FLASH_ERASE_SIZE #undef CONFIG_FLASH_ROW_SIZE /* Allow deferred (async) flash erase */ #undef CONFIG_FLASH_DEFERRED_ERASE /* Flash must be selected for write/erase operations to succeed. */ #undef CONFIG_FLASH_SELECT_REQUIRED /* Base address of program memory */ #undef CONFIG_PROGRAM_MEMORY_BASE /* * EC code can reside on internal or external storage. Only one of these * CONFIGs should be defined. */ #undef CONFIG_EXTERNAL_STORAGE #undef CONFIG_INTERNAL_STORAGE /* * Flash is directly mapped into the EC's address space. If this is not * defined, the flash driver must implement flash_physical_read(). */ #define CONFIG_MAPPED_STORAGE /* * Base address of memory-mapped flash storage, for platforms which define * CONFIG_MAPPED_STORAGE. */ #undef CONFIG_MAPPED_STORAGE_BASE #undef CONFIG_FLASH_PROTECT_NEXT_BOOT /* * Some platforms need to write protect RW independently of all flash. */ #undef CONFIG_FLASH_PROTECT_RW /* * Store persistent write protect for the flash inside the flash data itself. * This allows ECs with internal flash to emulate something closer to a SPI * flash write protect register. If this is not defined, write protect state * is maintained solely by the physical flash driver. */ #define CONFIG_FLASH_PSTATE /* * Store the pstate data in its own dedicated bank of flash. This allows * disabling the protect-RO-at-boot flag without rewriting the RO firmware, * but costs a bank of flash. * * If this is not defined, the pstate data is stored inside the RO firmware * image itself. This is more space-efficient, but the only way to clear the * flag once it's set is to rewrite the RO firmware (after removing the WP * screw, of course). */ #define CONFIG_FLASH_PSTATE_BANK /* * Lock the PSTATE by default (currently only supported when * CONFIG_FLASH_PSTATE_BANK is not defined). */ #undef CONFIG_FLASH_PSTATE_LOCKED /* * For flash that is segemented in different regions. */ #undef CONFIG_FLASH_MULTIPLE_REGION /* Number of regions of different size/type */ #undef CONFIG_FLASH_REGION_TYPE_COUNT /* Total size of writable flash */ #undef CONFIG_FLASH_SIZE /* Minimum flash write size (in bytes) */ #undef CONFIG_FLASH_WRITE_SIZE /* Most efficient flash write size (in bytes) */ #undef CONFIG_FLASH_WRITE_IDEAL_SIZE /* Protected region of storage belonging to EC */ #undef CONFIG_EC_PROTECTED_STORAGE_OFF #undef CONFIG_EC_PROTECTED_STORAGE_SIZE /* Writable region of storage belonging to EC */ #undef CONFIG_EC_WRITABLE_STORAGE_OFF #undef CONFIG_EC_WRITABLE_STORAGE_SIZE /* Enable robust non-volatile counter in flash */ #undef CONFIG_FLASH_NVCOUNTER /* Address of start of the NVcounter flash page */ #undef CONFIG_FLASH_NVCTR_BASE_A #undef CONFIG_FLASH_NVCTR_BASE_B /*****************************************************************************/ /* NvMem Configuration */ /* Enable NV Memory module within flash */ #undef CONFIG_FLASH_NVMEM /* Offset to start of NvMem area from base of flash */ #undef CONFIG_FLASH_NVMEM_OFFSET_A #undef CONFIG_FLASH_NVMEM_OFFSET_B /* Address of start of Nvmem area */ #undef CONFIG_FLASH_NVMEM_BASE_A #undef CONFIG_FLASH_NVMEM_BASE_B /* Size in bytes of NvMem area */ #undef CONFIG_FLASH_NVMEM_SIZE /* Enable <key,value> variable support (requires CONFIG_FLASH_NVMEM) */ #undef CONFIG_FLASH_NVMEM_VARS /* * We already have to define nvmem_user_sizes[] to specify the order and size * of the user regions. CONFIG_FLASH_NVMEM_VARS looks for two symbols to * specify the region number and size for the variable region. */ #undef CONFIG_FLASH_NVMEM_VARS_USER_NUM #undef CONFIG_FLASH_NVMEM_VARS_USER_SIZE /*****************************************************************************/ /* Include a flashmap in the compiled firmware image */ #define CONFIG_FMAP /* Allow EC serial console input to wake up the EC from STOP mode */ #undef CONFIG_FORCE_CONSOLE_RESUME /* Enable support for floating point unit */ #undef CONFIG_FPU /*****************************************************************************/ /* Firmware region configuration */ #undef CONFIG_FW_PSTATE_OFF #undef CONFIG_FW_PSTATE_SIZE /* * Reuse the space that was occupied in RAM by the little firmware (LFW) loader * with the section ".bss.slow" instead. */ #undef CONFIG_REPLACE_LOADER_WITH_BSS_SLOW /* * Read-only / read-write image configuration. * Images may reside on storage (ex. external or internal SPI) at a different * offset than when copied to program memory. Hence, two sets of offsets, * for STORAGE and for MEMORY. */ #undef CONFIG_RO_MEM_OFF /* Offset relative to CONFIG_EC_PROTECTED_STORAGE_OFF */ #undef CONFIG_RO_STORAGE_OFF #undef CONFIG_RO_SIZE #undef CONFIG_RW_MEM_OFF /* Some targets include two RW sections in the image. */ #undef CONFIG_RW_B /* This is the offset of the second RW section into the flash. */ #undef CONFIG_RW_B_MEM_OFF /* Offset relative to CONFIG_EC_WRITABLE_STORAGE_OFF */ #undef CONFIG_RW_STORAGE_OFF #undef CONFIG_RW_SIZE /* * NPCX-specific bootheader geometry. * TODO(crosbug.com/p/23796): Factor these CONFIGs out. */ #undef CONFIG_RO_HDR_MEM_OFF #undef CONFIG_RO_HDR_SIZE /* * Write protect region offset / size. This region normally encompasses the * RO image, but may also contain additional images or data. */ #undef CONFIG_WP_STORAGE_OFF #undef CONFIG_WP_STORAGE_SIZE /* * Rollback protect region. If CONFIG_ROLLBACK is defined to enable the rollback * protect region, CONFIG_ROLLBACK_OFF and CONFIG_ROLLBACK_SIZE must be defined * too. */ #undef CONFIG_ROLLBACK #undef CONFIG_ROLLBACK_OFF #undef CONFIG_ROLLBACK_SIZE /* If defined, add support for storing some entropy in the rollback region. */ #undef CONFIG_ROLLBACK_SECRET_SIZE /* * If defined, inject some locally generated entropy when secret is updated, * using board_get_entropy function. * Large values may take a long time to generate. */ #undef CONFIG_ROLLBACK_SECRET_LOCAL_ENTROPY_SIZE /* If defined, we can update rollback information (RW can unset this). */ #define CONFIG_ROLLBACK_UPDATE /* * Current rollback version. Meaningless for RO (but provides the minimum value * that will be written to the rollback protection at flash time). * * For RW, rollback version included in version structure, used by RO to * determine if the RW image is recent enough and can be jumped to. * * Valid values are >= 0, <= INT32_MAX (positive, 32-bit signed integer). */ #define CONFIG_ROLLBACK_VERSION 0 /* * Board Image ec.bin contains a RO firmware. If not defined, the image will * only contain the RW firmware. The RO firmware comes from another board. */ #define CONFIG_FW_INCLUDE_RO /* If defined, another image (RW) exists with more features */ #undef CONFIG_FW_LIMITED_IMAGE /* * If defined, we can use system_get_fw_reset_vector function to decide * reset vector of RO/RW firmware for sysjump. */ #undef CONFIG_FW_RESET_VECTOR /*****************************************************************************/ /* Motion sensor based gesture recognition information */ /* These all require HAS_TASK_MOTIONSENSE to work */ /* Do we want to detect gestures? */ #undef CONFIG_GESTURE_DETECTION /* Mask of all sensors used for gesture dectections */ #undef CONFIG_GESTURE_DETECTION_MASK /* some gesture recognition done in software */ #undef CONFIG_GESTURE_SW_DETECTION /* enable gesture host interface */ #undef CONFIG_GESTURE_HOST_DETECTION /* Sensor sampling interval for gesture recognition */ #undef CONFIG_GESTURE_SAMPLING_INTERVAL_MS /* Which sensor to look for battery tap recognition */ #undef CONFIG_GESTURE_SENSOR_BATTERY_TAP /* * Double tap detection parameters * Double tap works by looking for two isolated Z-axis accelerometer impulses * preceded and followed by relatively calm periods of accelerometer motion. * * Define an outer and inner window. The inner window specifies how * long the tap impulse is expected to last. The outer window specifies the * period before the initial tap impluse and after the final tap impulse for * which to check for relatively calm periods. In between the two impulses * there is a minimum and maximum interstice time allowed. * * Define an acceleration threshold to dectect a tap, in mg. */ #undef CONFIG_GESTURE_TAP_OUTER_WINDOW_T #undef CONFIG_GESTURE_TAP_INNER_WINDOW_T #undef CONFIG_GESTURE_TAP_MIN_INTERSTICE_T #undef CONFIG_GESTURE_TAP_MAX_INTERSTICE_T #undef CONFIG_GESTURE_TAP_THRES_MG /* Event generated when battery tap is detected */ #undef CONFIG_GESTURE_TAP_EVENT /* Which sensor to look for significant motion activity */ #undef CONFIG_GESTURE_SIGMO /* * Significant motion parameters * Sigmo state machine looks for movement, waits skip milli-seconds, * and check for movement again with proof milli-seconds. */ #undef CONFIG_GESTURE_SIGMO_PROOF_MS #undef CONFIG_GESTURE_SIGMO_SKIP_MS #undef CONFIG_GESTURE_SIGMO_THRES_MG /* Event generated when significant motion is detected. */ #undef CONFIG_GESTURE_SIGMO_EVENT /* Do we want to detect the lid angle? */ #undef CONFIG_LID_ANGLE /* * Add code for preventing 0 and 360 degree transition. Needed when * Device supports tablet mode. */ #undef CONFIG_LID_ANGLE_INVALID_CHECK /* * Use lid angle to detect tablet mode. */ #undef CONFIG_LID_ANGLE_TABLET_MODE /* Which sensor is located on the base? */ #undef CONFIG_LID_ANGLE_SENSOR_BASE /* Which sensor is located on the lid? */ #undef CONFIG_LID_ANGLE_SENSOR_LID /* * Allows using the lid angle measurement to determine if peripheral devices * should be enabled or disabled, like key scanning, trackpad interrupt. */ #undef CONFIG_LID_ANGLE_UPDATE /* * During shutdown sequence sensor rails can be powered down asynchronously * to the EC hence EC cannot interlock the sensor states with the power down * states. To avoid this issue, defer switching the sensors rate with a * configurable delay if in S3. By the time deferred function is serviced, * if the chipset is in S5 we can back out from switching the sensor rate. */ #define CONFIG_MOTION_SENSE_SUSPEND_DELAY_US 0 /* Define motion sensor count in board layer */ #undef CONFIG_DYNAMIC_MOTION_SENSOR_COUNT /******************************************************************************/ /* Host to RAM (H2RAM) Memory Mapping */ /* H2RAM Base memory address */ #undef CONFIG_H2RAM_BASE /* H2RAM Size */ #undef CONFIG_H2RAM_SIZE /* H2RAM Host LPC I/O base memory address */ #undef CONFIG_H2RAM_HOST_LPC_IO_BASE /* ISH boot start address */ #undef CONFIG_ISH_BOOT_START /* * Define the minimal amount of time (in ms) betwen running motion sense task * loop. */ #define CONFIG_MOTION_MIN_SENSE_WAIT_TIME 3 /*****************************************************************************/ /* * Support the host asking the EC about the status of the most recent host * command. * * When the AP is attached to the EC via a serialized bus such as I2C or SPI, * it needs a way to minimize the length of time an EC command will tie up the * bus (and the kernel driver on the AP). If this config is defined, the EC * may return an in-progress result code for slow commands such as flash * erase/write instead of stalling until the command finishes processing, and * the AP may then inquire the status of the current command and/or the result * of the previous command. */ #undef CONFIG_HOST_COMMAND_STATUS /* clear bit(s) to mask reporting of an EC_HOST_EVENT_XXX event(s) */ #define CONFIG_HOST_EVENT_REPORT_MASK 0xffffffff #define CONFIG_HOST_EVENT64_REPORT_MASK 0xffffffffffffffffULL /* Config option to support 64-bit hostevents and wake-masks. */ #define CONFIG_HOST_EVENT64 /* * The host commands are sorted in the .rodata.hcmds section so use the binary * search algorithm to match a command to its handler */ #undef CONFIG_HOSTCMD_SECTION_SORTED /* * Host command parameters and response are 32-bit aligned. This generates * much more efficient code on ARM. */ #undef CONFIG_HOSTCMD_ALIGNED /* Default hcdebug mode, e.g. HCDEBUG_OFF or HCDEBUG_NORMAL */ #define CONFIG_HOSTCMD_DEBUG_MODE HCDEBUG_NORMAL /* If we have host command task, assume we also are using host events. */ #ifdef HAS_TASK_HOSTCMD #define CONFIG_HOSTCMD_EVENTS #else #undef CONFIG_HOSTCMD_EVENTS #endif /* * Board supports host command to get EC SPI flash info. This is typically * only needed if the factory needs to determine which of several possible SPI * flash chips is attached to the EC on a given board. */ #undef CONFIG_HOSTCMD_FLASH_SPI_INFO /* * For ECs where the host command interface is I2C, slave * address which the EC will respond to. */ #undef CONFIG_HOSTCMD_I2C_SLAVE_ADDR /* * Accept EC host commands over the SPI slave (SPS) interface. */ #undef CONFIG_HOSTCMD_SPS /* * Host command rate limiting assures EC will have time to process lower * priority tasks even if the AP is hammering the EC with host commands. * If there is less than CONFIG_HOSTCMD_RATE_LIMITING_MIN_REST between * host commands for CONFIG_HOSTCMD_RATE_LIMITING_PERIOD, then a * recess period of CONFIG_HOSTCMD_RATE_LIMITING_RECESS will be * enforced. */ #define CONFIG_HOSTCMD_RATE_LIMITING_PERIOD (500 * MSEC) #define CONFIG_HOSTCMD_RATE_LIMITING_MIN_REST (3 * MSEC) #define CONFIG_HOSTCMD_RATE_LIMITING_RECESS (20 * MSEC) /* PD MCU supports host commands */ #undef CONFIG_HOSTCMD_PD /* EC supports EC_CMD_PD_CHIP_INFO */ #define CONFIG_EC_CMD_PD_CHIP_INFO /* * Use if PD MCU controls charging (selecting charging port and input * current limit). */ #undef CONFIG_HOSTCMD_PD_CHG_CTRL /* Panic when status of PD MCU reflects that it has crashed */ #undef CONFIG_HOSTCMD_PD_PANIC /* Board supports RTC host commands */ #undef CONFIG_HOSTCMD_RTC /* For access to VBNV on-EC battery-backed storage */ #undef CONFIG_HOSTCMD_VBNV_CONTEXT /* EC controls the board's SKU ID and can report that to the AP */ #undef CONFIG_HOSTCMD_SKUID /* Set SKU ID from AP */ #undef CONFIG_HOSTCMD_AP_SET_SKUID /*****************************************************************************/ /* Enable debugging and profiling statistics for hook functions */ #undef CONFIG_HOOK_DEBUG /*****************************************************************************/ /* CRC configuration */ /* Enable the hardware accelerator for CRC computation */ #undef CONFIG_HW_CRC /* Enable the software routine for CRC computation */ #undef CONFIG_SW_CRC /*****************************************************************************/ /* Enable system hibernate */ #define CONFIG_HIBERNATE /* Default delay after shutting down before hibernating */ #define CONFIG_HIBERNATE_DELAY_SEC 3600 /* * Use to define going in to hibernate early if low on battery. * CONFIG_HIBERNATE_BATT_PCT specifies the low battery threshold * for going into hibernate early, and CONFIG_HIBERNATE_BATT_SEC defines * the minimum amount of time to stay in G3 before checking for low * battery hibernate. */ #undef CONFIG_HIBERNATE_BATT_PCT #undef CONFIG_HIBERNATE_BATT_SEC /* For ECs with multiple wakeup pins, define enabled wakeup pins */ #undef CONFIG_HIBERNATE_WAKEUP_PINS /* * Use PSL (Power Switch Logic) for hibernating. It turns off VCC power rail * for ultra-low power consumption and uses PSL inputs rely on VSBY power rail * to wake up ec and the whole system. */ #undef CONFIG_HIBERNATE_PSL /* Use a hardware specific udelay(). */ #undef CONFIG_HW_SPECIFIC_UDELAY /*****************************************************************************/ /* I2C configuration */ #undef CONFIG_I2C #undef CONFIG_I2C_DEBUG #undef CONFIG_I2C_DEBUG_PASSTHRU #undef CONFIG_I2C_PASSTHROUGH #undef CONFIG_I2C_PASSTHRU_RESTRICTED #undef CONFIG_I2C_VIRTUAL_BATTERY /* * Conservative I2C reading size per single transaction. For example, register * of stm32f0 and stm32l4 are limited to be 8 bits for this field. */ #define CONFIG_I2C_CHIP_MAX_READ_SIZE 255 /* * Enable i2c_xfer() for receiving request larger than * CONFIG_I2C_CHIP_MAX_READ_SIZE. */ #undef CONFIG_I2C_XFER_LARGE_READ /* EC uses an I2C master interface */ #undef CONFIG_I2C_MASTER /* EC uses an I2C slave interface */ #undef CONFIG_I2C_SLAVE /* Defines I2C operation retry count when slave nack'd(EC_ERROR_BUSY) */ #define CONFIG_I2C_NACK_RETRY_COUNT 0 /* * I2C SCL gating. * * If CONFIG_I2C_SCL_GATE_ADDR/PORT is defined, whenever the defined address * is addressed, CONFIG_I2C_SCL_GATE_GPIO is set to high. When the I2C * transaction is done, the pin is set back to low. */ #undef CONFIG_I2C_SCL_GATE_PORT #undef CONFIG_I2C_SCL_GATE_ADDR #undef CONFIG_I2C_SCL_GATE_GPIO /* * Some chip supports two owned slave address. The second slave address is used * for other purpose such as board specific i2c commands. This option can be * set if user of the second slave address requires larger host packet buffer * size. */ #define CONFIG_I2C_EXTRA_PACKET_SIZE 0 /* * I2C multi-port controller. * * If CONFIG_I2C_MULTI_PORT_CONTROLLER is defined, a single on-chip I2C * controller may have multiple I2C ports attached. Therefore, I2c operations * must lock the controller (not just the port) to prevent hardware access * conflicts. */ #undef CONFIG_I2C_MULTI_PORT_CONTROLLER #undef CONFI_ISH_I2C_PORT0_SPEED #undef CONFI_ISH_I2C_PORT1_SPEED #undef CONFI_ISH_I2C_PORT2_SPEED /*****************************************************************************/ /* Current/Power monitor */ /* * Compile driver for INA219 or INA231. These two flags may not be both * defined. */ #undef CONFIG_INA219 #undef CONFIG_INA231 /*****************************************************************************/ /* Inductive charging */ /* Enable inductive charging support */ #undef CONFIG_INDUCTIVE_CHARGING /******************************************************************************/ /* Support NXP PCA9534 I/O expander. */ #undef CONFIG_IO_EXPANDER_PCA9534 /*****************************************************************************/ /* Number of IRQs supported on the EC chip */ #undef CONFIG_IRQ_COUNT /* * The IT8320 supports e-flash clock up to 48 MHz (IT8390 maximum is 32 MHz). * Enable it if we want better performance of fetching instruction from e-flash. * * This is valid with PLL frequency equal to 48/96MHz only. */ #undef CONFIG_IT83XX_FLASH_CLOCK_48MHZ /* To define it, if I2C channel C and PECI used at the same time. */ #undef CONFIG_IT83XX_SMCLK2_ON_GPC7 /*****************************************************************************/ /* Keyboard config */ /* * The Silego reset chip sits in between the EC and the physical keyboard on * column 2. To save power in low-power modes, some Silego variants require * the signal to be inverted so that the open-drain output from the EC isn't * costing power due to the pull-up resistor in the Silego. */ #undef CONFIG_KEYBOARD_COL2_INVERTED /* * Config KSO to start from a different KSO pin. This is to allow some chips * to use alternate functions on KSO pins. */ #define CONFIG_KEYBOARD_KSO_BASE 0 /* * For certain board configurations, KSI2 will be stuck asserted for all * scan columns if the power button is held. We must be aware of this case * in order to correctly handle recovery mode key combinations. */ #undef CONFIG_KEYBOARD_PWRBTN_ASSERTS_KSI2 /* Enable extra debugging output from keyboard modules */ #undef CONFIG_KEYBOARD_DEBUG /* The board uses a negative edge-triggered GPIO for keyboard interrupts. */ #undef CONFIG_KEYBOARD_IRQ_GPIO /* Compile code for 8042 keyboard protocol */ #undef CONFIG_KEYBOARD_PROTOCOL_8042 /* Compile code for MKBP keyboard protocol */ #undef CONFIG_KEYBOARD_PROTOCOL_MKBP /* Support keyboard factory test scanning */ #undef CONFIG_KEYBOARD_FACTORY_TEST /* * Keyboard config (struct keyboard_scan_config) is in board.c. If this is * not defined, default values from common/keyboard_scan.c will be used. */ #undef CONFIG_KEYBOARD_BOARD_CONFIG /* * Support for boot key combinations (e.g. refresh key being held on boot to * trigger recovery). */ #define CONFIG_KEYBOARD_BOOT_KEYS /* Add support for the new key. */ #undef CONFIG_KEYBOARD_NEW_KEY /* * Minimum CPU clocks between scans. This ensures that keyboard scanning * doesn't starve the other EC tasks of CPU when running at a decreased system * clock. */ #undef CONFIG_KEYBOARD_POST_SCAN_CLOCKS /* Print keyboard scan time intervals. */ #undef CONFIG_KEYBOARD_PRINT_SCAN_TIMES /* * Support for extra runtime key combinations (e.g. alt+volup+h/r for hibernate * and warm reboot, respectively). */ #define CONFIG_KEYBOARD_RUNTIME_KEYS /* * Allow the keyboard scan code set tables to be modified at runtime. */ #undef CONFIG_KEYBOARD_SCANCODE_MUTABLE /* * Call board-supplied keyboard_suppress_noise() function when the debounced * keyboard state changes. Some boards use this to send a signal to the audio * codec to suppress typing noise picked up by the microphone. */ #undef CONFIG_KEYBOARD_SUPPRESS_NOISE /* * Enable keyboard testing functionality. This enables a message which receives * a list of keyscan events from the AP and processes them. This will cause * keypresses to appear on the AP through the same mechanism as a normal * keyboard press. * * This can be used to spoof keyboard events, so is not normally defined, * except during internal testing. */ #undef CONFIG_KEYBOARD_TEST /* * Enable quasi-bidirectional buffers for KSO pins. It has an open-drain output * and a low-impedance pull-up. The low-impedance pull-up is active when ec * changes the output data buffers from 0 to 1, thereby reducing the * low-to-high transition time. */ #undef CONFIG_KEYBOARD_KSO_HIGH_DRIVE /*****************************************************************************/ /* Support common LED interface */ #undef CONFIG_LED_COMMON /* Standard LED behavior according to spec given that we have a red-green * bicolor led for charging and one power led */ #undef CONFIG_LED_POLICY_STD /* * LEDs for LED_POLICY STD may be inverted. In this case they are active low * and the GPIO names will be GPIO_LED..._L. */ #undef CONFIG_LED_BAT_ACTIVE_LOW #undef CONFIG_LED_POWER_ACTIVE_LOW /* Support for LED driver chip(s) */ #undef CONFIG_LED_DRIVER_DS2413 /* Maxim DS2413, on one-wire interface */ #undef CONFIG_LED_DRIVER_LP5562 /* LP5562, on I2C interface */ /* Offset in flash where little firmware will live. */ #undef CONFIG_LFW_OFFSET /* * Compile lid switch support. * * This is enabled by default because all boards other than reference boards * are for laptops with lid switchs. Reference boards #undef it. */ #define CONFIG_LID_SWITCH /* * GPIOs to use to detect that the lid is opened. * * This is a X-macro composed of a list of LID_OPEN(GPIO_xxx) elements defining * all the GPIOs to check to find whether the lid is currently opened. * If not defined, it is using GPIO_LID_OPEN. */ #undef CONFIG_LID_SWITCH_GPIO_LIST /* * Support for turning the lightbar power rails on briefly when the AP is off. * Enabling this requires implementing the board-specific lb_power() function * to do it (see lb_common.h). */ #undef CONFIG_LIGHTBAR_POWER_RAILS /* * For tap sequence, show the last segment in dim to give a better idea of * battery percentage. */ #undef CONFIG_LIGHTBAR_TAP_DIM_LAST_SEGMENT /* Program memory offset for little firmware loader. */ #undef CONFIG_LOADER_MEM_OFF /* Size of little firmware loader. */ #undef CONFIG_LOADER_SIZE /* Little firmware loader storage offset. */ #undef CONFIG_LOADER_STORAGE_OFF /* * Low power idle options. These are disabled by default and all boards that * want to use low power idle must define it. When using the LFIOSC, the low * frequency clock will be used to conserve even more power when possible. * * GPIOs which need to trigger interrupts in low power idle must specify the * GPIO_INT_DSLEEP flag in gpio_list[]. * * Note that for some processors (e.g. LM4), an active JTAG connection will * prevent the EC from using low-power idle. */ #undef CONFIG_LOW_POWER_IDLE #undef CONFIG_LOW_POWER_USE_LFIOSC /* * Enable deep sleep during S0 (ignores SLEEP_MASK_AP_RUN). */ #undef CONFIG_LOW_POWER_S0 /* Support LPC interface */ #undef CONFIG_LPC /* Base address of low power RAM. */ #undef CONFIG_LPRAM_BASE /* Size of low power RAM. */ #undef CONFIG_LPRAM_SIZE /* Use Link-Time Optimizations to try to reduce the firmware code size */ #undef CONFIG_LTO /* Provide rudimentary malloc/free like services for shared memory. */ #undef CONFIG_MALLOC /* Need for a math library */ #undef CONFIG_MATH_UTIL /* Include code to do online compass calibration */ #undef CONFIG_MAG_CALIBRATE /* Presence of a Bosh Sensortec BMM150 magnetometer behind a BMI160. */ #undef CONFIG_MAG_BMI160_BMM150 /* Microchip EC SRAM start address */ #undef CONFIG_MEC_SRAM_BASE_START /* Microchip EC SRAM end address */ #undef CONFIG_MEC_SRAM_BASE_END /* Microchip EC SRAM size */ #undef CONFIG_MEC_SRAM_SIZE /* * Define Megachips DisplayPort to HDMI protocol converter/level shifter serial * interface. */ #undef CONFIG_MCDP28X0 /* Define clock input to MFT module. */ #undef CONFIG_MFT_INPUT_LFCLK /* Support MKBP event */ #undef CONFIG_MKBP_EVENT /* MKBP events are sent using host event */ #undef CONFIG_MKBP_USE_HOST_EVENT /* * With this option, we can define the MKBP wakeup events in this mask (as a * white list) in board level, those events allow to interrupt AP during S3. */ #undef CONFIG_MKBP_WAKEUP_MASK /* Support memory protection unit (MPU) */ #undef CONFIG_MPU /* Do not try hold I/O pins at frozen level during deep sleep */ #undef CONFIG_NO_PINHOLD /* Support one-wire interface */ #undef CONFIG_ONEWIRE /* Support One Time Protection structure */ #undef CONFIG_OTP /* Support PECI interface to x86 processor */ #undef CONFIG_PECI /* * Maximum operating temperature in degrees Celcius used on some x86 * processors. CPU chip temperature is reported relative to this value and * is never reported greater than this value. Processor asserts PROCHOT# * and starts throttling frequency and voltage at this temp. Operation may * become unreliable if temperature exceeds this limit. */ #undef CONFIG_PECI_TJMAX /* Support physical presence detection (via a physical button) */ #undef CONFIG_PHYSICAL_PRESENCE /* Enable (unsafe!) developer debug features for physical presence */ #undef CONFIG_PHYSICAL_PRESENCE_DEBUG_UNSAFE /*****************************************************************************/ /* PMU config */ /* * Enable hard-resetting the PMU from the EC. The implementation is rather * hacky; it simply shorts out the 3.3V rail to force the PMIC to panic. We * need this unfortunate hack because it's the only way to reset the I2C engine * inside the PMU. */ #undef CONFIG_PMU_HARD_RESET /* * Enable this config to make console UART self sufficient (no other * initialization required before uart_init(), no interrupts, uart_tx_char() * does not exit until character finished transmitting). * * This is useful during early hardware bringup, each platform needs to * implement its own code to support this. */ #undef CONFIG_POLLING_UART /* Define length of history buffer for port80 messages. */ #define CONFIG_PORT80_HISTORY_LEN 128 /* * Enable/Disable printing of port80 messages in interrupt context. By default, * this is disabled. */ #define CONFIG_PORT80_PRINT_IN_INT 0 /* Compile common code to support power button debouncing */ #undef CONFIG_POWER_BUTTON /* Force the active state of the power button : 0(default if unset) or 1 */ #undef CONFIG_POWER_BUTTON_ACTIVE_STATE /* Allow the power button to send events while the lid is closed */ #undef CONFIG_POWER_BUTTON_IGNORE_LID /* Support sending the power button signal to x86 chipsets */ #undef CONFIG_POWER_BUTTON_X86 /* Set power button state idle at init. Implemented only for npcx. */ #undef CONFIG_POWER_BUTTON_INIT_IDLE /* * Enable delay between DSW_PWROK and PWRBTN assertion. * If enabled, DSW_PWROK_TO_PWRBTN_US and get_time_dsw_pwrok must be defined * as well. */ #undef CONFIG_DELAY_DSW_PWROK_TO_PWRBTN /* * The time in usec required for PMC to be ready to detect power button press. * Refer to the timing diagram for G3 to S0 on PDG for details. */ #define CONFIG_DSW_PWROK_TO_PWRBTN_US (95 * MSEC) /* Compile common code for AP power state machine */ #undef CONFIG_POWER_COMMON /* Disable the power-on transition when the lid is opened */ #undef CONFIG_POWER_IGNORE_LID_OPEN /* Enable a task-safe way to control the PP5000 rail. */ #undef CONFIG_POWER_PP5000_CONTROL /* Support stopping in S5 on shutdown */ #undef CONFIG_POWER_SHUTDOWN_PAUSE_IN_S5 /* * Detect power signal interrupt storms, defined as more than * CONFIG_POWER_SIGNAL_INTERRUPT_STORM_DETECT_THRESHOLD occurences of a single * power signal interrupt within one second. */ #undef CONFIG_POWER_SIGNAL_INTERRUPT_STORM_DETECT_THRESHOLD /* Use part of the EC's data EEPROM to hold persistent storage for the AP. */ #undef CONFIG_PSTORE /* Support S0ix */ #undef CONFIG_POWER_S0IX /* * Allow the host to self-report its sleep state, in case there is some delay * between the host beginning to enter the sleep state and power signals * actually reflecting the new state. */ #undef CONFIG_POWER_TRACK_HOST_SLEEP_STATE /*****************************************************************************/ /* Support PWM control */ #undef CONFIG_PWM /* Define clock input to PWM module. */ #undef CONFIG_PWM_INPUT_LFCLK /*****************************************************************************/ /* Support PWM output to display backlight */ #undef CONFIG_PWM_DISPLIGHT /* Support PWM output to keyboard backlight */ #undef CONFIG_PWM_KBLIGHT /* Base address of RAM for the chip */ #undef CONFIG_RAM_BASE /* * CONFIG_DATA_RAM_SIZE and CONFIG_RAM_SIZE indicate size of all data RAM * available on the chip in bytes and size of data RAM available for EC in * bytes, respectively. * Usually, CONFIG_DATA_RAM_SIZE = CONFIG_RAM_SIZE but some chips need to * allocate RAM for the mask ROM. Then CONFIG_DATA_RAM_SIZE > CONFIG_RAM_SIZE. */ #undef CONFIG_DATA_RAM_SIZE #undef CONFIG_RAM_SIZE /* Enable rbox peripheral */ #undef CONFIG_RBOX /* Enable RDD peripheral */ #undef CONFIG_RDD /* Support IR357x Link voltage regulator debugging / reprogramming */ #undef CONFIG_REGULATOR_IR357X /* Support RMA auth challenge-response */ #undef CONFIG_RMA_AUTH /* If that's defined, the server public key and ID must also be defined */ #undef CONFIG_RMA_AUTH_SERVER_PUBLIC_KEY /* 32 bytes: {0xNN, 0xNN, ... 0xNN} */ #undef CONFIG_RMA_AUTH_SERVER_KEY_ID /* 6-bit key ID, 0xMM */ /* Enable hardware Random Number generator support */ #undef CONFIG_RNG /* Support verifying 2048-bit RSA signature */ #undef CONFIG_RSA /* Define the RSA key size. */ #undef CONFIG_RSA_KEY_SIZE /* Use RSA exponent 3 instead of F4 (65537) */ #undef CONFIG_RSA_EXPONENT_3 /* * Adjust the compiler optimization flags for the RSA code to get a speed-up * at the expense of a small code size delta. */ #undef CONFIG_RSA_OPTIMIZED /* * Verify the RW firmware using the RSA signature. * (for accessories without software sync) */ #undef CONFIG_RWSIG /* * Disable rwsig jump when the reset source is hard pin-reset. This only work * for the case where rwsig task is not used. */ #undef CONFIG_RWSIG_DONT_CHECK_ON_PIN_RESET /* * When RWSIG verification is performed as a task, time to wait from signature * verification to an automatic jump to RW (if AP does not request the wait to * be interrupted). */ #define CONFIG_RWSIG_JUMP_TIMEOUT (1000 * MSEC) /* * Defines what type of futility signature type should be used. * RWSIG should be used for new designs. * Old adapters use the USBPD1 futility signature type. */ #undef CONFIG_RWSIG_TYPE_RWSIG #undef CONFIG_RWSIG_TYPE_USBPD1 /* * By default the pubkey and sig are put at the end of the first and second * half of the total flash, and take up the minimum space possible. You can * override those defaults with these. */ #undef CONFIG_RO_PUBKEY_ADDR #undef CONFIG_RO_PUBKEY_SIZE #undef CONFIG_RW_SIG_ADDR #undef CONFIG_RW_SIG_SIZE /* Size of the serial number if needed */ #undef CONFIG_SERIALNO_LEN /****************************************************************************/ /* Shared objects library. */ /* Support shared objects library between RO and RW. */ #undef CONFIG_SHAREDLIB /* Size of shared objects library. */ #undef CONFIG_SHAREDLIB_SIZE /* Program memory offset of shared objects library. */ #undef CONFIG_SHAREDLIB_MEM_OFF /* Storage offset of sharedobjects library. */ #undef CONFIG_SHAREDLIB_STORAGE_OFF /* * If defined, the hash module will save its last computed hash when jumping * between EC images. */ #undef CONFIG_SAVE_VBOOT_HASH /* Allow the board to use a GPIO for the SCI# signal. */ #undef CONFIG_SCI_GPIO /* Support computing SHA-1 hash */ #undef CONFIG_SHA1 /* Support computing of other hash sizes (without the VBOOT code) */ #undef CONFIG_SHA256 /* Unroll some loops in SHA256_transform for better performance. */ #undef CONFIG_SHA256_UNROLLED /* Emulate the CLZ (Count Leading Zeros) in software for CPU lacking support */ #undef CONFIG_SOFTWARE_CLZ /* Emulate the CLZ (Count Trailing Zeros) in software for CPU lacking support */ #undef CONFIG_SOFTWARE_CTZ /* Support smbus interface */ #undef CONFIG_SMBUS /* Support SPI interfaces */ #undef CONFIG_SPI /* Support deprecated SPI protocol version 2. */ #undef CONFIG_SPI_PROTOCOL_V2 /* * Support SPI Slave interfaces. The first board supporting this is cr50 and * in its parlance SPI_SLAVE is called SPS. This convention might be * reconsidered later, and the use of "SPI" in different config options needs * to be cleand up. (crbug.com/512613). */ #undef CONFIG_SPS /* Define the SPI port to use to access SPI accelerometer */ #undef CONFIG_SPI_ACCEL_PORT /* Support SPI flash */ #undef CONFIG_SPI_FLASH /* Support SPI flash protection register translation */ #undef CONFIG_SPI_FLASH_REGS /* Define the SPI port to use to access the flash */ #undef CONFIG_SPI_FLASH_PORT /* Select any of the following SPI flash configs that your board uses. */ #undef CONFIG_SPI_FLASH_GD25LQ40 #undef CONFIG_SPI_FLASH_GD25Q41B #undef CONFIG_SPI_FLASH_W25Q40 #undef CONFIG_SPI_FLASH_W25Q64 #undef CONFIG_SPI_FLASH_W25Q80 #undef CONFIG_SPI_FLASH_W25X40 /* SPI flash part supports SR2 register */ #undef CONFIG_SPI_FLASH_HAS_SR2 /* Define the SPI port to use to access the fingerprint sensor */ #undef CONFIG_SPI_FP_PORT /* Support JEDEC SFDP based Serial NOR flash */ #undef CONFIG_SPI_NOR /* Enable SPI_NOR debugging providing additional console output while * initializing Serial NOR Flash devices including SFDP discovery. */ #undef CONFIG_SPI_NOR_DEBUG /* Maximum Serial NOR flash command size, in Bytes */ #undef CONFIG_SPI_NOR_MAX_MESSAGE_SIZE /* Maximum Serial NOR flash read size, in Bytes */ #undef CONFIG_SPI_NOR_MAX_READ_SIZE /* Maximum Serial NOR flash write size, in Bytes. Note this must be a power of * two. */ #undef CONFIG_SPI_NOR_MAX_WRITE_SIZE /* If defined will enable block (64KiB) erase operations. */ #undef CONFIG_SPI_NOR_BLOCK_ERASE /* If defined will read the sector/block to be erased first and only initiate * the erase operation if not already in an erased state. The read operation * (performed in CONFIG_SPI_NOR_MAX_READ_SIZE chunks) is aborted early if a * non "0xff" byte is encountered. * !! Make sure there is enough stack space to host a * !! CONFIG_SPI_NOR_MAX_READ_SIZE sized buffer before enabling. */ #undef CONFIG_SPI_NOR_SMART_ERASE /* SPI master feature */ #undef CONFIG_SPI_MASTER /* SPI master halfduplex/3-wire mode */ #undef CONFIG_SPI_HALFDUPLEX /* Support STM32 SPI1 as master. */ #undef CONFIG_STM32_SPI1_MASTER /* SPI master configure gpios on init */ #undef CONFIG_SPI_MASTER_CONFIGURE_GPIOS /* Support SPI masters without GPIO-specified Chip Selects, instead rely on the * SPI master port's hardwired CS pin. */ #undef CONFIG_SPI_MASTER_NO_CS_GPIOS /* Support testing SPI slave controller driver. */ #undef CONFIG_SPS_TEST /* Default stack size to use for tasks, in bytes */ #undef CONFIG_STACK_SIZE /* Use 32-bit timer for clock source on stm32. */ #undef CONFIG_STM_HWTIMER32 /* Compile charger detect for STM32 */ #undef CONFIG_STM32_CHARGER_DETECT /* Fake hibernate mode */ #undef CONFIG_STM32L_FAKE_HIBERNATE /* * Compile common code to handle simple switch inputs such as the recovery * button input from the servo debug interface. */ #undef CONFIG_SWITCH /* Support dedicated recovery signal from servo board */ #undef CONFIG_SWITCH_DEDICATED_RECOVERY /* * System should remain unlocked even if write protect is enabled. * * NOTE: This should ONLY be defined during bringup, and should never be * defined on a shipping / released platform. */ #undef CONFIG_SYSTEM_UNLOCKED /* * Device can be a tablet as well as a clamshell. */ #undef CONFIG_TABLET_MODE /* * Add a virtual switch to indicate when we are in tablet mode. */ #undef CONFIG_TABLET_MODE_SWITCH /*****************************************************************************/ /* Task config */ /* * List of enabled tasks in ascending priority order. This is normally * defined in each board's ec.tasklist file. * * For each task, use the macro TASK_ALWAYS(n, r, d, s) for base tasks and * TASK_NOTEST(n, r, d, s) for tasks that can be excluded in test binaries, * where : * 'n' is the name of the task * 'r' is the main routine of the task * 'd' is an opaque parameter passed to the routine at startup * 's' is the stack size in bytes; must be a multiple of 8 */ #undef CONFIG_TASK_LIST /* * List of test tasks. Same format as CONFIG_TASK_LIST, but used to define * additional tasks for a unit test. Normally defined in * test/{testname}.tasklist. */ #undef CONFIG_TEST_TASK_LIST /* * List of tasks used by CTS * * cts.tasklist contains tasks run only for CTS. These tasks are added to the * tasks registered in ec.tasklist with higher priority. * * If a CTS suite does not define its own cts.tasklist, the common list is used * (i.e. cts/cts.tasklist). */ #undef CONFIG_CTS_TASK_LIST /* * Enable task profiling. * * Boards may #undef this to reduce image size and RAM usage. */ #define CONFIG_TASK_PROFILING /*****************************************************************************/ /* Temperature sensor config */ /* Compile common code for temperature sensor support */ #undef CONFIG_TEMP_SENSOR /* Support particular temperature sensor chips */ #undef CONFIG_TEMP_SENSOR_BD99992GW /* BD99992GW PMIC, on I2C bus */ #undef CONFIG_TEMP_SENSOR_EC_ADC /* Thermistors on EC's own ADC */ #undef CONFIG_TEMP_SENSOR_G781 /* G781 sensor, on I2C bus */ #undef CONFIG_TEMP_SENSOR_G782 /* G782 sensor, on I2C bus */ #undef CONFIG_TEMP_SENSOR_TMP006 /* TI TMP006 sensor, on I2C bus */ #undef CONFIG_TEMP_SENSOR_TMP432 /* TI TMP432 sensor, on I2C bus */ #undef CONFIG_THERMISTOR_NCP15WB /* NCP15WB thermistor */ /* * If defined, active-high GPIO which indicates temperature sensor chips are * powered. If not defined, temperature sensors are assumed to be always * powered. */ #undef CONFIG_TEMP_SENSOR_POWER_GPIO /* Compile common code for throttling the CPU based on the temp sensors */ #undef CONFIG_THROTTLE_AP /* * If defined, dptf is enabled to manage thermals. * * NOTE: This doesn't mean that thermal control is completely taken care by * DPTF. We have some hybrid solutions where the EC still manages the fans. */ #undef CONFIG_DPTF /*****************************************************************************/ /* Touchpad config */ /* Enable touchpad, you must pick a driver (currently, only Elan exists) */ #undef CONFIG_TOUCHPAD /* Enable Elan driver */ #undef CONFIG_TOUCHPAD_ELAN /* Set I2C port and address (8-bit) */ #undef CONFIG_TOUCHPAD_I2C_PORT #undef CONFIG_TOUCHPAD_I2C_ADDR /* * Enable touchpad FW update over USB update protocol, and define touchpad * virtual address and size. */ #undef CONFIG_TOUCHPAD_VIRTUAL_OFF #undef CONFIG_TOUCHPAD_VIRTUAL_SIZE /* * Include hashes of the touchpad FW in the EC image, passed as TOUCHPAD_FW * parameter to make command. */ #undef CONFIG_TOUCHPAD_HASH_FW /*****************************************************************************/ /* TPM-like configuration */ /* Speak the TPM SPI Hardware Protocol on the SPI slave interface */ #undef CONFIG_TPM_SPS /* Speak to the TPM 2.0 hardware protocol on the I2C slave interface */ #undef CONFIG_TPM_I2CS /* Record TPM events in circular buffer */ #undef CONFIG_TPM_LOGGING /*****************************************************************************/ /* USART stream config */ #undef CONFIG_STREAM_USART /* * Each USART stream can be individually enabled and accessible using the * stream interface provided in the usart_config struct. */ #undef CONFIG_STREAM_USART1 #undef CONFIG_STREAM_USART2 #undef CONFIG_STREAM_USART3 #undef CONFIG_STREAM_USART4 /*****************************************************************************/ /* U2F config: second factor authentication */ #undef CONFIG_U2F /*****************************************************************************/ /* USB stream config */ #undef CONFIG_STREAM_USB /*****************************************************************************/ /* UART config */ /* Baud rate for UARTs */ #define CONFIG_UART_BAUD_RATE 115200 /* Allow bit banging of a UARTs pins and bypassing the UART block. */ #undef CONFIG_UART_BITBANG /* UART index (number) for EC console */ #undef CONFIG_UART_CONSOLE /* UART index (number) for host UART, if present */ #undef CONFIG_UART_HOST /* Use uart_input_filter() to filter UART input. See prototype in uart.h */ #undef CONFIG_UART_INPUT_FILTER /* * Allow switching the EC console UART to an alternate pad. This must be * used for short transactions only, and EC is only able to receive data on * that alternate pad after it has been explicitly switched. */ #undef CONFIG_UART_PAD_SWITCH /* * UART receive buffer size in bytes. Must be a power of 2 for macros in * common/uart_buffering.c to work properly. Must be larger than * CONFIG_CONSOLE_INPUT_LINE_SIZE to copy and paste scripts. */ #define CONFIG_UART_RX_BUF_SIZE 128 /* Use DMA for UART input */ #undef CONFIG_UART_RX_DMA /* * On some platforms, UART receive DMA can't trigger an interrupt when a single * character is received. Those platforms poll for characters every HOOK_TICK. * When a character is received, make this many additional checks between then * and the next HOOK_TICK, to increase responsiveness of the console to input. */ #define CONFIG_UART_RX_DMA_RECHECKS 5 /* * UART transmit buffer size in bytes. Must be a power of 2 for macros in * common/uart_buffering.c to work properly. */ #define CONFIG_UART_TX_BUF_SIZE 512 /* Use DMA for UART output */ #undef CONFIG_UART_TX_DMA /* The DMA channel for UART. If not defined, default to UART1. */ #undef CONFIG_UART_TX_DMA_CH #undef CONFIG_UART_RX_DMA_CH /* The DMA peripheral request signal for UART TX. STM32 only. */ #undef CONFIG_UART_TX_DMA_PH /* The DMA channel mapping config for stm32f4. */ #undef CONFIG_UART_TX_REQ_CH #undef CONFIG_UART_RX_REQ_CH /*****************************************************************************/ /* USB PD config */ /* Include all USB Power Delivery modules */ #undef CONFIG_USB_POWER_DELIVERY /* Support for USB PD alternate mode */ #undef CONFIG_USB_PD_ALT_MODE /* Support for USB PD alternate mode of Downward Facing Port */ #undef CONFIG_USB_PD_ALT_MODE_DFP /* Check if max voltage request is allowed before each request */ #undef CONFIG_USB_PD_CHECK_MAX_REQUEST_ALLOWED /* Default state of PD communication disabled flag */ #undef CONFIG_USB_PD_COMM_DISABLED /* * Do not enable PD communication in RO as a security measure. * We don't want to allow communication to outside world until * we jump to RW. This can by overridden with the removal of * the write protect screw to allow for easier testing. */ #undef CONFIG_USB_PD_COMM_LOCKED /* Respond to custom vendor-defined messages over PD */ #undef CONFIG_USB_PD_CUSTOM_VDM /* Default USB data role when a USB PD debug accessory is seen */ #define CONFIG_USB_PD_DEBUG_DR PD_ROLE_DFP /* * Define to have a fixed PD Task debug level. * Undef to allow runtime change via console command. */ #undef CONFIG_USB_PD_DEBUG_LEVEL /* * Define if this board can enable VBUS discharge (eg. through a GPIO-controlled * discharge circuit, or through port controller registers) to discharge VBUS * rapidly on disconnect. */ #undef CONFIG_USB_PD_DISCHARGE /* * Define (along with CONFIG_USB_PD_DISCHARGE) if discharge circuit is * EC GPIO-controlled. */ #undef CONFIG_USB_PD_DISCHARGE_GPIO /* * Define (along with CONFIG_USB_PD_DISCHARGE) if discharge circuit is * using PD discharge registers. */ #undef CONFIG_USB_PD_DISCHARGE_TCPC /* Define if this board can act as a dual-role PD port (source and sink) */ #undef CONFIG_USB_PD_DUAL_ROLE /* Define if this board can used TCPC-controlled DRP toggle */ #undef CONFIG_USB_PD_DUAL_ROLE_AUTO_TOGGLE /* Initial DRP / toggle policy */ #define CONFIG_USB_PD_INITIAL_DRP_STATE PD_DRP_TOGGLE_OFF /* * Define if VBUS source GPIOs (GPIO_USB_C*_5V_EN) are active-low (and named * (..._L) rather than default active-high. */ #undef CONFIG_USB_PD_5V_EN_ACTIVE_LOW /* Dynamic USB PD source capability */ #undef CONFIG_USB_PD_DYNAMIC_SRC_CAP /* Support USB PD flash. */ #undef CONFIG_USB_PD_FLASH /* Check whether PD is the sole power source before flash erase operation */ #undef CONFIG_USB_PD_FLASH_ERASE_CHECK /* Define if this board, operating as a sink, can give power back to a source */ #undef CONFIG_USB_PD_GIVE_BACK /* Enable USB PD Rev3.0 features */ #undef CONFIG_USB_PD_REV30 /* Major and Minor ChromeOS specific PD device Hardware IDs. */ #undef CONFIG_USB_PD_HW_DEV_ID_BOARD_MAJOR #undef CONFIG_USB_PD_HW_DEV_ID_BOARD_MINOR /* HW & SW version for alternate mode discover identity response (4bits each) */ #undef CONFIG_USB_PD_IDENTITY_HW_VERS #undef CONFIG_USB_PD_IDENTITY_SW_VERS /* USB PD MCU slave address for host commands */ #define CONFIG_USB_PD_I2C_SLAVE_ADDR 0x3c /* Define if using internal comparator for PD receive */ #undef CONFIG_USB_PD_INTERNAL_COMP /* Record main PD events in a circular buffer */ #undef CONFIG_USB_PD_LOGGING /* The size in bytes of the FIFO used for event logging */ #define CONFIG_EVENT_LOG_SIZE 512 /* Save power by waking up on VBUS rather than polling CC */ #define CONFIG_USB_PD_LOW_POWER /* Allow chip to go into low power idle even when a PD device is attached */ #undef CONFIG_USB_PD_LOW_POWER_IDLE_WHEN_CONNECTED /* Number of USB PD ports */ #undef CONFIG_USB_PD_PORT_COUNT /* Simple DFP, such as power adapter, will not send discovery VDM on connect */ #undef CONFIG_USB_PD_SIMPLE_DFP /* Use comparator module for PD RX interrupt */ #define CONFIG_USB_PD_RX_COMP_IRQ /* Use TCPC module (type-C port controller) */ #undef CONFIG_USB_PD_TCPC /* Board provides specific TCPC init function */ #undef CONFIG_USB_PD_TCPC_BOARD_INIT /* Enable TCPC to enter low power mode */ #undef CONFIG_USB_PD_TCPC_LOW_POWER /* * Track VBUS level in TCPC module. This will only be needed if we're acting * as an external TCPC. */ #undef CONFIG_USB_PD_TCPC_TRACK_VBUS /* * Choose one of the following TCPMs (type-C port manager) to manage TCPC. The * TCPM stub is used to make direct function calls to TCPC when TCPC is on * the same MCU. The TCPCI TCPM uses the standard TCPCI i2c interface to TCPC. */ #undef CONFIG_USB_PD_TCPM_STUB #undef CONFIG_USB_PD_TCPM_TCPCI #undef CONFIG_USB_PD_TCPM_FUSB302 #undef CONFIG_USB_PD_TCPM_ITE83XX #undef CONFIG_USB_PD_TCPM_ANX74XX #undef CONFIG_USB_PD_TCPM_ANX7688 #undef CONFIG_USB_PD_TCPM_PS8751 #undef CONFIG_USB_PD_TCPM_PS8805 /* * Use this option if the TCPC port controller supports the optional register * 18h CONFIG_STANDARD_OUTPUT to steer the high-speed muxes. */ #undef CONFIG_USB_PD_TCPM_MUX /* * The TCPM must know whether VBUS is present in order to make proper state * transitions. In addition, charge_manager must know about VBUS presence in * order to make charging decisions. VBUS state can be determined by various * methods: * - Some TCPCs can detect and report the presence of VBUS. * - In some configurations, charger ICs can report the presence of VBUS. * - On some boards, dedicated VBUS interrupt pins are available. * - Some power path controllers (PPC) can report the presence of VBUS. * * Exactly one of these should be defined for all boards that run the PD * state machine. */ #undef CONFIG_USB_PD_VBUS_DETECT_TCPC #undef CONFIG_USB_PD_VBUS_DETECT_CHARGER #undef CONFIG_USB_PD_VBUS_DETECT_GPIO #undef CONFIG_USB_PD_VBUS_DETECT_PPC #undef CONFIG_USB_PD_VBUS_DETECT_NONE /* Define the type-c port controller I2C base address. */ #define CONFIG_TCPC_I2C_BASE_ADDR 0x9c /* Use this option to enable Try.SRC mode for Dual Role devices */ #undef CONFIG_USB_PD_TRY_SRC /* Set the default minimum battery percentage for Try.Src to be enabled */ #define CONFIG_USB_PD_TRY_SRC_MIN_BATT_SOC 1 /* Alternative configuration keeping only the TX part of PHY */ #undef CONFIG_USB_PD_TX_PHY_ONLY /* Use DAC as reference for comparator at 850mV. */ #undef CONFIG_PD_USE_DAC_AS_REF /* USB Product ID. */ #undef CONFIG_USB_PID /* USB Type-C Power Path Controllers (PPC) */ #undef CONFIG_USBC_PPC_SN5S330 /* Support for USB type-c superspeed mux */ #undef CONFIG_USBC_SS_MUX /* * Only configure USB type-c superspeed mux when DFP (for chipsets that * don't support being a UFP) */ #undef CONFIG_USBC_SS_MUX_DFP_ONLY /* Support v1.1 type-C connection state machine */ #undef CONFIG_USBC_BACKWARDS_COMPATIBLE_DFP /* Support for USB type-c vconn. Not needed for captive cables. */ #undef CONFIG_USBC_VCONN /* Support VCONN swap */ #undef CONFIG_USBC_VCONN_SWAP /* USB Binary device Object Store support */ #undef CONFIG_USB_BOS /* USB Device version of product */ #undef CONFIG_USB_BCD_DEV /* * Used during generation of VIF for USB Type-C Compliance Testing. * Indicates whether the UUT can communicate with USB 2.0 or USB 3.1 as a host * or as the Downstream Facing Port of a hub. */ #undef CONFIG_VIF_TYPE_C_CAN_ACT_AS_HOST /* * Used during generation of VIF for USB Type-C Compliance Testing. * Indicates whether the UUT has a captive cable. */ #undef CONFIG_VIF_CAPTIVE_CABLE /*****************************************************************************/ /* Compile chip support for the USB device controller */ #undef CONFIG_USB /* Support USB blob handler. */ #undef CONFIG_USB_BLOB /* Common USB / BC1.2 charger detection routines */ #undef CONFIG_USB_CHARGER /* External BC1.2 charger detection devices. */ #undef CONFIG_BC12_DETECT_BQ24392 #undef CONFIG_BC12_DETECT_PI3USB9281 /* Number of Pericom PI3USB9281 chips present in system */ #undef CONFIG_BC12_DETECT_PI3USB9281_CHIP_COUNT /* Enable USB serial console module. */ #undef CONFIG_USB_CONSOLE /* Support USB HID interface. */ #undef CONFIG_USB_HID /* Support USB HID keyboard interface. */ #undef CONFIG_USB_HID_KEYBOARD /* Support USB HID keyboard backlight. */ #undef CONFIG_USB_HID_KEYBOARD_BACKLIGHT /* Support USB HID touchpad interface. */ #undef CONFIG_USB_HID_TOUCHPAD /* HID touchpad logical dimensions */ #undef CONFIG_USB_HID_TOUCHPAD_LOGICAL_MAX_X #undef CONFIG_USB_HID_TOUCHPAD_LOGICAL_MAX_Y /* HID touchpad physical dimensions (tenth of mm) */ #undef CONFIG_USB_HID_TOUCHPAD_PHYSICAL_MAX_X #undef CONFIG_USB_HID_TOUCHPAD_PHYSICAL_MAX_Y /* USB device buffers and descriptors */ #undef CONFIG_USB_RAM_ACCESS_SIZE #undef CONFIG_USB_RAM_ACCESS_TYPE #undef CONFIG_USB_RAM_BASE #undef CONFIG_USB_RAM_SIZE /* Disable automatic connection of USB peripheral */ #undef CONFIG_USB_INHIBIT_CONNECT /* Disable automatic initialization of USB peripheral */ #undef CONFIG_USB_INHIBIT_INIT /* Support control of multiple PHY */ #undef CONFIG_USB_SELECT_PHY /* Select which USB PHY will be used at startup */ #undef CONFIG_USB_SELECT_PHY_DEFAULT /* Support simple control of power to the device's USB ports */ #undef CONFIG_USB_PORT_POWER_DUMB /* * Support supplying USB power in S3, if the host leaves the port enabled when * entering S3. */ #undef CONFIG_USB_PORT_POWER_IN_S3 /* * Support smart power control to the device's USB ports, using * dedicated power control chips. This potentially enables automatic * negotiation of supplying more power to peripherals. */ #undef CONFIG_USB_PORT_POWER_SMART /* * Support smart power control to the device's USB ports, however only CDP and * SDP are supported. Usually this is the case if all the control lines to the * charging port controller are hard-wired. */ #undef CONFIG_USB_PORT_POWER_SMART_CDP_SDP_ONLY /* * Override the default charging mode for USB smart power control. * Value is selected from usb_charge_mode in include/usb_charge.h */ #undef CONFIG_USB_PORT_POWER_SMART_DEFAULT_MODE /* * Smart USB power control can use a full set of control signals to the USB * port power chip, or a reduced set. If this is defined, use the reduced set. */ #undef CONFIG_USB_PORT_POWER_SMART_SIMPLE /* Number of smart USB power ports. */ #define CONFIG_USB_PORT_POWER_SMART_PORT_COUNT 2 /* * Smart USB power control current limit pins may be inverted. In this case * they are active low and the GPIO names will be GPIO_USBn_ILIM_SEL_L. */ #undef CONFIG_USB_PORT_POWER_SMART_INVERTED /* * Support waking up host by setting the K-state on the data lines (requires * CONFIG_USB_SUSPEND to be set as well). */ #undef CONFIG_USB_REMOTE_WAKEUP /* Support programmable USB device iSerial field. */ #undef CONFIG_USB_SERIALNO /* Support reporting of configuration bMaxPower in mA */ #define CONFIG_USB_MAXPOWER_MA 500 /* Support reporting as self powered in USB configuration. */ #undef CONFIG_USB_SELF_POWERED /* Support correct handling of USB suspend (host-initiated). */ #undef CONFIG_USB_SUSPEND /* Default pull-up value on the USB-C ports when they are used as source. */ #define CONFIG_USB_PD_PULLUP TYPEC_RP_1A5 /* * Override the pull-up value when only zero or one port is actively sourcing * current and we can advertise more current than what is defined by * `CONFIG_USB_PD_PULLUP`. * Should be defined with one of the tcpc_rp_value. */ #undef CONFIG_USB_PD_MAX_SINGLE_SOURCE_CURRENT /******************************************************************************/ /* stm32f4 dwc usb configs. */ /* Set USB speed to FS rather than HS */ #undef CONFIG_USB_DWC_FS /******************************************************************************/ /* USB port switch */ /* Support the ITE IT5205 Type-C USB alternate mode mux. */ #undef CONFIG_USB_MUX_IT5205 /* Support the Pericom PI3USB30532 USB3.0/DP1.2 Matrix Switch */ #undef CONFIG_USB_MUX_PI3USB30532 /* Support the Parade PS8740 Type-C Redriving Switch */ #undef CONFIG_USB_MUX_PS8740 /* Support the Parade PS8743 Type-C Redriving Switch */ #undef CONFIG_USB_MUX_PS8743 /* 'Virtual' USB mux under host (not EC) control */ #undef CONFIG_USB_MUX_VIRTUAL /*****************************************************************************/ /* USB GPIO config */ #undef CONFIG_USB_GPIO /*****************************************************************************/ /* USB SPI config */ #undef CONFIG_USB_SPI /*****************************************************************************/ /* USB I2C config */ #undef CONFIG_USB_I2C /* Allowed read/write count for USB over I2C */ #define CONFIG_USB_I2C_MAX_WRITE_COUNT 60 #define CONFIG_USB_I2C_MAX_READ_COUNT 60 /*****************************************************************************/ /* USB Power monitoring interface config */ #undef CONFIG_USB_POWER /*****************************************************************************/ /* * USB stream signing config. This allows data read over UART or SPI * to have a signature generated that can be used to validate the data * offline based on H1's registered key. Used by mn50. */ #undef CONFIG_STREAM_SIGNATURE /*****************************************************************************/ /* Support early firmware selection */ #undef CONFIG_VBOOT_EFS /* Support computing hash of code for verified boot */ #undef CONFIG_VBOOT_HASH /* Support for secure temporary storage for verified boot */ #undef CONFIG_VSTORE /* Number of supported slots for secure temporary storage */ #undef CONFIG_VSTORE_SLOT_COUNT /*****************************************************************************/ /* Watchdog config */ /* * Compile watchdog timer support. The watchdog timer will reboot the system * if the hook task (which is the lowest-priority task on the system) gets * starved for CPU time and isn't able to fire its HOOK_TICK event. */ #define CONFIG_WATCHDOG /* * Try to detect a watchdog that is about to fire, and print a trace. This is * required on chips such as STM32 where the watchdog timer simply reboots the * system without any early warning. */ #undef CONFIG_WATCHDOG_HELP /* Watchdog period in ms; see also AUX_TIMER_PERIOD_MS */ #define CONFIG_WATCHDOG_PERIOD_MS 1600 /* * Fire auxiliary timer 500ms before watchdog timer expires. This leaves * some time for debug trace to be printed. */ #define CONFIG_AUX_TIMER_PERIOD_MS (CONFIG_WATCHDOG_PERIOD_MS - 500) /*****************************************************************************/ /* WebUSB config */ /* * Enable the WebUSB support and define its URL. * Export a WebUSB Platform Descriptor in the Binary Object Store descriptor. * The WebUSB landing page URL is equal to 'CONFIG_WEBUSB_URL' plus the * https:// prefix. * This requires CONFIG_USB_BOS. */ #undef CONFIG_WEBUSB_URL /*****************************************************************************/ /* * Support controlling power to WiFi, WWAN (3G/LTE), and/or bluetooth modules. */ #undef CONFIG_WIRELESS /* * Support for WiFi devices that must remain powered in suspend. Set to the * combination of EC_WIRELESS_SWITCH flags (from ec_commands.h) which should * be set in suspend. */ #undef CONFIG_WIRELESS_SUSPEND /* WiFi power control signal is active-low. */ #undef CONFIG_WLAN_POWER_ACTIVE_LOW /* * Write protect signal is active-high. If this is defined, there must be a * GPIO named GPIO_WP; if not defined, there must be a GPIO names GPIO_WP_L. */ #undef CONFIG_WP_ACTIVE_HIGH /* * The write protect signal is always asserted, * independantly of the GPIO existence or current value. */ #undef CONFIG_WP_ALWAYS /* * If needed to allocate some free space in the base of the RO or RW section * of the image, define these to be equal the required size of the free space. */ #undef CONFIG_RO_HEAD_ROOM #undef CONFIG_RW_HEAD_ROOM /* Firmware upgrade options. */ /* Firmware updates using other than HC channel(s). */ #undef CONFIG_NON_HC_FW_UPDATE #undef CONFIG_USB_FW_UPDATE /* A different config for the same update. TODO(vbendeb): dedup these */ #undef CONFIG_USB_UPDATE /* Add support for pairing over the USB update interface. */ #undef CONFIG_USB_PAIRING /* PDU size for fw update over USB (or TPM). */ #define CONFIG_UPDATE_PDU_SIZE 1024 /* * If defined, charge_get_state returns a special status if battery is * discharging and battery is nearly full. */ #undef CONFIG_PWR_STATE_DISCHARGE_FULL /* * Define this if a chip needs to add some information to the common 'version' * command output. */ #undef CONFIG_EXTENDED_VERSION_INFO /* * Define this if board ID support is required. For g chip based boards it * allows to nail different images to different boards. */ #undef CONFIG_BOARD_ID_SUPPORT /*****************************************************************************/ /* * Include board and core configs, since those hold the CONFIG_ constants for a * given configuration. This guarantees they get included everywhere, and * fixes a fairly common bug where we gate out code with #ifndef * CONFIG_SOMETHING and but forget to include both of these. * * Board is included after chip, so that chip defaults can be overridden on a * per-board basis as needed. */ #ifdef __CROS_EC_CONFIG_CHIP_H #error Include config.h instead of config_chip.h! #endif #ifdef __BOARD_H #error Include config.h instead of board.h! #endif #include "config_chip.h" #include "board.h" /******************************************************************************/ /* * Set default data ram size unless it's customized by the chip. */ #ifndef CONFIG_DATA_RAM_SIZE #define CONFIG_DATA_RAM_SIZE CONFIG_RAM_SIZE #endif /******************************************************************************/ /* * Disable the built-in console history if using the experimental console. * * The experimental console keeps its own session-persistent history which * survives EC reboot. It also requires CRC8 for command integrity. */ #ifdef CONFIG_EXPERIMENTAL_CONSOLE #undef CONFIG_CONSOLE_HISTORY #define CONFIG_CRC8 #endif /* defined(CONFIG_EXPERIMENTAL_CONSOLE) */ /******************************************************************************/ /* * Throttle AP must have temperature sensor enabled to get the readings for * thermal throttling. */ #if defined(CONFIG_THROTTLE_AP) && !defined(CONFIG_TEMP_SENSOR) #define CONFIG_TEMP_SENSOR #endif /******************************************************************************/ /* * DPTF must have temperature sensor enabled to get the readings for * generating DPTF thresholds events. */ #if defined(CONFIG_DPTF) && !defined(CONFIG_TEMP_SENSOR) #define CONFIG_TEMP_SENSOR #endif /******************************************************************************/ /* The Matrix Keyboard Protocol depends on MKBP events. */ #ifdef CONFIG_KEYBOARD_PROTOCOL_MKBP #define CONFIG_MKBP_EVENT #endif /******************************************************************************/ /* Set generic orientation config if a specific orientation config is set. */ #if defined(CONFIG_KX022_ORIENTATION_SENSOR) || \ defined(CONFIG_BMI160_ORIENTATION_SENSOR) #ifndef CONFIG_ACCEL_FIFO #error CONFIG_ACCEL_FIFO must be defined to use hw orientation sensor support #endif #define CONFIG_ORIENTATION_SENSOR #endif /*****************************************************************************/ /* Define CONFIG_BATTERY if board has a battery. */ #if defined(CONFIG_BATTERY_BQ20Z453) || \ defined(CONFIG_BATTERY_BQ27541) || \ defined(CONFIG_BATTERY_BQ27621) || \ defined(CONFIG_BATTERY_MAX17055) || \ defined(CONFIG_BATTERY_SMART) #define CONFIG_BATTERY #endif /*****************************************************************************/ /* Define CONFIG_USBC_PPC if board has a USB Type-C Power Path Controller. */ #if defined(CONFIG_USBC_PPC_SN5S330) #define CONFIG_USBC_PPC #endif /* "has a PPC" */ /*****************************************************************************/ /* * Define CONFIG_USB_PD_VBUS_MEASURE_CHARGER if the charger on the board * supports VBUS measurement. */ #if defined(CONFIG_CHARGER_BD9995X) || \ defined(CONFIG_CHARGER_RT9466) || \ defined(CONFIG_CHARGER_RT9467) #define CONFIG_USB_PD_VBUS_MEASURE_CHARGER #endif /*****************************************************************************/ /* * Handle task-dependent configs. * * This prevent sub-modules from being compiled when the task and parent module * are not present. */ #ifndef HAS_TASK_CHIPSET #undef CONFIG_CHIPSET_APOLLOLAKE #undef CONFIG_CHIPSET_BRASWELL #undef CONFIG_CHIPSET_CANNONLAKE #undef CONFIG_CHIPSET_MEDIATEK #undef CONFIG_CHIPSET_RK3399 #undef CONFIG_CHIPSET_ROCKCHIP #undef CONFIG_CHIPSET_SKYLAKE #undef CONFIG_CHIPSET_STONEY #undef CONFIG_POWER_COMMON #undef CONFIG_POWER_TRACK_HOST_SLEEP_STATE #endif #ifndef HAS_TASK_KEYPROTO #undef CONFIG_KEYBOARD_PROTOCOL_8042 /* * Note that we don't undef CONFIG_KEYBOARD_PROTOCOL_MKBP, because it doesn't * have its own task. */ #endif #ifndef HAS_TASK_PDCMD #undef CONFIG_HOSTCMD_PD #endif /*****************************************************************************/ /* * Apply test config overrides last, since tests need to override some of the * config flags in non-standard ways to mock only parts of the system. */ #include "test_config.h" /* * Sanity checks to make sure some of the configs above make sense. */ #if (CONFIG_AUX_TIMER_PERIOD_MS) < ((HOOK_TICK_INTERVAL_MS) * 2) #error "CONFIG_AUX_TIMER_PERIOD_MS must be at least 2x HOOK_TICK_INTERVAL_MS" #endif #ifdef CONFIG_USB_SERIALNO #define CONFIG_SERIALNO_LEN 28 #endif #ifndef CONFIG_EC_MAX_SENSOR_FREQ_MILLIHZ #define CONFIG_EC_MAX_SENSOR_FREQ_MILLIHZ \ CONFIG_EC_MAX_SENSOR_FREQ_DEFAULT_MILLIHZ #endif #endif /* __CROS_EC_CONFIG_H */
30.821484
80
0.731092
[ "geometry", "object", "vector", "model" ]
d2818fa776d37ef50b1309419ab1c3dfc9469526
11,032
c
C
minimal-examples/dbus-client/minimal-dbus-ws-proxy-testclient/minimal-dbus-ws-proxy-testclient.c
CDK-Vonkil/libwebsockets
d618ee87611c5d4c139c7d7359e655472f27d9ea
[ "MIT" ]
2
2020-07-14T19:01:27.000Z
2020-09-30T09:56:02.000Z
minimal-examples/dbus-client/minimal-dbus-ws-proxy-testclient/minimal-dbus-ws-proxy-testclient.c
CDK-Vonkil/libwebsockets
d618ee87611c5d4c139c7d7359e655472f27d9ea
[ "MIT" ]
34
2019-05-25T01:16:31.000Z
2021-11-16T23:56:30.000Z
minimal-examples/dbus-client/minimal-dbus-ws-proxy-testclient/minimal-dbus-ws-proxy-testclient.c
CDK-Vonkil/libwebsockets
d618ee87611c5d4c139c7d7359e655472f27d9ea
[ "MIT" ]
4
2020-04-14T08:25:16.000Z
2020-10-07T07:49:27.000Z
/* * lws-minimal-dbus-ws-proxy-testclient * * Written in 2010-2019 by Andy Green <andy@warmcat.com> * * This file is made available under the Creative Commons CC0 1.0 * Universal Public Domain Dedication. * * This acts as a test client over DBUS, opening a session with * minimal-dbus-ws-proxy and sending and receiving data on the libwebsockets * mirror demo page. */ #include <stdbool.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <libwebsockets.h> #include <libwebsockets/lws-dbus.h> /* * These are the various states our connection can be in, both with regards * to the direct connection to the proxy, and the state of the onward ws * connection the proxy opens at our request. */ enum lws_dbus_client_state { LDCS_NOTHING, /* no connection yet */ LDCS_CONN, /* conn to proxy */ LDCS_CONN_WAITING_ONWARD, /* conn to proxy, awaiting proxied conn */ LDCS_CONN_ONWARD, /* conn to proxy and onward conn OK */ LDCS_CONN_CLOSED, /* conn to proxy but onward conn closed */ LDCS_CLOSED, /* connection to proxy is closed */ }; /* * our expanded dbus context */ struct lws_dbus_ctx_wsproxy_client { struct lws_dbus_ctx ctx; enum lws_dbus_client_state state; }; static struct lws_dbus_ctx_wsproxy_client *dbus_ctx; static struct lws_context *context; static int interrupted, autoexit_budget = -1, count_rx, count_tx; #define THIS_INTERFACE "org.libwebsockets.wsclientproxy" #define THIS_OBJECT "/org/libwebsockets/wsclientproxy" #define THIS_BUSNAME "org.libwebsockets.wsclientproxy" #define THIS_LISTEN_PATH "unix:abstract=org.libwebsockets.wsclientproxy" static void state_transition(struct lws_dbus_ctx_wsproxy_client *dcwc, enum lws_dbus_client_state state) { lwsl_notice("%s: %p: from state %d -> %d\n", __func__, dcwc,dcwc->state, state); dcwc->state = state; } static DBusHandlerResult filter(DBusConnection *conn, DBusMessage *message, void *data) { struct lws_dbus_ctx_wsproxy_client *dcwc = (struct lws_dbus_ctx_wsproxy_client *)data; const char *str; if (!dbus_message_get_args(message, NULL, DBUS_TYPE_STRING, &str, DBUS_TYPE_INVALID)) return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; /* received ws data */ if (dbus_message_is_signal(message, THIS_INTERFACE, "Receive")) { lwsl_user("%s: Received '%s'\n", __func__, str); count_rx++; } /* proxy ws connection failed */ if (dbus_message_is_signal(message, THIS_INTERFACE, "Status") && !strcmp(str, "ws client connection error")) state_transition(dcwc, LDCS_CONN_CLOSED); /* proxy ws connection succeeded */ if (dbus_message_is_signal(message, THIS_INTERFACE, "Status") && !strcmp(str, "ws client connection established")) state_transition(dcwc, LDCS_CONN_ONWARD); /* proxy ws connection has closed */ if (dbus_message_is_signal(message, THIS_INTERFACE, "Status") && !strcmp(str, "ws client connection closed")) state_transition(dcwc, LDCS_CONN_CLOSED); return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; } static void destroy_dbus_client_conn(struct lws_dbus_ctx_wsproxy_client **pdcwc) { struct lws_dbus_ctx_wsproxy_client *dcwc = *pdcwc; if (!dcwc || !dcwc->ctx.conn) return; lwsl_notice("%s\n", __func__); dbus_connection_remove_filter(dcwc->ctx.conn, filter, &dcwc->ctx); dbus_connection_close(dcwc->ctx.conn); dbus_connection_unref(dcwc->ctx.conn); free(dcwc); *pdcwc = NULL; } /* * This callback is coming when lws has noticed the fd took a POLLHUP. The * ctx has effectively gone out of scope before this, and the connection can * be cleaned up and the ctx freed. */ static void cb_closing(struct lws_dbus_ctx *ctx) { struct lws_dbus_ctx_wsproxy_client *dcwc = (struct lws_dbus_ctx_wsproxy_client *)ctx; lwsl_err("%s: closing\n", __func__); if (dcwc == dbus_ctx) dbus_ctx = NULL; destroy_dbus_client_conn(&dcwc); interrupted = 1; } static struct lws_dbus_ctx_wsproxy_client * create_dbus_client_conn(struct lws_vhost *vh, int tsi, const char *ads) { struct lws_dbus_ctx_wsproxy_client *dcwc; DBusError e; dcwc = malloc(sizeof(*dcwc)); if (!dcwc) return NULL; memset(dcwc, 0, sizeof(*dcwc)); dcwc->state = LDCS_NOTHING; dcwc->ctx.vh = vh; dcwc->ctx.tsi = tsi; dbus_error_init(&e); lwsl_user("%s: connecting to '%s'\n", __func__, ads); #if 1 /* connect to our daemon bus */ dcwc->ctx.conn = dbus_connection_open_private(ads, &e); if (!dcwc->ctx.conn) { lwsl_err("%s: Failed to connect: %s\n", __func__, e.message); goto fail; } #else /* connect to the SYSTEM bus */ dcwc->ctx.conn = dbus_bus_get(DBUS_BUS_SYSTEM, &e); if (!dcwc->ctx.conn) { lwsl_err("%s: Failed to get a session DBus connection: %s\n", __func__, e.message); goto fail; } #endif dbus_connection_set_exit_on_disconnect(dcwc->ctx.conn, 0); if (!dbus_connection_add_filter(dcwc->ctx.conn, filter, &dcwc->ctx, NULL)) { lwsl_err("%s: Failed to add filter\n", __func__); goto fail; } /* * This is the part that binds the connection to lws watcher and * timeout handling provided by lws */ if (lws_dbus_connection_setup(&dcwc->ctx, dcwc->ctx.conn, cb_closing)) { lwsl_err("%s: connection bind to lws failed\n", __func__); goto fail; } state_transition(dcwc, LDCS_CONN); lwsl_notice("%s: created OK\n", __func__); return dcwc; fail: dbus_error_free(&e); free(dcwc); return NULL; } void sigint_handler(int sig) { interrupted = 1; } /* * This gets called if we timed out waiting for the dbus server reply, or the * reply arrived. */ static void pending_call_notify(DBusPendingCall *pending, void *data) { const char *payload; DBusMessage *msg; if (!dbus_pending_call_get_completed(pending)) { lwsl_err("%s: timed out waiting for reply\n", __func__); goto bail; } msg = dbus_pending_call_steal_reply(pending); if (!msg) goto bail; if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &payload, DBUS_TYPE_INVALID)) { goto bail1; } lwsl_user("%s: received '%s'\n", __func__, payload); bail1: dbus_message_unref(msg); bail: dbus_pending_call_unref(pending); } static int remote_method_call(struct lws_dbus_ctx_wsproxy_client *dcwc) { char _uri[96]; const char *subprotocol = "lws-mirror-protocol", *uri = _uri; DBusMessage *msg; int ret = 1; /* * make our own private mirror session... because others may run this * at the same time against libwebsockets.org... as happened 2019-03-14 * and broke travis tests :-) */ lws_snprintf(_uri, sizeof(_uri), "wss://libwebsockets.org/?mirror=dbt-%d", (int)getpid()); msg = dbus_message_new_method_call( /* dest */ THIS_BUSNAME, /* object-path */ THIS_OBJECT, /* interface */ THIS_INTERFACE, /* method */ "Connect"); if (!msg) return 1; if (!dbus_message_append_args(msg, DBUS_TYPE_STRING, &uri, DBUS_TYPE_STRING, &subprotocol, DBUS_TYPE_INVALID)) goto bail; lwsl_user("%s: requesting proxy connection %s %s\n", __func__, uri, subprotocol); if (!dbus_connection_send_with_reply(dcwc->ctx.conn, msg, &dcwc->ctx.pc, DBUS_TIMEOUT_USE_DEFAULT)) { lwsl_err("%s: unable to send\n", __func__); goto bail; } dbus_pending_call_set_notify(dcwc->ctx.pc, pending_call_notify, &dcwc->ctx, NULL); state_transition(dcwc, LDCS_CONN_WAITING_ONWARD); ret = 0; bail: dbus_message_unref(msg); return ret; } /* * Stub lws protocol, just so we can get synchronous timers conveniently. * * Set up a 1Hz timer and if our connection state is suitable, use that * to write mirror protocol drawing packets to the proxied ws connection */ static int callback_just_timer(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) { char payload[64]; const char *ws_pkt = payload; DBusMessage *msg; switch (reason) { case LWS_CALLBACK_PROTOCOL_INIT: case LWS_CALLBACK_USER: lwsl_info("%s: LWS_CALLBACK_USER\n", __func__); if (!dbus_ctx || dbus_ctx->state != LDCS_CONN_ONWARD) goto again; if (autoexit_budget > 0) { if (!--autoexit_budget) { lwsl_notice("reached autoexit budget\n"); interrupted = 1; break; } } msg = dbus_message_new_method_call(THIS_BUSNAME, THIS_OBJECT, THIS_INTERFACE, "Send"); if (!msg) break; lws_snprintf(payload, sizeof(payload), "d #%06X %d %d %d %d;", rand() & 0xffffff, rand() % 480, rand() % 300, rand() % 480, rand() % 300); if (!dbus_message_append_args(msg, DBUS_TYPE_STRING, &ws_pkt, DBUS_TYPE_INVALID)) { dbus_message_unref(msg); break; } if (!dbus_connection_send_with_reply(dbus_ctx->ctx.conn, msg, &dbus_ctx->ctx.pc, DBUS_TIMEOUT_USE_DEFAULT)) { lwsl_err("%s: unable to send\n", __func__); dbus_message_unref(msg); break; } dbus_message_unref(msg); dbus_pending_call_set_notify(dbus_ctx->ctx.pc, pending_call_notify, &dbus_ctx->ctx, NULL); count_tx++; again: lws_timed_callback_vh_protocol(lws_get_vhost(wsi), lws_get_protocol(wsi), LWS_CALLBACK_USER, 2); break; default: break; } return 0; } static struct lws_protocols protocols[] = { { "_just_timer", callback_just_timer, 0, 10, 0, NULL, 0 }, { } }; int main(int argc, const char **argv) { struct lws_vhost *vh; struct lws_context_creation_info info; const char *p; int n = 0, logs = LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE /* for LLL_ verbosity above NOTICE to be built into lws, * lws must have been configured and built with * -DCMAKE_BUILD_TYPE=DEBUG instead of =RELEASE */ /* | LLL_INFO */ /* | LLL_PARSER */ /* | LLL_HEADER */ /* | LLL_EXT */ /* | LLL_CLIENT */ /* | LLL_LATENCY */ /* | LLL_DEBUG */ /* | LLL_THREAD */; signal(SIGINT, sigint_handler); if ((p = lws_cmdline_option(argc, argv, "-d"))) logs = atoi(p); if ((p = lws_cmdline_option(argc, argv, "-x"))) autoexit_budget = atoi(p); lws_set_log_level(logs, NULL); lwsl_user("LWS minimal DBUS ws proxy testclient\n"); memset(&info, 0, sizeof info); /* otherwise uninitialized garbage */ info.options = LWS_SERVER_OPTION_EXPLICIT_VHOSTS; info.protocols = protocols; context = lws_create_context(&info); if (!context) { lwsl_err("lws init failed\n"); return 1; } info.options |= LWS_SERVER_OPTION_HTTP_HEADERS_SECURITY_BEST_PRACTICES_ENFORCE; vh = lws_create_vhost(context, &info); if (!vh) goto bail; dbus_ctx = create_dbus_client_conn(vh, 0, THIS_LISTEN_PATH); if (!dbus_ctx) goto bail1; if (remote_method_call(dbus_ctx)) goto bail2; /* lws event loop (default poll one) */ while (n >= 0 && !interrupted) n = lws_service(context, 0); bail2: destroy_dbus_client_conn(&dbus_ctx); bail1: /* this is required for valgrind-cleanliness */ dbus_shutdown(); lws_context_destroy(context); lwsl_notice("Exiting cleanly, rx: %d, tx: %d\n", count_rx, count_tx); return 0; bail: lwsl_err("%s: failed to start\n", __func__); lws_context_destroy(context); return 1; }
23.982609
77
0.702411
[ "object" ]
d28e9b9ed11ff272433ea8820137039882b3aa3d
2,943
h
C
nx/include/switch/types.h
tiliarou/libnx
372825b1bac0b50b92b8c824fe1542939cc39ebb
[ "ISC" ]
null
null
null
nx/include/switch/types.h
tiliarou/libnx
372825b1bac0b50b92b8c824fe1542939cc39ebb
[ "ISC" ]
null
null
null
nx/include/switch/types.h
tiliarou/libnx
372825b1bac0b50b92b8c824fe1542939cc39ebb
[ "ISC" ]
null
null
null
/** * @file switch/types.h * @brief Various system types. * @copyright libnx Authors */ #pragma once #include <stdint.h> #include <stdbool.h> #include <stddef.h> #include <stdalign.h> /// The maximum value of a u64. #define U64_MAX UINT64_MAX #ifndef SSIZE_MAX #ifdef SIZE_MAX #define SSIZE_MAX ((SIZE_MAX) >> 1) #endif #endif typedef uint8_t u8; ///< 8-bit unsigned integer. typedef uint16_t u16; ///< 16-bit unsigned integer. typedef uint32_t u32; ///< 32-bit unsigned integer. typedef uint64_t u64; ///< 64-bit unsigned integer. typedef __uint128_t u128; ///< 128-bit unsigned integer. typedef int8_t s8; ///< 8-bit signed integer. typedef int16_t s16; ///< 16-bit signed integer. typedef int32_t s32; ///< 32-bit signed integer. typedef int64_t s64; ///< 64-bit signed integer. typedef __int128_t s128; ///< 128-bit unsigned integer. typedef volatile u8 vu8; ///< 8-bit volatile unsigned integer. typedef volatile u16 vu16; ///< 16-bit volatile unsigned integer. typedef volatile u32 vu32; ///< 32-bit volatile unsigned integer. typedef volatile u64 vu64; ///< 64-bit volatile unsigned integer. typedef volatile u128 vu128; ///< 128-bit volatile unsigned integer. typedef volatile s8 vs8; ///< 8-bit volatile signed integer. typedef volatile s16 vs16; ///< 16-bit volatile signed integer. typedef volatile s32 vs32; ///< 32-bit volatile signed integer. typedef volatile s64 vs64; ///< 64-bit volatile signed integer. typedef volatile s128 vs128; ///< 128-bit volatile signed integer. typedef u32 Handle; ///< Kernel object handle. typedef u32 Result; ///< Function error code result type. typedef void (*ThreadFunc)(void *); ///< Thread entrypoint function. typedef void (*VoidFn)(void); ///< Function without arguments nor return value. /// Creates a bitmask from a bit number. #ifndef BIT #define BIT(n) (1U<<(n)) #endif /// Packs a struct so that it won't include padding bytes. #ifndef PACKED #define PACKED __attribute__((packed)) #endif /// Marks a function as not returning, for the purposes of compiler optimization. #ifndef NORETURN #define NORETURN __attribute__((noreturn)) #endif /// Performs a dummy operation on the specified argument in order to silence compiler warnings about unused arguments. #ifndef IGNORE_ARG #define IGNORE_ARG(x) (void)(x) #endif /// Flags a function as deprecated. #ifndef DEPRECATED #ifndef LIBNX_NO_DEPRECATION #define DEPRECATED __attribute__ ((deprecated)) #else #define DEPRECATED #endif #endif /// Flags a function as (always) inline. #define NX_INLINE __attribute__((always_inline)) static inline /// Flags a function as constexpr in C++14 and above; or as (always) inline otherwise. #if __cplusplus >= 201402L #define NX_CONSTEXPR NX_INLINE constexpr #else #define NX_CONSTEXPR NX_INLINE #endif /// Invalid handle. #define INVALID_HANDLE ((Handle) 0)
31.98913
118
0.713218
[ "object" ]
d29826b989502617d109bd3caaf882d9f171183e
3,580
h
C
include/operators/LogSoftmax.h
SubhamIO/dnnCompiler
a9df5ab0eefe0f48a1416fe504f50e2bf71aeecc
[ "Apache-2.0" ]
1
2019-08-19T05:35:07.000Z
2019-08-19T05:35:07.000Z
include/operators/LogSoftmax.h
SubhamIO/dnnCompiler
a9df5ab0eefe0f48a1416fe504f50e2bf71aeecc
[ "Apache-2.0" ]
null
null
null
include/operators/LogSoftmax.h
SubhamIO/dnnCompiler
a9df5ab0eefe0f48a1416fe504f50e2bf71aeecc
[ "Apache-2.0" ]
null
null
null
// Copyright 2018 The AITS DNNC Authors.All Rights Reserved. // // Licensed to the Apache Software Foundation(ASF) under one // or more contributor license agreements.See the NOTICE file // distributed with this work for additional information // regarding copyright ownership.The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License.You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied.See the License for the // specific language governing permissionsand limitations // under the License. // // This file is part of AITS DNN compiler maintained at // https://github.com/ai-techsystems/dnnCompiler // // Eigen cwise unsupported-tensors(written TODO in original doc) // computing softmax as per axis(https://en.wikipedia.org/wiki/Softmax_function) #pragma once #include "operators/baseOperator.h" #include <string> using namespace Eigen; namespace dnnc { /*! The operator computes the logsoftmax (log of softmax) values for each layer * in the batch of the given input. */ /*! Input does not need to explicitly be a 2D vector; rather, it will be coerced * into one: */ /*! A tensor of N-dimension \f$ [a_0, a_1, ..., a_{k-1}, a_k, ..., a_{n-1}] \f$ * where k is a attribute ,will be coerced into 2-D \f$ [a_0 * ... * a_{k-1}, * a_k * ... * a_{n-1}] \f$ .*/ template <typename T> class LogSoftmax : public baseOperator<T, T, T> { // LogSoftmax attributes protected: // default int axis = 1; /*!< Describes the axis of the inputs when coerced to 2D; defaults to one because the 0th axis most likely describes the batch_size */ public: LogSoftmax(std::string name = "opLogSoftmax", int axis = 1) : baseOperator<T, T, T>(opLogSoftmax, name) { this->axis = axis; } bool getAttribute(OPATTR attrName, int &obj) { if (attrName == attr_axis) { obj = axis; return true; } return false; } tensor<T> compute(tensor<T> a/*< The input tensor that will be coerced into a 2D matrix of size (NxD) as described in operator definition*/) { if (!(this->template type_check<float, double>(typeid(T)))) throw std::invalid_argument( "Constrain input and output types to float tensors."); if (axis >= int(a.rank())) std::invalid_argument("Reshaping failed"); std::vector<size_t> original_shape = a.shape(); size_t axis1 = 1; size_t axis2 = 1; for (int i = 0; i < axis; i++) { axis1 *= a.shape()[i]; } if (axis1 > a.length()) std::invalid_argument("Reshaping failed.Check Axis"); axis2 = a.length() / axis1; std::vector<size_t> shape{axis1, axis2}; a.reshape(shape); tensor<T> result(a.shape()[0], a.shape()[1]); Eigen::MatrixXf::Index max_index; DNNC_EIGEN_MATRIX(eigenMatrix1, T, a); for (int i = 0; i < int(a.shape()[0]); i++) { float sum = 0; float e_x = 0; float max_x = eigenMatrix1.row(i).maxCoeff(&max_index); for (int j = 0; j < int(a.shape()[1]); j++) { e_x = exp(eigenMatrix1(i, j) - max_x); sum += e_x; } for (int j = 0; j < int(a.shape()[1]); j++) { result(i, j) = eigenMatrix1(i, j) - max_x - log(sum); } } result.reshape(original_shape); return result; } }; } // namespace dnnc
35.8
144
0.654469
[ "shape", "vector" ]
d2989d213b218fb22d7621bf1d90ecb74522b1bb
95,812
c
C
src/libserver/rspamd_symcache.c
pombredanne/rspamd
67470931229eda9003de0911ba875e47321c5466
[ "Apache-2.0" ]
null
null
null
src/libserver/rspamd_symcache.c
pombredanne/rspamd
67470931229eda9003de0911ba875e47321c5466
[ "Apache-2.0" ]
null
null
null
src/libserver/rspamd_symcache.c
pombredanne/rspamd
67470931229eda9003de0911ba875e47321c5466
[ "Apache-2.0" ]
null
null
null
/*- * Copyright 2016 Vsevolod Stakhov * * 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 "config.h" #include "util.h" #include "rspamd.h" #include "message.h" #include "rspamd_symcache.h" #include "cfg_file.h" #include "lua/lua_common.h" #include "unix-std.h" #include "contrib/t1ha/t1ha.h" #include "libserver/worker_util.h" #include "khash.h" #include "utlist.h" #include <math.h> #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L # include <stdalign.h> #endif #define msg_err_cache(...) rspamd_default_log_function (G_LOG_LEVEL_CRITICAL, \ cache->static_pool->tag.tagname, cache->cfg->checksum, \ G_STRFUNC, \ __VA_ARGS__) #define msg_warn_cache(...) rspamd_default_log_function (G_LOG_LEVEL_WARNING, \ cache->static_pool->tag.tagname, cache->cfg->checksum, \ G_STRFUNC, \ __VA_ARGS__) #define msg_info_cache(...) rspamd_default_log_function (G_LOG_LEVEL_INFO, \ cache->static_pool->tag.tagname, cache->cfg->checksum, \ G_STRFUNC, \ __VA_ARGS__) #define msg_debug_cache(...) rspamd_conditional_debug_fast (NULL, NULL, \ rspamd_symcache_log_id, "symcache", cache->cfg->checksum, \ G_STRFUNC, \ __VA_ARGS__) #define msg_debug_cache_task(...) rspamd_conditional_debug_fast (NULL, NULL, \ rspamd_symcache_log_id, "symcache", task->task_pool->tag.uid, \ G_STRFUNC, \ __VA_ARGS__) INIT_LOG_MODULE(symcache) #define CHECK_START_BIT(checkpoint, dyn_item) \ ((dyn_item)->started) #define SET_START_BIT(checkpoint, dyn_item) \ (dyn_item)->started = 1 #define CLR_START_BIT(checkpoint, dyn_item) \ (dyn_item)->started = 0 #define CHECK_FINISH_BIT(checkpoint, dyn_item) \ ((dyn_item)->finished) #define SET_FINISH_BIT(checkpoint, dyn_item) \ (dyn_item)->finished = 1 #define CLR_FINISH_BIT(checkpoint, dyn_item) \ (dyn_item)->finished = 0 static const guchar rspamd_symcache_magic[8] = {'r', 's', 'c', 2, 0, 0, 0, 0 }; struct rspamd_symcache_header { guchar magic[8]; guint nitems; guchar checksum[64]; guchar unused[128]; }; struct symcache_order { GPtrArray *d; guint id; ref_entry_t ref; }; /* * This structure is optimised to store ids list: * - If the first element is -1 then use dynamic part, else use static part */ struct rspamd_symcache_id_list { union { guint32 st[4]; struct { guint32 e; /* First element */ guint16 len; guint16 allocated; guint *n; } dyn; }; }; struct rspamd_symcache_condition { gint cb; struct rspamd_symcache_condition *prev, *next; }; struct rspamd_symcache_item { /* This block is likely shared */ struct rspamd_symcache_item_stat *st; guint64 last_count; struct rspamd_counter_data *cd; gchar *symbol; const gchar *type_descr; gint type; /* Callback data */ union { struct { symbol_func_t func; gpointer user_data; struct rspamd_symcache_condition *conditions; } normal; struct { gint parent; struct rspamd_symcache_item *parent_item; } virtual; } specific; /* Condition of execution */ gboolean enabled; /* Used for async stuff checks */ gboolean is_filter; gboolean is_virtual; /* Priority */ gint priority; /* Topological order */ guint order; gint id; gint frequency_peaks; /* Settings ids */ struct rspamd_symcache_id_list allowed_ids; /* Allows execution but not symbols insertion */ struct rspamd_symcache_id_list exec_only_ids; struct rspamd_symcache_id_list forbidden_ids; /* Dependencies */ GPtrArray *deps; GPtrArray *rdeps; /* Container */ GPtrArray *container; }; struct rspamd_symcache { /* Hash table for fast access */ GHashTable *items_by_symbol; GPtrArray *items_by_id; struct symcache_order *items_by_order; GPtrArray *connfilters; GPtrArray *prefilters; GPtrArray *filters; GPtrArray *postfilters; GPtrArray *composites; GPtrArray *idempotent; GPtrArray *virtual; GList *delayed_deps; GList *delayed_conditions; rspamd_mempool_t *static_pool; guint64 cksum; gdouble total_weight; guint used_items; guint stats_symbols_count; guint64 total_hits; guint id; struct rspamd_config *cfg; gdouble reload_time; gdouble last_profile; gint peak_cb; }; struct rspamd_symcache_dynamic_item { guint16 start_msec; /* Relative to task time */ unsigned started:1; unsigned finished:1; /* unsigned pad:14; */ guint32 async_events; }; struct cache_dependency { struct rspamd_symcache_item *item; /* Real dependency */ gchar *sym; /* Symbolic dep name */ gint id; /* Real from */ gint vid; /* Virtual from */ }; struct delayed_cache_dependency { gchar *from; gchar *to; }; struct delayed_cache_condition { gchar *sym; gint cbref; lua_State *L; }; struct cache_savepoint { guint version; guint items_inflight; gboolean profile; gboolean has_slow; gdouble profile_start; struct rspamd_scan_result *rs; gdouble lim; struct rspamd_symcache_item *cur_item; struct symcache_order *order; struct rspamd_symcache_dynamic_item dynamic_items[]; }; struct rspamd_cache_refresh_cbdata { gdouble last_resort; ev_timer resort_ev; struct rspamd_symcache *cache; struct rspamd_worker *w; struct ev_loop *event_loop; }; /* At least once per minute */ #define PROFILE_MAX_TIME (60.0) /* For messages larger than 2Mb enable profiling */ #define PROFILE_MESSAGE_SIZE_THRESHOLD (1024 * 1024 * 2) /* Enable profile at least once per this amount of messages processed */ #define PROFILE_PROBABILITY (0.01) /* weight, frequency, time */ #define TIME_ALPHA (1.0) #define WEIGHT_ALPHA (0.1) #define FREQ_ALPHA (0.01) #define SCORE_FUN(w, f, t) (((w) > 0 ? (w) : WEIGHT_ALPHA) \ * ((f) > 0 ? (f) : FREQ_ALPHA) \ / (t > TIME_ALPHA ? t : TIME_ALPHA)) static gboolean rspamd_symcache_check_symbol (struct rspamd_task *task, struct rspamd_symcache *cache, struct rspamd_symcache_item *item, struct cache_savepoint *checkpoint); static gboolean rspamd_symcache_check_deps (struct rspamd_task *task, struct rspamd_symcache *cache, struct rspamd_symcache_item *item, struct cache_savepoint *checkpoint, guint recursion, gboolean check_only); static void rspamd_symcache_disable_symbol_checkpoint (struct rspamd_task *task, struct rspamd_symcache *cache, const gchar *symbol); static void rspamd_symcache_enable_symbol_checkpoint (struct rspamd_task *task, struct rspamd_symcache *cache, const gchar *symbol); static void rspamd_symcache_order_dtor (gpointer p) { struct symcache_order *ord = p; g_ptr_array_free (ord->d, TRUE); g_free (ord); } static void rspamd_symcache_order_unref (gpointer p) { struct symcache_order *ord = p; REF_RELEASE (ord); } static gint rspamd_id_cmp (const void * a, const void * b) { return (*(guint32*)a - *(guint32*)b); } static struct symcache_order * rspamd_symcache_order_new (struct rspamd_symcache *cache, gsize nelts) { struct symcache_order *ord; ord = g_malloc0 (sizeof (*ord)); ord->d = g_ptr_array_sized_new (nelts); ord->id = cache->id; REF_INIT_RETAIN (ord, rspamd_symcache_order_dtor); return ord; } static inline struct rspamd_symcache_dynamic_item* rspamd_symcache_get_dynamic (struct cache_savepoint *checkpoint, struct rspamd_symcache_item *item) { return &checkpoint->dynamic_items[item->id]; } static inline struct rspamd_symcache_item * rspamd_symcache_find_filter (struct rspamd_symcache *cache, const gchar *name, bool resolve_parent) { struct rspamd_symcache_item *item; g_assert (cache != NULL); if (name == NULL) { return NULL; } item = g_hash_table_lookup (cache->items_by_symbol, name); if (item != NULL) { if (resolve_parent && item->is_virtual && !(item->type & SYMBOL_TYPE_GHOST)) { item =item->specific.virtual.parent_item; } return item; } return NULL; } const gchar * rspamd_symcache_get_parent (struct rspamd_symcache *cache, const gchar *symbol) { struct rspamd_symcache_item *item, *parent; g_assert (cache != NULL); if (symbol == NULL) { return NULL; } item = g_hash_table_lookup (cache->items_by_symbol, symbol); if (item != NULL) { if (item->is_virtual && !(item->type & SYMBOL_TYPE_GHOST)) { parent = item->specific.virtual.parent_item; if (!parent) { item->specific.virtual.parent_item = g_ptr_array_index (cache->items_by_id, item->specific.virtual.parent); parent = item->specific.virtual.parent_item; } item = parent; } return item->symbol; } return NULL; } static gint postfilters_cmp (const void *p1, const void *p2, gpointer ud) { const struct rspamd_symcache_item *i1 = *(struct rspamd_symcache_item **)p1, *i2 = *(struct rspamd_symcache_item **)p2; double w1, w2; w1 = i1->priority; w2 = i2->priority; if (w1 > w2) { return 1; } else if (w1 < w2) { return -1; } return 0; } static gint prefilters_cmp (const void *p1, const void *p2, gpointer ud) { const struct rspamd_symcache_item *i1 = *(struct rspamd_symcache_item **)p1, *i2 = *(struct rspamd_symcache_item **)p2; double w1, w2; w1 = i1->priority; w2 = i2->priority; if (w1 < w2) { return 1; } else if (w1 > w2) { return -1; } return 0; } #define TSORT_MARK_PERM(it) (it)->order |= (1u << 31) #define TSORT_MARK_TEMP(it) (it)->order |= (1u << 30) #define TSORT_IS_MARKED_PERM(it) ((it)->order & (1u << 31)) #define TSORT_IS_MARKED_TEMP(it) ((it)->order & (1u << 30)) #define TSORT_UNMASK(it) ((it)->order & ~((1u << 31) | (1u << 30))) static gint cache_logic_cmp (const void *p1, const void *p2, gpointer ud) { const struct rspamd_symcache_item *i1 = *(struct rspamd_symcache_item **)p1, *i2 = *(struct rspamd_symcache_item **)p2; struct rspamd_symcache *cache = ud; double w1, w2; double weight1, weight2; double f1 = 0, f2 = 0, t1, t2, avg_freq, avg_weight; guint o1 = TSORT_UNMASK (i1), o2 = TSORT_UNMASK (i2); if (o1 == o2) { /* Heuristic */ if (i1->priority == i2->priority) { avg_freq = ((gdouble) cache->total_hits / cache->used_items); avg_weight = (cache->total_weight / cache->used_items); f1 = (double) i1->st->total_hits / avg_freq; f2 = (double) i2->st->total_hits / avg_freq; weight1 = fabs (i1->st->weight) / avg_weight; weight2 = fabs (i2->st->weight) / avg_weight; t1 = i1->st->avg_time; t2 = i2->st->avg_time; w1 = SCORE_FUN (weight1, f1, t1); w2 = SCORE_FUN (weight2, f2, t2); } else { /* Strict sorting */ w1 = abs (i1->priority); w2 = abs (i2->priority); } } else { w1 = o1; w2 = o2; } if (w2 > w1) { return 1; } else if (w2 < w1) { return -1; } return 0; } static void rspamd_symcache_tsort_visit (struct rspamd_symcache *cache, struct rspamd_symcache_item *it, guint cur_order) { struct cache_dependency *dep; guint i; if (TSORT_IS_MARKED_PERM (it)) { if (cur_order > TSORT_UNMASK (it)) { /* Need to recalculate the whole chain */ it->order = cur_order; /* That also removes all masking */ } else { /* We are fine, stop DFS */ return; } } else if (TSORT_IS_MARKED_TEMP (it)) { msg_err_cache ("cyclic dependencies found when checking '%s'!", it->symbol); return; } TSORT_MARK_TEMP (it); msg_debug_cache ("visiting node: %s (%d)", it->symbol, cur_order); PTR_ARRAY_FOREACH (it->deps, i, dep) { msg_debug_cache ("visiting dep: %s (%d)", dep->item->symbol, cur_order + 1); rspamd_symcache_tsort_visit (cache, dep->item, cur_order + 1); } it->order = cur_order; TSORT_MARK_PERM (it); } static void rspamd_symcache_resort (struct rspamd_symcache *cache) { struct symcache_order *ord; guint i; guint64 total_hits = 0; struct rspamd_symcache_item *it; ord = rspamd_symcache_order_new (cache, cache->filters->len); for (i = 0; i < cache->filters->len; i ++) { it = g_ptr_array_index (cache->filters, i); total_hits += it->st->total_hits; it->order = 0; g_ptr_array_add (ord->d, it); } /* Topological sort, intended to be O(N) but my implementation * is not linear (semi-linear usually) as I want to make it as * simple as possible. * On each stage it does DFS for unseen nodes. In theory, that * can be more complicated than linear - O(N^2) for specially * crafted data. But I don't care. */ PTR_ARRAY_FOREACH (ord->d, i, it) { if (it->order == 0) { rspamd_symcache_tsort_visit (cache, it, 1); } } /* * Now we have all sorted and can do some heuristical sort, keeping * topological order invariant */ g_ptr_array_sort_with_data (ord->d, cache_logic_cmp, cache); cache->total_hits = total_hits; if (cache->items_by_order) { REF_RELEASE (cache->items_by_order); } cache->items_by_order = ord; } static void rspamd_symcache_propagate_dep (struct rspamd_symcache *cache, struct rspamd_symcache_item *it, struct rspamd_symcache_item *dit) { const guint *ids; guint nids = 0; msg_debug_cache ("check id propagation for dependency %s from %s", it->symbol, dit->symbol); ids = rspamd_symcache_get_allowed_settings_ids (cache, dit->symbol, &nids); /* TODO: merge? */ if (nids > 0) { msg_info_cache ("propagate allowed ids from %s to %s", dit->symbol, it->symbol); rspamd_symcache_set_allowed_settings_ids (cache, it->symbol, ids, nids); } ids = rspamd_symcache_get_forbidden_settings_ids (cache, dit->symbol, &nids); if (nids > 0) { msg_info_cache ("propagate forbidden ids from %s to %s", dit->symbol, it->symbol); rspamd_symcache_set_forbidden_settings_ids (cache, it->symbol, ids, nids); } } static void rspamd_symcache_process_dep (struct rspamd_symcache *cache, struct rspamd_symcache_item *it, struct cache_dependency *dep) { struct rspamd_symcache_item *dit = NULL, *vdit = NULL; struct cache_dependency *rdep; if (dep->id >= 0) { msg_debug_cache ("process real dependency %s on %s", it->symbol, dep->sym); dit = rspamd_symcache_find_filter (cache, dep->sym, true); } if (dep->vid >= 0) { /* Case of the virtual symbol that depends on another (maybe virtual) symbol */ vdit = rspamd_symcache_find_filter (cache, dep->sym, false); if (!vdit) { if (dit) { msg_err_cache ("cannot add dependency from %s on %s: no dependency symbol registered", dep->sym, dit->symbol); } } else { msg_debug_cache ("process virtual dependency %s(%d) on %s(%d)", it->symbol, dep->vid, vdit->symbol, vdit->id); } } else { vdit = dit; } if (dit != NULL) { if (!dit->is_filter) { /* * Check sanity: * - filters -> prefilter dependency is OK and always satisfied * - postfilter -> (filter, prefilter) dep is ok * - idempotent -> (any) dep is OK * * Otherwise, emit error * However, even if everything is fine this dep is useless ¯\_(ツ)_/¯ */ gboolean ok_dep = FALSE; if (it->is_filter) { if (dit->is_filter) { ok_dep = TRUE; } else if (dit->type & SYMBOL_TYPE_PREFILTER) { ok_dep = TRUE; } } else if (it->type & SYMBOL_TYPE_POSTFILTER) { if (dit->type & SYMBOL_TYPE_PREFILTER) { ok_dep = TRUE; } } else if (it->type & SYMBOL_TYPE_IDEMPOTENT) { if (dit->type & (SYMBOL_TYPE_PREFILTER|SYMBOL_TYPE_POSTFILTER)) { ok_dep = TRUE; } } else if (it->type & SYMBOL_TYPE_PREFILTER) { if (it->priority < dit->priority) { /* Also OK */ ok_dep = TRUE; } } if (!ok_dep) { msg_err_cache ("cannot add dependency from %s on %s: invalid symbol types", dep->sym, dit->symbol); return; } } else { if (dit->id == it->id) { msg_err_cache ("cannot add dependency on self: %s -> %s " "(resolved to %s)", it->symbol, dep->sym, dit->symbol); } else { rdep = rspamd_mempool_alloc (cache->static_pool, sizeof (*rdep)); rdep->sym = dep->sym; rdep->item = it; rdep->id = it->id; g_assert (dit->rdeps != NULL); g_ptr_array_add (dit->rdeps, rdep); dep->item = dit; dep->id = dit->id; msg_debug_cache ("add dependency from %d on %d", it->id, dit->id); } } } else if (dep->id >= 0) { msg_err_cache ("cannot find dependency on symbol %s for symbol %s", dep->sym, it->symbol); return; } if (vdit) { /* Use virtual symbol to propagate deps */ rspamd_symcache_propagate_dep (cache, it, vdit); } } /* Sort items in logical order */ static void rspamd_symcache_post_init (struct rspamd_symcache *cache) { struct rspamd_symcache_item *it, *vit; struct cache_dependency *dep; struct delayed_cache_dependency *ddep; struct delayed_cache_condition *dcond; GList *cur; gint i, j; cur = cache->delayed_deps; while (cur) { ddep = cur->data; vit = rspamd_symcache_find_filter (cache, ddep->from, false); it = rspamd_symcache_find_filter (cache, ddep->from, true); if (it == NULL || vit == NULL) { msg_err_cache ("cannot register delayed dependency between %s and %s: " "%s is missing", ddep->from, ddep->to, ddep->from); } else { msg_debug_cache ("delayed between %s(%d:%d) -> %s", ddep->from, it->id, vit->id, ddep->to); rspamd_symcache_add_dependency (cache, it->id, ddep->to, vit != it ? vit->id : -1); } cur = g_list_next (cur); } cur = cache->delayed_conditions; while (cur) { dcond = cur->data; it = rspamd_symcache_find_filter (cache, dcond->sym, true); if (it == NULL) { msg_err_cache ( "cannot register delayed condition for %s", dcond->sym); luaL_unref (dcond->L, LUA_REGISTRYINDEX, dcond->cbref); } else { struct rspamd_symcache_condition *ncond = rspamd_mempool_alloc0 (cache->static_pool, sizeof (*ncond)); ncond->cb = dcond->cbref; DL_APPEND (it->specific.normal.conditions, ncond); } cur = g_list_next (cur); } PTR_ARRAY_FOREACH (cache->items_by_id, i, it) { PTR_ARRAY_FOREACH (it->deps, j, dep) { rspamd_symcache_process_dep (cache, it, dep); } if (it->deps) { /* Reversed loop to make removal safe */ for (j = it->deps->len - 1; j >= 0; j--) { dep = g_ptr_array_index (it->deps, j); if (dep->item == NULL) { /* Remove useless dep */ g_ptr_array_remove_index (it->deps, j); } } } } /* Special case for virtual symbols */ PTR_ARRAY_FOREACH (cache->virtual, i, it) { PTR_ARRAY_FOREACH (it->deps, j, dep) { rspamd_symcache_process_dep (cache, it, dep); } } g_ptr_array_sort_with_data (cache->connfilters, prefilters_cmp, cache); g_ptr_array_sort_with_data (cache->prefilters, prefilters_cmp, cache); g_ptr_array_sort_with_data (cache->postfilters, postfilters_cmp, cache); g_ptr_array_sort_with_data (cache->idempotent, postfilters_cmp, cache); rspamd_symcache_resort (cache); } static gboolean rspamd_symcache_load_items (struct rspamd_symcache *cache, const gchar *name) { struct rspamd_symcache_header *hdr; struct stat st; struct ucl_parser *parser; ucl_object_t *top; const ucl_object_t *cur, *elt; ucl_object_iter_t it; struct rspamd_symcache_item *item, *parent; const guchar *p; gint fd; gpointer map; fd = open (name, O_RDONLY); if (fd == -1) { msg_info_cache ("cannot open file %s, error %d, %s", name, errno, strerror (errno)); return FALSE; } rspamd_file_lock (fd, FALSE); if (fstat (fd, &st) == -1) { rspamd_file_unlock (fd, FALSE); close (fd); msg_info_cache ("cannot stat file %s, error %d, %s", name, errno, strerror (errno)); return FALSE; } if (st.st_size < (gint)sizeof (*hdr)) { rspamd_file_unlock (fd, FALSE); close (fd); errno = EINVAL; msg_info_cache ("cannot use file %s, error %d, %s", name, errno, strerror (errno)); return FALSE; } map = mmap (NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0); if (map == MAP_FAILED) { rspamd_file_unlock (fd, FALSE); close (fd); msg_info_cache ("cannot mmap file %s, error %d, %s", name, errno, strerror (errno)); return FALSE; } hdr = map; if (memcmp (hdr->magic, rspamd_symcache_magic, sizeof (rspamd_symcache_magic)) != 0) { msg_info_cache ("cannot use file %s, bad magic", name); munmap (map, st.st_size); rspamd_file_unlock (fd, FALSE); close (fd); return FALSE; } parser = ucl_parser_new (0); p = (const guchar *)(hdr + 1); if (!ucl_parser_add_chunk (parser, p, st.st_size - sizeof (*hdr))) { msg_info_cache ("cannot use file %s, cannot parse: %s", name, ucl_parser_get_error (parser)); munmap (map, st.st_size); ucl_parser_free (parser); rspamd_file_unlock (fd, FALSE); close (fd); return FALSE; } top = ucl_parser_get_object (parser); munmap (map, st.st_size); rspamd_file_unlock (fd, FALSE); close (fd); ucl_parser_free (parser); if (top == NULL || ucl_object_type (top) != UCL_OBJECT) { msg_info_cache ("cannot use file %s, bad object", name); ucl_object_unref (top); return FALSE; } it = ucl_object_iterate_new (top); while ((cur = ucl_object_iterate_safe (it, true))) { item = g_hash_table_lookup (cache->items_by_symbol, ucl_object_key (cur)); if (item) { /* Copy saved info */ /* * XXX: don't save or load weight, it should be obtained from the * metric */ #if 0 elt = ucl_object_lookup (cur, "weight"); if (elt) { w = ucl_object_todouble (elt); if (w != 0) { item->weight = w; } } #endif elt = ucl_object_lookup (cur, "time"); if (elt) { item->st->avg_time = ucl_object_todouble (elt); } elt = ucl_object_lookup (cur, "count"); if (elt) { item->st->total_hits = ucl_object_toint (elt); item->last_count = item->st->total_hits; } elt = ucl_object_lookup (cur, "frequency"); if (elt && ucl_object_type (elt) == UCL_OBJECT) { const ucl_object_t *freq_elt; freq_elt = ucl_object_lookup (elt, "avg"); if (freq_elt) { item->st->avg_frequency = ucl_object_todouble (freq_elt); } freq_elt = ucl_object_lookup (elt, "stddev"); if (freq_elt) { item->st->stddev_frequency = ucl_object_todouble (freq_elt); } } if (item->is_virtual && !(item->type & SYMBOL_TYPE_GHOST)) { g_assert (item->specific.virtual.parent < (gint)cache->items_by_id->len); parent = g_ptr_array_index (cache->items_by_id, item->specific.virtual.parent); item->specific.virtual.parent_item = parent; if (parent->st->weight < item->st->weight) { parent->st->weight = item->st->weight; } /* * We maintain avg_time for virtual symbols equal to the * parent item avg_time */ item->st->avg_time = parent->st->avg_time; } cache->total_weight += fabs (item->st->weight); cache->total_hits += item->st->total_hits; } } ucl_object_iterate_free (it); ucl_object_unref (top); return TRUE; } #define ROUND_DOUBLE(x) (floor((x) * 100.0) / 100.0) static gboolean rspamd_symcache_save_items (struct rspamd_symcache *cache, const gchar *name) { struct rspamd_symcache_header hdr; ucl_object_t *top, *elt, *freq; GHashTableIter it; struct rspamd_symcache_item *item; struct ucl_emitter_functions *efunc; gpointer k, v; gint fd; FILE *fp; bool ret; gchar path[PATH_MAX]; rspamd_snprintf (path, sizeof (path), "%s.new", name); fd = open (path, O_CREAT | O_WRONLY | O_EXCL, 00644); if (fd == -1) { if (errno == EEXIST) { /* Some other process is already writing data, give up silently */ return TRUE; } msg_err_cache ("cannot open file %s, error %d, %s", path, errno, strerror (errno)); return FALSE; } rspamd_file_lock (fd, FALSE); fp = fdopen (fd, "w"); memset (&hdr, 0, sizeof (hdr)); memcpy (hdr.magic, rspamd_symcache_magic, sizeof (rspamd_symcache_magic)); if (fwrite (&hdr, sizeof (hdr), 1, fp) == -1) { msg_err_cache ("cannot write to file %s, error %d, %s", path, errno, strerror (errno)); rspamd_file_unlock (fd, FALSE); fclose (fp); return FALSE; } top = ucl_object_typed_new (UCL_OBJECT); g_hash_table_iter_init (&it, cache->items_by_symbol); while (g_hash_table_iter_next (&it, &k, &v)) { item = v; elt = ucl_object_typed_new (UCL_OBJECT); ucl_object_insert_key (elt, ucl_object_fromdouble (ROUND_DOUBLE (item->st->weight)), "weight", 0, false); ucl_object_insert_key (elt, ucl_object_fromdouble (ROUND_DOUBLE (item->st->time_counter.mean)), "time", 0, false); ucl_object_insert_key (elt, ucl_object_fromint (item->st->total_hits), "count", 0, false); freq = ucl_object_typed_new (UCL_OBJECT); ucl_object_insert_key (freq, ucl_object_fromdouble (ROUND_DOUBLE (item->st->frequency_counter.mean)), "avg", 0, false); ucl_object_insert_key (freq, ucl_object_fromdouble (ROUND_DOUBLE (item->st->frequency_counter.stddev)), "stddev", 0, false); ucl_object_insert_key (elt, freq, "frequency", 0, false); ucl_object_insert_key (top, elt, k, 0, false); } efunc = ucl_object_emit_file_funcs (fp); ret = ucl_object_emit_full (top, UCL_EMIT_JSON_COMPACT, efunc, NULL); ucl_object_emit_funcs_free (efunc); ucl_object_unref (top); rspamd_file_unlock (fd, FALSE); fclose (fp); if (rename (path, name) == -1) { msg_err_cache ("cannot rename %s -> %s, error %d, %s", path, name, errno, strerror (errno)); (void)unlink (path); ret = FALSE; } return ret; } #undef ROUND_DOUBLE gint rspamd_symcache_add_symbol (struct rspamd_symcache *cache, const gchar *name, gint priority, symbol_func_t func, gpointer user_data, enum rspamd_symbol_type type, gint parent) { struct rspamd_symcache_item *item = NULL; const gchar *type_str = "normal"; g_assert (cache != NULL); if (name == NULL && !(type & SYMBOL_TYPE_CALLBACK)) { msg_warn_cache ("no name for non-callback symbol!"); } else if ((type & SYMBOL_TYPE_VIRTUAL & (~SYMBOL_TYPE_GHOST)) && parent == -1) { msg_warn_cache ("no parent symbol is associated with virtual symbol %s", name); } if (name != NULL && !(type & SYMBOL_TYPE_CALLBACK)) { struct rspamd_symcache_item *existing; if (strcspn (name, " \t\n\r") != strlen (name)) { msg_warn_cache ("bogus characters in symbol name: \"%s\"", name); } if ((existing = g_hash_table_lookup (cache->items_by_symbol, name)) != NULL) { if (existing->type & SYMBOL_TYPE_GHOST) { /* * Complicated part: * - we need to remove the existing ghost symbol * - we need to cleanup containers: * - symbols hash * - specific array * - items_by_it * - decrement used_items */ msg_info_cache ("duplicate ghost symbol %s is removed", name); if (existing->container) { g_ptr_array_remove (existing->container, existing); } g_ptr_array_remove (cache->items_by_id, existing->container); cache->used_items --; g_hash_table_remove (cache->items_by_symbol, name); /* * Here can be memory leak, but we assume that ghost symbols * are also virtual */ } else { msg_err_cache ("skip duplicate symbol registration for %s", name); return -1; } } } if (type & (SYMBOL_TYPE_CLASSIFIER|SYMBOL_TYPE_CALLBACK| SYMBOL_TYPE_PREFILTER|SYMBOL_TYPE_POSTFILTER| SYMBOL_TYPE_IDEMPOTENT|SYMBOL_TYPE_GHOST)) { type |= SYMBOL_TYPE_NOSTAT; } item = rspamd_mempool_alloc0 (cache->static_pool, sizeof (struct rspamd_symcache_item)); item->st = rspamd_mempool_alloc0_shared (cache->static_pool, sizeof (*item->st)); item->enabled = TRUE; /* * We do not share cd to skip locking, instead we'll just calculate it on * save or accumulate */ item->cd = rspamd_mempool_alloc0 (cache->static_pool, sizeof (struct rspamd_counter_data)); item->priority = priority; item->type = type; if ((type & SYMBOL_TYPE_FINE) && item->priority == 0) { /* Make priority for negative weighted symbols */ item->priority = 1; } if (func) { /* Non-virtual symbol */ g_assert (parent == -1); if (item->type & SYMBOL_TYPE_PREFILTER) { type_str = "prefilter"; g_ptr_array_add (cache->prefilters, item); item->container = cache->prefilters; } else if (item->type & SYMBOL_TYPE_IDEMPOTENT) { type_str = "idempotent"; g_ptr_array_add (cache->idempotent, item); item->container = cache->idempotent; } else if (item->type & SYMBOL_TYPE_POSTFILTER) { type_str = "postfilter"; g_ptr_array_add (cache->postfilters, item); item->container = cache->postfilters; } else if (item->type & SYMBOL_TYPE_CONNFILTER) { type_str = "connfilter"; g_ptr_array_add (cache->connfilters, item); item->container = cache->connfilters; } else { item->is_filter = TRUE; g_ptr_array_add (cache->filters, item); item->container = cache->filters; } item->id = cache->items_by_id->len; g_ptr_array_add (cache->items_by_id, item); item->specific.normal.func = func; item->specific.normal.user_data = user_data; item->specific.normal.conditions = NULL; } else { /* * Three possibilities here when no function is specified: * - virtual symbol (beware of ghosts!) * - classifier symbol * - composite symbol */ if (item->type & SYMBOL_TYPE_COMPOSITE) { item->specific.normal.conditions = NULL; item->specific.normal.user_data = user_data; g_assert (user_data != NULL); g_ptr_array_add (cache->composites, item); item->id = cache->items_by_id->len; g_ptr_array_add (cache->items_by_id, item); item->container = cache->composites; type_str = "composite"; } else if (item->type & SYMBOL_TYPE_CLASSIFIER) { /* Treat it as normal symbol to allow enable/disable */ item->id = cache->items_by_id->len; g_ptr_array_add (cache->items_by_id, item); item->is_filter = TRUE; item->specific.normal.func = NULL; item->specific.normal.user_data = NULL; item->specific.normal.conditions = NULL; type_str = "classifier"; } else { item->is_virtual = TRUE; item->specific.virtual.parent = parent; item->specific.virtual.parent_item = g_ptr_array_index (cache->items_by_id, parent); item->id = cache->virtual->len; g_ptr_array_add (cache->virtual, item); item->container = cache->virtual; /* Not added to items_by_id, handled by parent */ type_str = "virtual"; } } cache->used_items ++; cache->id ++; if (!(item->type & (SYMBOL_TYPE_IDEMPOTENT|SYMBOL_TYPE_NOSTAT|SYMBOL_TYPE_CLASSIFIER))) { if (name != NULL) { cache->cksum = t1ha (name, strlen (name), cache->cksum); } else { cache->cksum = t1ha (&item->id, sizeof (item->id), cache->cksum); } cache->stats_symbols_count ++; } if (name != NULL) { item->symbol = rspamd_mempool_strdup (cache->static_pool, name); msg_debug_cache ("used items: %d, added symbol: %s, %d; symbol type: %s", cache->used_items, name, item->id, type_str); } else { g_assert (func != NULL); msg_debug_cache ("used items: %d, added unnamed symbol: %d; symbol type: %s", cache->used_items, item->id, type_str); } item->deps = g_ptr_array_new (); item->rdeps = g_ptr_array_new (); item->type_descr = type_str; rspamd_mempool_add_destructor (cache->static_pool, rspamd_ptr_array_free_hard, item->deps); rspamd_mempool_add_destructor (cache->static_pool, rspamd_ptr_array_free_hard, item->rdeps); if (name != NULL) { g_hash_table_insert (cache->items_by_symbol, item->symbol, item); } return item->id; } void rspamd_symcache_set_peak_callback (struct rspamd_symcache *cache, gint cbref) { g_assert (cache != NULL); if (cache->peak_cb != -1) { luaL_unref (cache->cfg->lua_state, LUA_REGISTRYINDEX, cache->peak_cb); } cache->peak_cb = cbref; msg_info_cache ("registered peak callback"); } gboolean rspamd_symcache_add_condition_delayed (struct rspamd_symcache *cache, const gchar *sym, lua_State *L, gint cbref) { struct delayed_cache_condition *ncond; g_assert (cache != NULL); g_assert (sym != NULL); ncond = g_malloc0 (sizeof (*ncond)); ncond->sym = g_strdup (sym); ncond->cbref = cbref; ncond->L = L; cache->id ++; cache->delayed_conditions = g_list_prepend (cache->delayed_conditions, ncond); return TRUE; } void rspamd_symcache_save (struct rspamd_symcache *cache) { if (cache != NULL) { if (cache->cfg->cache_filename) { /* Try to sync values to the disk */ if (!rspamd_symcache_save_items (cache, cache->cfg->cache_filename)) { msg_err_cache ("cannot save cache data to %s: %s", cache->cfg->cache_filename, strerror (errno)); } } } } void rspamd_symcache_destroy (struct rspamd_symcache *cache) { GList *cur; struct delayed_cache_dependency *ddep; struct delayed_cache_condition *dcond; if (cache != NULL) { if (cache->delayed_deps) { cur = cache->delayed_deps; while (cur) { ddep = cur->data; g_free (ddep->from); g_free (ddep->to); g_free (ddep); cur = g_list_next (cur); } g_list_free (cache->delayed_deps); } if (cache->delayed_conditions) { cur = cache->delayed_conditions; while (cur) { dcond = cur->data; g_free (dcond->sym); g_free (dcond); cur = g_list_next (cur); } g_list_free (cache->delayed_conditions); } g_hash_table_destroy (cache->items_by_symbol); g_ptr_array_free (cache->items_by_id, TRUE); rspamd_mempool_delete (cache->static_pool); g_ptr_array_free (cache->connfilters, TRUE); g_ptr_array_free (cache->prefilters, TRUE); g_ptr_array_free (cache->filters, TRUE); g_ptr_array_free (cache->postfilters, TRUE); g_ptr_array_free (cache->idempotent, TRUE); g_ptr_array_free (cache->composites, TRUE); g_ptr_array_free (cache->virtual, TRUE); REF_RELEASE (cache->items_by_order); if (cache->peak_cb != -1) { luaL_unref (cache->cfg->lua_state, LUA_REGISTRYINDEX, cache->peak_cb); } g_free (cache); } } struct rspamd_symcache* rspamd_symcache_new (struct rspamd_config *cfg) { struct rspamd_symcache *cache; cache = g_malloc0 (sizeof (struct rspamd_symcache)); cache->static_pool = rspamd_mempool_new (rspamd_mempool_suggest_size (), "symcache", 0); cache->items_by_symbol = g_hash_table_new (rspamd_str_hash, rspamd_str_equal); cache->items_by_id = g_ptr_array_new (); cache->connfilters = g_ptr_array_new (); cache->prefilters = g_ptr_array_new (); cache->filters = g_ptr_array_new (); cache->postfilters = g_ptr_array_new (); cache->idempotent = g_ptr_array_new (); cache->composites = g_ptr_array_new (); cache->virtual = g_ptr_array_new (); cache->reload_time = cfg->cache_reload_time; cache->total_hits = 1; cache->total_weight = 1.0; cache->cfg = cfg; cache->cksum = 0xdeadbabe; cache->peak_cb = -1; cache->id = (guint)rspamd_random_uint64_fast (); return cache; } static void rspamd_symcache_metric_connect_cb (gpointer k, gpointer v, gpointer ud) { struct rspamd_symcache *cache = (struct rspamd_symcache *)ud; const gchar *sym = k; struct rspamd_symbol *s = (struct rspamd_symbol *)v; gdouble weight; struct rspamd_symcache_item *item; weight = *s->weight_ptr; item = g_hash_table_lookup (cache->items_by_symbol, sym); if (item) { item->st->weight = weight; s->cache_item = item; } } gboolean rspamd_symcache_init (struct rspamd_symcache *cache) { gboolean res = TRUE; g_assert (cache != NULL); cache->reload_time = cache->cfg->cache_reload_time; if (cache->cfg->cache_filename != NULL) { res = rspamd_symcache_load_items (cache, cache->cfg->cache_filename); } rspamd_symcache_post_init (cache); /* Connect metric symbols with symcache symbols */ if (cache->cfg->symbols) { g_hash_table_foreach (cache->cfg->symbols, rspamd_symcache_metric_connect_cb, cache); } return res; } static void rspamd_symcache_validate_cb (gpointer k, gpointer v, gpointer ud) { struct rspamd_symcache_item *item = v, *parent; struct rspamd_config *cfg; struct rspamd_symcache *cache = (struct rspamd_symcache *)ud; struct rspamd_symbol *s; gboolean skipped, ghost; gint p1, p2; ghost = item->st->weight == 0 ? TRUE : FALSE; cfg = cache->cfg; /* Check whether this item is skipped */ skipped = !ghost; g_assert (cfg != NULL); if ((item->type & (SYMBOL_TYPE_NORMAL|SYMBOL_TYPE_VIRTUAL|SYMBOL_TYPE_COMPOSITE|SYMBOL_TYPE_CLASSIFIER)) && g_hash_table_lookup (cfg->symbols, item->symbol) == NULL) { if (!isnan(cfg->unknown_weight)) { skipped = FALSE; item->st->weight = cfg->unknown_weight; s = rspamd_mempool_alloc0 (cache->static_pool, sizeof (*s)); s->name = item->symbol; s->weight_ptr = &item->st->weight; g_hash_table_insert (cfg->symbols, item->symbol, s); msg_info_cache ("adding unknown symbol %s with weight: %.2f", item->symbol, cfg->unknown_weight); ghost = FALSE; } else { skipped = TRUE; } } else { skipped = FALSE; } if (!ghost && skipped) { if (!(item->type & SYMBOL_TYPE_SKIPPED)) { item->type |= SYMBOL_TYPE_SKIPPED; msg_warn_cache ("symbol %s has no score registered, skip its check", item->symbol); } } if (ghost) { msg_debug_cache ("symbol %s is registered as ghost symbol, it won't be inserted " "to any metric", item->symbol); } if (item->st->weight < 0 && item->priority == 0) { item->priority ++; } if (item->is_virtual) { if (!(item->type & SYMBOL_TYPE_GHOST)) { g_assert (item->specific.virtual.parent != -1); g_assert (item->specific.virtual.parent < (gint) cache->items_by_id->len); parent = g_ptr_array_index (cache->items_by_id, item->specific.virtual.parent); item->specific.virtual.parent_item = parent; if (fabs (parent->st->weight) < fabs (item->st->weight)) { parent->st->weight = item->st->weight; } p1 = abs (item->priority); p2 = abs (parent->priority); if (p1 != p2) { parent->priority = MAX (p1, p2); item->priority = parent->priority; } } } cache->total_weight += fabs (item->st->weight); } gboolean rspamd_symcache_validate (struct rspamd_symcache *cache, struct rspamd_config *cfg, gboolean strict) { struct rspamd_symcache_item *item; GHashTableIter it; gpointer k, v; struct rspamd_symbol *sym_def; gboolean ignore_symbol = FALSE, ret = TRUE; if (cache == NULL) { msg_err ("empty cache is invalid"); return FALSE; } g_hash_table_foreach (cache->items_by_symbol, rspamd_symcache_validate_cb, cache); /* Now check each metric item and find corresponding symbol in a cache */ g_hash_table_iter_init (&it, cfg->symbols); while (g_hash_table_iter_next (&it, &k, &v)) { ignore_symbol = FALSE; sym_def = v; if (sym_def && (sym_def->flags & (RSPAMD_SYMBOL_FLAG_IGNORE_METRIC|RSPAMD_SYMBOL_FLAG_DISABLED))) { ignore_symbol = TRUE; } if (!ignore_symbol) { item = g_hash_table_lookup (cache->items_by_symbol, k); if (item == NULL) { msg_warn_cache ( "symbol '%s' has its score defined but there is no " "corresponding rule registered", k); if (strict) { ret = FALSE; } } } else if (sym_def->flags & RSPAMD_SYMBOL_FLAG_DISABLED) { item = g_hash_table_lookup (cache->items_by_symbol, k); if (item) { item->enabled = FALSE; } } } return ret; } /* Return true if metric has score that is more than spam score for it */ static gboolean rspamd_symcache_metric_limit (struct rspamd_task *task, struct cache_savepoint *cp) { struct rspamd_scan_result *res; double ms; if (task->flags & RSPAMD_TASK_FLAG_PASS_ALL) { return FALSE; } if (cp->lim == 0.0) { res = task->result; if (res) { ms = rspamd_task_get_required_score (task, res); if (!isnan (ms) && cp->lim < ms) { cp->rs = res; cp->lim = ms; } } } if (cp->rs) { if (cp->rs->score > cp->lim) { return TRUE; } } else { /* No reject score define, always check all rules */ cp->lim = -1; } return FALSE; } static inline gboolean rspamd_symcache_check_id_list (const struct rspamd_symcache_id_list *ls, guint32 id) { guint i; if (ls->dyn.e == -1) { guint *res = bsearch (&id, ls->dyn.n, ls->dyn.len, sizeof (guint32), rspamd_id_cmp); if (res) { return TRUE; } } else { for (i = 0; i < G_N_ELEMENTS (ls->st); i ++) { if (ls->st[i] == id) { return TRUE; } else if (ls->st[i] == 0) { return FALSE; } } } return FALSE; } gboolean rspamd_symcache_is_item_allowed (struct rspamd_task *task, struct rspamd_symcache_item *item, gboolean exec_only) { const gchar *what = "execution"; if (!exec_only) { what = "symbol insertion"; } /* Static checks */ if (!item->enabled || (RSPAMD_TASK_IS_EMPTY (task) && !(item->type & SYMBOL_TYPE_EMPTY)) || (item->type & SYMBOL_TYPE_MIME_ONLY && !RSPAMD_TASK_IS_MIME(task))) { if (!item->enabled) { msg_debug_cache_task ("skipping %s of %s as it is permanently disabled; symbol type=%s", what, item->symbol, item->type_descr); return FALSE; } else { /* * Exclude virtual symbols */ if (exec_only) { msg_debug_cache_task ("skipping check of %s as it cannot be " "executed for this task type; symbol type=%s", item->symbol, item->type_descr); return FALSE; } } } /* Settings checks */ if (task->settings_elt != 0) { guint32 id = task->settings_elt->id; if (item->forbidden_ids.st[0] != 0 && rspamd_symcache_check_id_list (&item->forbidden_ids, id)) { msg_debug_cache_task ("deny %s of %s as it is forbidden for " "settings id %ud; symbol type=%s", what, item->symbol, id, item->type_descr); return FALSE; } if (!(item->type & SYMBOL_TYPE_EXPLICIT_DISABLE)) { if (item->allowed_ids.st[0] == 0 || !rspamd_symcache_check_id_list (&item->allowed_ids, id)) { if (task->settings_elt->policy == RSPAMD_SETTINGS_POLICY_IMPLICIT_ALLOW) { msg_debug_cache_task ("allow execution of %s settings id %ud " "allows implicit execution of the symbols;" "symbol type=%s", item->symbol, id, item->type_descr); return TRUE; } if (exec_only) { /* * Special case if any of our virtual children are enabled */ if (rspamd_symcache_check_id_list (&item->exec_only_ids, id)) { return TRUE; } } msg_debug_cache_task ("deny %s of %s as it is not listed " "as allowed for settings id %ud; symbol type=%s", what, item->symbol, id, item->type_descr); return FALSE; } } else { msg_debug_cache_task ("allow %s of %s for " "settings id %ud as it can be only disabled explicitly;" " symbol type=%s", what, item->symbol, id, item->type_descr); } } else if (item->type & SYMBOL_TYPE_EXPLICIT_ENABLE) { msg_debug_cache_task ("deny %s of %s as it must be explicitly enabled; symbol type=%s", what, item->symbol, item->type_descr); return FALSE; } /* Allow all symbols with no settings id */ return TRUE; } static gboolean rspamd_symcache_check_symbol (struct rspamd_task *task, struct rspamd_symcache *cache, struct rspamd_symcache_item *item, struct cache_savepoint *checkpoint) { struct rspamd_task **ptask; lua_State *L; gboolean check = TRUE; struct rspamd_symcache_dynamic_item *dyn_item = rspamd_symcache_get_dynamic (checkpoint, item); if (item->type & (SYMBOL_TYPE_CLASSIFIER|SYMBOL_TYPE_COMPOSITE)) { /* Classifiers are special :( */ return TRUE; } if (rspamd_session_blocked (task->s)) { /* * We cannot add new events as session is either destroyed or * being cleaned up. */ return TRUE; } g_assert (!item->is_virtual); g_assert (item->specific.normal.func != NULL); if (CHECK_START_BIT (checkpoint, dyn_item)) { /* * This can actually happen when deps span over different layers */ return CHECK_FINISH_BIT (checkpoint, dyn_item); } /* Check has been started */ SET_START_BIT (checkpoint, dyn_item); if (!rspamd_symcache_is_item_allowed (task, item, TRUE)) { check = FALSE; } else if (item->specific.normal.conditions) { struct rspamd_symcache_condition *cur_cond; DL_FOREACH (item->specific.normal.conditions, cur_cond) { /* We also executes condition callback to check if we need this symbol */ L = task->cfg->lua_state; lua_rawgeti (L, LUA_REGISTRYINDEX, cur_cond->cb); ptask = lua_newuserdata (L, sizeof (struct rspamd_task *)); rspamd_lua_setclass (L, "rspamd{task}", -1); *ptask = task; if (lua_pcall (L, 1, 1, 0) != 0) { msg_info_task ("call to condition for %s failed: %s", item->symbol, lua_tostring (L, -1)); lua_pop (L, 1); } else { check = lua_toboolean (L, -1); lua_pop (L, 1); } if (!check) { break; } } if (!check) { msg_debug_cache_task ("skipping check of %s as its start condition is false; " "symbol type = %s", item->symbol, item->type_descr); } } if (check) { msg_debug_cache_task ("execute %s, %d; symbol type = %s", item->symbol, item->id, item->type_descr); if (checkpoint->profile) { ev_now_update_if_cheap (task->event_loop); dyn_item->start_msec = (ev_now (task->event_loop) - checkpoint->profile_start) * 1e3; } dyn_item->async_events = 0; checkpoint->cur_item = item; checkpoint->items_inflight ++; /* Callback now must finalize itself */ item->specific.normal.func (task, item, item->specific.normal.user_data); checkpoint->cur_item = NULL; if (checkpoint->items_inflight == 0) { return TRUE; } if (dyn_item->async_events == 0 && !CHECK_FINISH_BIT (checkpoint, dyn_item)) { msg_err_cache ("critical error: item %s has no async events pending, " "but it is not finalised", item->symbol); g_assert_not_reached (); } return FALSE; } else { SET_FINISH_BIT (checkpoint, dyn_item); } return TRUE; } static gboolean rspamd_symcache_check_deps (struct rspamd_task *task, struct rspamd_symcache *cache, struct rspamd_symcache_item *item, struct cache_savepoint *checkpoint, guint recursion, gboolean check_only) { struct cache_dependency *dep; guint i; gboolean ret = TRUE; static const guint max_recursion = 20; struct rspamd_symcache_dynamic_item *dyn_item; if (recursion > max_recursion) { msg_err_task ("cyclic dependencies: maximum check level %ud exceed when " "checking dependencies for %s", max_recursion, item->symbol); return TRUE; } if (item->deps != NULL && item->deps->len > 0) { for (i = 0; i < item->deps->len; i ++) { dep = g_ptr_array_index (item->deps, i); if (dep->item == NULL) { /* Assume invalid deps as done */ msg_debug_cache_task ("symbol %d(%s) has invalid dependencies on %d(%s)", item->id, item->symbol, dep->id, dep->sym); continue; } dyn_item = rspamd_symcache_get_dynamic (checkpoint, dep->item); if (!CHECK_FINISH_BIT (checkpoint, dyn_item)) { if (!CHECK_START_BIT (checkpoint, dyn_item)) { /* Not started */ if (!check_only) { if (!rspamd_symcache_check_deps (task, cache, dep->item, checkpoint, recursion + 1, check_only)) { ret = FALSE; msg_debug_cache_task ("delayed dependency %d(%s) for " "symbol %d(%s)", dep->id, dep->sym, item->id, item->symbol); } else if (!rspamd_symcache_check_symbol (task, cache, dep->item, checkpoint)) { /* Now started, but has events pending */ ret = FALSE; msg_debug_cache_task ("started check of %d(%s) symbol " "as dep for " "%d(%s)", dep->id, dep->sym, item->id, item->symbol); } else { msg_debug_cache_task ("dependency %d(%s) for symbol %d(%s) is " "already processed", dep->id, dep->sym, item->id, item->symbol); } } else { msg_debug_cache_task ("dependency %d(%s) for symbol %d(%s) " "cannot be started now", dep->id, dep->sym, item->id, item->symbol); ret = FALSE; } } else { /* Started but not finished */ msg_debug_cache_task ("dependency %d(%s) for symbol %d(%s) is " "still executing", dep->id, dep->sym, item->id, item->symbol); ret = FALSE; } } else { msg_debug_cache_task ("dependency %d(%s) for symbol %d(%s) is already " "checked", dep->id, dep->sym, item->id, item->symbol); } } } return ret; } static struct cache_savepoint * rspamd_symcache_make_checkpoint (struct rspamd_task *task, struct rspamd_symcache *cache) { struct cache_savepoint *checkpoint; if (cache->items_by_order->id != cache->id) { /* * Cache has been modified, need to resort it */ msg_info_cache ("symbols cache has been modified since last check:" " old id: %ud, new id: %ud", cache->items_by_order->id, cache->id); rspamd_symcache_resort (cache); } checkpoint = rspamd_mempool_alloc0 (task->task_pool, sizeof (*checkpoint) + sizeof (struct rspamd_symcache_dynamic_item) * cache->items_by_id->len); g_assert (cache->items_by_order != NULL); checkpoint->version = cache->items_by_order->d->len; checkpoint->order = cache->items_by_order; REF_RETAIN (checkpoint->order); rspamd_mempool_add_destructor (task->task_pool, rspamd_symcache_order_unref, checkpoint->order); /* Calculate profile probability */ ev_now_update_if_cheap (task->event_loop); ev_tstamp now = ev_now (task->event_loop); checkpoint->profile_start = now; if ((cache->last_profile == 0.0 || now > cache->last_profile + PROFILE_MAX_TIME) || (task->msg.len >= PROFILE_MESSAGE_SIZE_THRESHOLD) || (rspamd_random_double_fast () >= (1 - PROFILE_PROBABILITY))) { msg_debug_cache_task ("enable profiling of symbols for task"); checkpoint->profile = TRUE; cache->last_profile = now; } task->checkpoint = checkpoint; return checkpoint; } gboolean rspamd_symcache_process_settings (struct rspamd_task *task, struct rspamd_symcache *cache) { const ucl_object_t *wl, *cur, *disabled, *enabled; struct rspamd_symbols_group *gr; GHashTableIter gr_it; ucl_object_iter_t it = NULL; gboolean already_disabled = FALSE; gpointer k, v; wl = ucl_object_lookup (task->settings, "whitelist"); if (wl != NULL) { msg_info_task ("task is whitelisted"); task->flags |= RSPAMD_TASK_FLAG_SKIP; return TRUE; } enabled = ucl_object_lookup (task->settings, "symbols_enabled"); if (enabled) { /* Disable all symbols but selected */ rspamd_symcache_disable_all_symbols (task, cache, SYMBOL_TYPE_EXPLICIT_DISABLE); already_disabled = TRUE; it = NULL; while ((cur = ucl_iterate_object (enabled, &it, true)) != NULL) { rspamd_symcache_enable_symbol_checkpoint (task, cache, ucl_object_tostring (cur)); } } /* Enable groups of symbols */ enabled = ucl_object_lookup (task->settings, "groups_enabled"); if (enabled) { it = NULL; if (!already_disabled) { rspamd_symcache_disable_all_symbols (task, cache, SYMBOL_TYPE_EXPLICIT_DISABLE); } while ((cur = ucl_iterate_object (enabled, &it, true)) != NULL) { if (ucl_object_type (cur) == UCL_STRING) { gr = g_hash_table_lookup (task->cfg->groups, ucl_object_tostring (cur)); if (gr) { g_hash_table_iter_init (&gr_it, gr->symbols); while (g_hash_table_iter_next (&gr_it, &k, &v)) { rspamd_symcache_enable_symbol_checkpoint (task, cache, k); } } } } } disabled = ucl_object_lookup (task->settings, "symbols_disabled"); if (disabled) { it = NULL; while ((cur = ucl_iterate_object (disabled, &it, true)) != NULL) { rspamd_symcache_disable_symbol_checkpoint (task, cache, ucl_object_tostring (cur)); } } /* Disable groups of symbols */ disabled = ucl_object_lookup (task->settings, "groups_disabled"); if (disabled) { it = NULL; while ((cur = ucl_iterate_object (disabled, &it, true)) != NULL) { if (ucl_object_type (cur) == UCL_STRING) { gr = g_hash_table_lookup (task->cfg->groups, ucl_object_tostring (cur)); if (gr) { g_hash_table_iter_init (&gr_it, gr->symbols); while (g_hash_table_iter_next (&gr_it, &k, &v)) { rspamd_symcache_disable_symbol_checkpoint (task, cache, k); } } } } } return FALSE; } gboolean rspamd_symcache_process_symbols (struct rspamd_task *task, struct rspamd_symcache *cache, gint stage) { struct rspamd_symcache_item *item = NULL; struct rspamd_symcache_dynamic_item *dyn_item; struct cache_savepoint *checkpoint; gint i; gboolean all_done = TRUE; gint saved_priority; guint start_events_pending; g_assert (cache != NULL); if (task->checkpoint == NULL) { checkpoint = rspamd_symcache_make_checkpoint (task, cache); task->checkpoint = checkpoint; } else { checkpoint = task->checkpoint; } msg_debug_cache_task ("symbols processing stage at pass: %d", stage); start_events_pending = rspamd_session_events_pending (task->s); switch (stage) { case RSPAMD_TASK_STAGE_CONNFILTERS: /* Check for connection filters */ saved_priority = G_MININT; all_done = TRUE; for (i = 0; i < (gint) cache->connfilters->len; i++) { item = g_ptr_array_index (cache->connfilters, i); dyn_item = rspamd_symcache_get_dynamic (checkpoint, item); if (RSPAMD_TASK_IS_SKIPPED (task)) { return TRUE; } if (!CHECK_START_BIT (checkpoint, dyn_item) && !CHECK_FINISH_BIT (checkpoint, dyn_item)) { if (checkpoint->has_slow) { /* Delay */ checkpoint->has_slow = FALSE; return FALSE; } /* Check priorities */ if (saved_priority == G_MININT) { saved_priority = item->priority; } else { if (item->priority < saved_priority && rspamd_session_events_pending (task->s) > start_events_pending) { /* * Delay further checks as we have higher * priority filters to be processed */ return FALSE; } } rspamd_symcache_check_symbol (task, cache, item, checkpoint); all_done = FALSE; } } break; case RSPAMD_TASK_STAGE_PRE_FILTERS: /* Check for prefilters */ saved_priority = G_MININT; all_done = TRUE; for (i = 0; i < (gint) cache->prefilters->len; i++) { item = g_ptr_array_index (cache->prefilters, i); dyn_item = rspamd_symcache_get_dynamic (checkpoint, item); if (RSPAMD_TASK_IS_SKIPPED (task)) { return TRUE; } if (!CHECK_START_BIT (checkpoint, dyn_item) && !CHECK_FINISH_BIT (checkpoint, dyn_item)) { /* Check priorities */ if (checkpoint->has_slow) { /* Delay */ checkpoint->has_slow = FALSE; return FALSE; } if (saved_priority == G_MININT) { saved_priority = item->priority; } else { if (item->priority < saved_priority && rspamd_session_events_pending (task->s) > start_events_pending) { /* * Delay further checks as we have higher * priority filters to be processed */ return FALSE; } } rspamd_symcache_check_symbol (task, cache, item, checkpoint); all_done = FALSE; } } break; case RSPAMD_TASK_STAGE_FILTERS: all_done = TRUE; for (i = 0; i < (gint) checkpoint->version; i++) { if (RSPAMD_TASK_IS_SKIPPED (task)) { return TRUE; } item = g_ptr_array_index (checkpoint->order->d, i); dyn_item = rspamd_symcache_get_dynamic (checkpoint, item); if (item->type & SYMBOL_TYPE_CLASSIFIER) { continue; } if (!CHECK_START_BIT (checkpoint, dyn_item)) { all_done = FALSE; if (!rspamd_symcache_check_deps (task, cache, item, checkpoint, 0, FALSE)) { msg_debug_cache_task ("blocked execution of %d(%s) unless deps are " "resolved", item->id, item->symbol); continue; } rspamd_symcache_check_symbol (task, cache, item, checkpoint); if (checkpoint->has_slow) { /* Delay */ checkpoint->has_slow = FALSE; return FALSE; } } if (!(item->type & SYMBOL_TYPE_FINE)) { if (rspamd_symcache_metric_limit (task, checkpoint)) { msg_info_task ("task has already scored more than %.2f, so do " "not " "plan more checks", checkpoint->rs->score); all_done = TRUE; break; } } } break; case RSPAMD_TASK_STAGE_POST_FILTERS: /* Check for postfilters */ saved_priority = G_MININT; all_done = TRUE; for (i = 0; i < (gint) cache->postfilters->len; i++) { if (RSPAMD_TASK_IS_SKIPPED (task)) { return TRUE; } item = g_ptr_array_index (cache->postfilters, i); dyn_item = rspamd_symcache_get_dynamic (checkpoint, item); if (!CHECK_START_BIT (checkpoint, dyn_item) && !CHECK_FINISH_BIT (checkpoint, dyn_item)) { /* Check priorities */ all_done = FALSE; if (checkpoint->has_slow) { /* Delay */ checkpoint->has_slow = FALSE; return FALSE; } if (saved_priority == G_MININT) { saved_priority = item->priority; } else { if (item->priority > saved_priority && rspamd_session_events_pending (task->s) > start_events_pending) { /* * Delay further checks as we have higher * priority filters to be processed */ return FALSE; } } rspamd_symcache_check_symbol (task, cache, item, checkpoint); } } break; case RSPAMD_TASK_STAGE_IDEMPOTENT: /* Check for postfilters */ saved_priority = G_MININT; for (i = 0; i < (gint) cache->idempotent->len; i++) { item = g_ptr_array_index (cache->idempotent, i); dyn_item = rspamd_symcache_get_dynamic (checkpoint, item); if (!CHECK_START_BIT (checkpoint, dyn_item) && !CHECK_FINISH_BIT (checkpoint, dyn_item)) { /* Check priorities */ if (checkpoint->has_slow) { /* Delay */ checkpoint->has_slow = FALSE; return FALSE; } if (saved_priority == G_MININT) { saved_priority = item->priority; } else { if (item->priority > saved_priority && rspamd_session_events_pending (task->s) > start_events_pending) { /* * Delay further checks as we have higher * priority filters to be processed */ return FALSE; } } rspamd_symcache_check_symbol (task, cache, item, checkpoint); } } break; default: g_assert_not_reached (); } return all_done; } struct counters_cbdata { ucl_object_t *top; struct rspamd_symcache *cache; }; /* Leave several digits */ #define P10(X) (1e##X) #define ROUND_DOUBLE_DIGITS(x, dig) (floor((x) * P10(dig)) / P10(dig)) #define ROUND_DOUBLE(x) ROUND_DOUBLE_DIGITS(x, 3) static void rspamd_symcache_counters_cb (gpointer k, gpointer v, gpointer ud) { struct counters_cbdata *cbd = ud; ucl_object_t *obj, *top; struct rspamd_symcache_item *item = v, *parent; const gchar *symbol = k; top = cbd->top; obj = ucl_object_typed_new (UCL_OBJECT); ucl_object_insert_key (obj, ucl_object_fromstring (symbol ? symbol : "unknown"), "symbol", 0, false); if (item->is_virtual) { if (!(item->type & SYMBOL_TYPE_GHOST)) { parent = g_ptr_array_index (cbd->cache->items_by_id, item->specific.virtual.parent); ucl_object_insert_key (obj, ucl_object_fromdouble (ROUND_DOUBLE (item->st->weight)), "weight", 0, false); ucl_object_insert_key (obj, ucl_object_fromdouble (ROUND_DOUBLE (parent->st->avg_frequency)), "frequency", 0, false); ucl_object_insert_key (obj, ucl_object_fromint (parent->st->total_hits), "hits", 0, false); ucl_object_insert_key (obj, ucl_object_fromdouble (ROUND_DOUBLE (parent->st->avg_time)), "time", 0, false); } else { ucl_object_insert_key (obj, ucl_object_fromdouble (ROUND_DOUBLE (item->st->weight)), "weight", 0, false); ucl_object_insert_key (obj, ucl_object_fromdouble (0.0), "frequency", 0, false); ucl_object_insert_key (obj, ucl_object_fromdouble (0.0), "hits", 0, false); ucl_object_insert_key (obj, ucl_object_fromdouble (0.0), "time", 0, false); } } else { ucl_object_insert_key (obj, ucl_object_fromdouble (ROUND_DOUBLE (item->st->weight)), "weight", 0, false); ucl_object_insert_key (obj, ucl_object_fromdouble (ROUND_DOUBLE (item->st->avg_frequency)), "frequency", 0, false); ucl_object_insert_key (obj, ucl_object_fromint (item->st->total_hits), "hits", 0, false); ucl_object_insert_key (obj, ucl_object_fromdouble (ROUND_DOUBLE (item->st->avg_time)), "time", 0, false); } ucl_array_append (top, obj); } #undef ROUND_DOUBLE ucl_object_t * rspamd_symcache_counters (struct rspamd_symcache *cache) { ucl_object_t *top; struct counters_cbdata cbd; g_assert (cache != NULL); top = ucl_object_typed_new (UCL_ARRAY); cbd.top = top; cbd.cache = cache; g_hash_table_foreach (cache->items_by_symbol, rspamd_symcache_counters_cb, &cbd); return top; } static void rspamd_symcache_call_peak_cb (struct ev_loop *ev_base, struct rspamd_symcache *cache, struct rspamd_symcache_item *item, gdouble cur_value, gdouble cur_err) { lua_State *L = cache->cfg->lua_state; struct ev_loop **pbase; lua_rawgeti (L, LUA_REGISTRYINDEX, cache->peak_cb); pbase = lua_newuserdata (L, sizeof (*pbase)); *pbase = ev_base; rspamd_lua_setclass (L, "rspamd{ev_base}", -1); lua_pushstring (L, item->symbol); lua_pushnumber (L, item->st->avg_frequency); lua_pushnumber (L, sqrt (item->st->stddev_frequency)); lua_pushnumber (L, cur_value); lua_pushnumber (L, cur_err); if (lua_pcall (L, 6, 0, 0) != 0) { msg_info_cache ("call to peak function for %s failed: %s", item->symbol, lua_tostring (L, -1)); lua_pop (L, 1); } } static void rspamd_symcache_resort_cb (EV_P_ ev_timer *w, int revents) { gdouble tm; struct rspamd_cache_refresh_cbdata *cbdata = (struct rspamd_cache_refresh_cbdata *)w->data; struct rspamd_symcache *cache; struct rspamd_symcache_item *item; guint i; gdouble cur_ticks; static const double decay_rate = 0.25; cache = cbdata->cache; /* Plan new event */ tm = rspamd_time_jitter (cache->reload_time, 0); cur_ticks = rspamd_get_ticks (FALSE); msg_debug_cache ("resort symbols cache, next reload in %.2f seconds", tm); g_assert (cache != NULL); cbdata->resort_ev.repeat = tm; ev_timer_again (EV_A_ w); if (rspamd_worker_is_primary_controller (cbdata->w)) { /* Gather stats from shared execution times */ for (i = 0; i < cache->filters->len; i ++) { item = g_ptr_array_index (cache->filters, i); item->st->total_hits += item->st->hits; g_atomic_int_set (&item->st->hits, 0); if (item->last_count > 0 && cbdata->w->index == 0) { /* Calculate frequency */ gdouble cur_err, cur_value; cur_value = (item->st->total_hits - item->last_count) / (cur_ticks - cbdata->last_resort); rspamd_set_counter_ema (&item->st->frequency_counter, cur_value, decay_rate); item->st->avg_frequency = item->st->frequency_counter.mean; item->st->stddev_frequency = item->st->frequency_counter.stddev; if (cur_value > 0) { msg_debug_cache ("frequency for %s is %.2f, avg: %.2f", item->symbol, cur_value, item->st->avg_frequency); } cur_err = (item->st->avg_frequency - cur_value); cur_err *= cur_err; /* * TODO: replace magic number */ if (item->st->frequency_counter.number > 10 && cur_err > sqrt (item->st->stddev_frequency) * 3) { item->frequency_peaks ++; msg_debug_cache ("peak found for %s is %.2f, avg: %.2f, " "stddev: %.2f, error: %.2f, peaks: %d", item->symbol, cur_value, item->st->avg_frequency, item->st->stddev_frequency, cur_err, item->frequency_peaks); if (cache->peak_cb != -1) { rspamd_symcache_call_peak_cb (cbdata->event_loop, cache, item, cur_value, cur_err); } } } item->last_count = item->st->total_hits; if (item->cd->number > 0) { if (item->type & (SYMBOL_TYPE_CALLBACK|SYMBOL_TYPE_NORMAL)) { item->st->avg_time = item->cd->mean; rspamd_set_counter_ema (&item->st->time_counter, item->st->avg_time, decay_rate); item->st->avg_time = item->st->time_counter.mean; memset (item->cd, 0, sizeof (*item->cd)); } } } cbdata->last_resort = cur_ticks; /* We don't do actual sorting due to topological guarantees */ } } static void rspamd_symcache_refresh_dtor (void *d) { struct rspamd_cache_refresh_cbdata *cbdata = (struct rspamd_cache_refresh_cbdata *)d; ev_timer_stop (cbdata->event_loop, &cbdata->resort_ev); } void rspamd_symcache_start_refresh (struct rspamd_symcache *cache, struct ev_loop *ev_base, struct rspamd_worker *w) { gdouble tm; struct rspamd_cache_refresh_cbdata *cbdata; cbdata = rspamd_mempool_alloc0 (cache->static_pool, sizeof (*cbdata)); cbdata->last_resort = rspamd_get_ticks (TRUE); cbdata->event_loop = ev_base; cbdata->w = w; cbdata->cache = cache; tm = rspamd_time_jitter (cache->reload_time, 0); msg_debug_cache ("next reload in %.2f seconds", tm); g_assert (cache != NULL); cbdata->resort_ev.data = cbdata; ev_timer_init (&cbdata->resort_ev, rspamd_symcache_resort_cb, tm, tm); ev_timer_start (cbdata->event_loop, &cbdata->resort_ev); rspamd_mempool_add_destructor (cache->static_pool, rspamd_symcache_refresh_dtor, cbdata); } void rspamd_symcache_inc_frequency (struct rspamd_symcache *cache, struct rspamd_symcache_item *item) { if (item != NULL) { g_atomic_int_inc (&item->st->hits); } } void rspamd_symcache_add_dependency (struct rspamd_symcache *cache, gint id_from, const gchar *to, gint virtual_id_from) { struct rspamd_symcache_item *source, *vsource; struct cache_dependency *dep; g_assert (id_from >= 0 && id_from < (gint)cache->items_by_id->len); source = (struct rspamd_symcache_item *)g_ptr_array_index (cache->items_by_id, id_from); dep = rspamd_mempool_alloc (cache->static_pool, sizeof (*dep)); dep->id = id_from; dep->sym = rspamd_mempool_strdup (cache->static_pool, to); /* Will be filled later */ dep->item = NULL; dep->vid = -1; g_ptr_array_add (source->deps, dep); if (virtual_id_from >= 0) { g_assert (virtual_id_from < (gint)cache->virtual->len); /* We need that for settings id propagation */ vsource = (struct rspamd_symcache_item *) g_ptr_array_index (cache->virtual, virtual_id_from); dep = rspamd_mempool_alloc (cache->static_pool, sizeof (*dep)); dep->vid = virtual_id_from; dep->id = -1; dep->sym = rspamd_mempool_strdup (cache->static_pool, to); /* Will be filled later */ dep->item = NULL; g_ptr_array_add (vsource->deps, dep); } } void rspamd_symcache_add_delayed_dependency (struct rspamd_symcache *cache, const gchar *from, const gchar *to) { struct delayed_cache_dependency *ddep; g_assert (from != NULL); g_assert (to != NULL); ddep = g_malloc0 (sizeof (*ddep)); ddep->from = g_strdup (from); ddep->to = g_strdup (to); cache->delayed_deps = g_list_prepend (cache->delayed_deps, ddep); } gint rspamd_symcache_find_symbol (struct rspamd_symcache *cache, const gchar *name) { struct rspamd_symcache_item *item; g_assert (cache != NULL); if (name == NULL) { return -1; } item = g_hash_table_lookup (cache->items_by_symbol, name); if (item != NULL) { return item->id; } return -1; } gboolean rspamd_symcache_stat_symbol (struct rspamd_symcache *cache, const gchar *name, gdouble *frequency, gdouble *freq_stddev, gdouble *tm, guint *nhits) { struct rspamd_symcache_item *item; g_assert (cache != NULL); if (name == NULL) { return FALSE; } item = g_hash_table_lookup (cache->items_by_symbol, name); if (item != NULL) { *frequency = item->st->avg_frequency; *freq_stddev = sqrt (item->st->stddev_frequency); *tm = item->st->time_counter.mean; if (nhits) { *nhits = item->st->hits; } return TRUE; } return FALSE; } const gchar * rspamd_symcache_symbol_by_id (struct rspamd_symcache *cache, gint id) { struct rspamd_symcache_item *item; g_assert (cache != NULL); if (id < 0 || id >= (gint)cache->items_by_id->len) { return NULL; } item = g_ptr_array_index (cache->items_by_id, id); return item->symbol; } guint rspamd_symcache_stats_symbols_count (struct rspamd_symcache *cache) { g_assert (cache != NULL); return cache->stats_symbols_count; } void rspamd_symcache_disable_all_symbols (struct rspamd_task *task, struct rspamd_symcache *cache, guint skip_mask) { struct cache_savepoint *checkpoint; guint i; struct rspamd_symcache_item *item; struct rspamd_symcache_dynamic_item *dyn_item; if (task->checkpoint == NULL) { checkpoint = rspamd_symcache_make_checkpoint (task, cache); task->checkpoint = checkpoint; } else { checkpoint = task->checkpoint; } /* Enable for squeezed symbols */ PTR_ARRAY_FOREACH (cache->items_by_id, i, item) { dyn_item = rspamd_symcache_get_dynamic (checkpoint, item); if (!(item->type & (skip_mask))) { SET_FINISH_BIT (checkpoint, dyn_item); SET_START_BIT (checkpoint, dyn_item); } } } static void rspamd_symcache_disable_symbol_checkpoint (struct rspamd_task *task, struct rspamd_symcache *cache, const gchar *symbol) { struct cache_savepoint *checkpoint; struct rspamd_symcache_item *item; struct rspamd_symcache_dynamic_item *dyn_item; if (task->checkpoint == NULL) { checkpoint = rspamd_symcache_make_checkpoint (task, cache); task->checkpoint = checkpoint; } else { checkpoint = task->checkpoint; } item = rspamd_symcache_find_filter (cache, symbol, true); if (item) { dyn_item = rspamd_symcache_get_dynamic (checkpoint, item); SET_FINISH_BIT (checkpoint, dyn_item); SET_START_BIT (checkpoint, dyn_item); msg_debug_cache_task ("disable execution of %s", symbol); } else { msg_info_task ("cannot disable %s: not found", symbol); } } static void rspamd_symcache_enable_symbol_checkpoint (struct rspamd_task *task, struct rspamd_symcache *cache, const gchar *symbol) { struct cache_savepoint *checkpoint; struct rspamd_symcache_item *item; struct rspamd_symcache_dynamic_item *dyn_item; if (task->checkpoint == NULL) { checkpoint = rspamd_symcache_make_checkpoint (task, cache); task->checkpoint = checkpoint; } else { checkpoint = task->checkpoint; } item = rspamd_symcache_find_filter (cache, symbol, true); if (item) { dyn_item = rspamd_symcache_get_dynamic (checkpoint, item); dyn_item->finished = 0; dyn_item->started = 0; msg_debug_cache_task ("enable execution of %s", symbol); } else { msg_info_task ("cannot enable %s: not found", symbol); } } struct rspamd_abstract_callback_data* rspamd_symcache_get_cbdata (struct rspamd_symcache *cache, const gchar *symbol) { struct rspamd_symcache_item *item; g_assert (cache != NULL); g_assert (symbol != NULL); item = rspamd_symcache_find_filter (cache, symbol, true); if (item) { return item->specific.normal.user_data; } return NULL; } gboolean rspamd_symcache_is_checked (struct rspamd_task *task, struct rspamd_symcache *cache, const gchar *symbol) { struct cache_savepoint *checkpoint; struct rspamd_symcache_item *item; struct rspamd_symcache_dynamic_item *dyn_item; g_assert (cache != NULL); g_assert (symbol != NULL); if (task->checkpoint == NULL) { checkpoint = rspamd_symcache_make_checkpoint (task, cache); task->checkpoint = checkpoint; } else { checkpoint = task->checkpoint; } item = rspamd_symcache_find_filter (cache, symbol, true); if (item) { dyn_item = rspamd_symcache_get_dynamic (checkpoint, item); return dyn_item->started; } return FALSE; } void rspamd_symcache_disable_symbol_perm (struct rspamd_symcache *cache, const gchar *symbol, gboolean resolve_parent) { struct rspamd_symcache_item *item; g_assert (cache != NULL); g_assert (symbol != NULL); item = rspamd_symcache_find_filter (cache, symbol, resolve_parent); if (item) { item->enabled = FALSE; } } void rspamd_symcache_enable_symbol_perm (struct rspamd_symcache *cache, const gchar *symbol) { struct rspamd_symcache_item *item; g_assert (cache != NULL); g_assert (symbol != NULL); item = rspamd_symcache_find_filter (cache, symbol, true); if (item) { item->enabled = TRUE; } } guint64 rspamd_symcache_get_cksum (struct rspamd_symcache *cache) { g_assert (cache != NULL); return cache->cksum; } gboolean rspamd_symcache_is_symbol_enabled (struct rspamd_task *task, struct rspamd_symcache *cache, const gchar *symbol) { struct cache_savepoint *checkpoint; struct rspamd_symcache_item *item; struct rspamd_symcache_dynamic_item *dyn_item; lua_State *L; struct rspamd_task **ptask; gboolean ret = TRUE; g_assert (cache != NULL); g_assert (symbol != NULL); checkpoint = task->checkpoint; if (checkpoint) { item = rspamd_symcache_find_filter (cache, symbol, true); if (item) { if (!rspamd_symcache_is_item_allowed (task, item, TRUE)) { ret = FALSE; } else { dyn_item = rspamd_symcache_get_dynamic (checkpoint, item); if (CHECK_START_BIT (checkpoint, dyn_item)) { ret = FALSE; } else { if (item->specific.normal.conditions) { struct rspamd_symcache_condition *cur_cond; DL_FOREACH (item->specific.normal.conditions, cur_cond) { /* * We also executes condition callback to check * if we need this symbol */ L = task->cfg->lua_state; lua_rawgeti (L, LUA_REGISTRYINDEX, cur_cond->cb); ptask = lua_newuserdata (L, sizeof (struct rspamd_task *)); rspamd_lua_setclass (L, "rspamd{task}", -1); *ptask = task; if (lua_pcall (L, 1, 1, 0) != 0) { msg_info_task ("call to condition for %s failed: %s", item->symbol, lua_tostring (L, -1)); lua_pop (L, 1); } else { ret = lua_toboolean (L, -1); lua_pop (L, 1); } if (!ret) { break; } } } } } } } return ret; } gboolean rspamd_symcache_enable_symbol (struct rspamd_task *task, struct rspamd_symcache *cache, const gchar *symbol) { struct cache_savepoint *checkpoint; struct rspamd_symcache_item *item; struct rspamd_symcache_dynamic_item *dyn_item; gboolean ret = FALSE; g_assert (cache != NULL); g_assert (symbol != NULL); checkpoint = task->checkpoint; if (checkpoint) { item = rspamd_symcache_find_filter (cache, symbol, true); if (item) { dyn_item = rspamd_symcache_get_dynamic (checkpoint, item); if (!CHECK_FINISH_BIT (checkpoint, dyn_item)) { ret = TRUE; CLR_START_BIT (checkpoint, dyn_item); CLR_FINISH_BIT (checkpoint, dyn_item); } else { msg_debug_task ("cannot enable symbol %s: already started", symbol); } } } return ret; } gboolean rspamd_symcache_disable_symbol (struct rspamd_task *task, struct rspamd_symcache *cache, const gchar *symbol) { struct cache_savepoint *checkpoint; struct rspamd_symcache_item *item; struct rspamd_symcache_dynamic_item *dyn_item; gboolean ret = FALSE; g_assert (cache != NULL); g_assert (symbol != NULL); checkpoint = task->checkpoint; if (checkpoint) { item = rspamd_symcache_find_filter (cache, symbol, true); if (item) { dyn_item = rspamd_symcache_get_dynamic (checkpoint, item); if (!CHECK_START_BIT (checkpoint, dyn_item)) { ret = TRUE; SET_START_BIT (checkpoint, dyn_item); SET_FINISH_BIT (checkpoint, dyn_item); } else { if (!CHECK_FINISH_BIT (checkpoint, dyn_item)) { msg_warn_task ("cannot disable symbol %s: already started", symbol); } } } } return ret; } void rspamd_symcache_foreach (struct rspamd_symcache *cache, void (*func) (struct rspamd_symcache_item *, gpointer), gpointer ud) { struct rspamd_symcache_item *item; GHashTableIter it; gpointer k, v; g_hash_table_iter_init (&it, cache->items_by_symbol); while (g_hash_table_iter_next (&it, &k, &v)) { item = (struct rspamd_symcache_item *)v; func (item, ud); } } struct rspamd_symcache_item * rspamd_symcache_get_cur_item (struct rspamd_task *task) { struct cache_savepoint *checkpoint = task->checkpoint; if (checkpoint == NULL) { return NULL; } return checkpoint->cur_item; } /** * Replaces the current item being processed. * Returns the current item being processed (if any) * @param task * @param item * @return */ struct rspamd_symcache_item * rspamd_symcache_set_cur_item (struct rspamd_task *task, struct rspamd_symcache_item *item) { struct cache_savepoint *checkpoint = task->checkpoint; struct rspamd_symcache_item *ex; ex = checkpoint->cur_item; checkpoint->cur_item = item; return ex; } struct rspamd_symcache_delayed_cbdata { struct rspamd_symcache_item *item; struct rspamd_task *task; struct rspamd_async_event *event; struct ev_timer tm; }; static void rspamd_symcache_delayed_item_fin (gpointer ud) { struct rspamd_symcache_delayed_cbdata *cbd = (struct rspamd_symcache_delayed_cbdata *)ud; struct rspamd_task *task; struct cache_savepoint *checkpoint; task = cbd->task; checkpoint = task->checkpoint; checkpoint->has_slow = FALSE; ev_timer_stop (task->event_loop, &cbd->tm); } static void rspamd_symcache_delayed_item_cb (EV_P_ ev_timer *w, int what) { struct rspamd_symcache_delayed_cbdata *cbd = (struct rspamd_symcache_delayed_cbdata *)w->data; struct rspamd_symcache_item *item; struct rspamd_task *task; struct cache_dependency *rdep; struct cache_savepoint *checkpoint; struct rspamd_symcache_dynamic_item *dyn_item; guint i; item = cbd->item; task = cbd->task; checkpoint = task->checkpoint; cbd->event = NULL; /* Timer will be stopped here */ rspamd_session_remove_event (task->s, rspamd_symcache_delayed_item_fin, cbd); /* Process all reverse dependencies */ PTR_ARRAY_FOREACH (item->rdeps, i, rdep) { if (rdep->item) { dyn_item = rspamd_symcache_get_dynamic (checkpoint, rdep->item); if (!CHECK_START_BIT (checkpoint, dyn_item)) { msg_debug_cache_task ("check item %d(%s) rdep of %s ", rdep->item->id, rdep->item->symbol, item->symbol); if (!rspamd_symcache_check_deps (task, task->cfg->cache, rdep->item, checkpoint, 0, FALSE)) { msg_debug_cache_task ("blocked execution of %d(%s) rdep of %s " "unless deps are resolved", rdep->item->id, rdep->item->symbol, item->symbol); } else { rspamd_symcache_check_symbol (task, task->cfg->cache, rdep->item, checkpoint); } } } } } static void rspamd_delayed_timer_dtor (gpointer d) { struct rspamd_symcache_delayed_cbdata *cbd = (struct rspamd_symcache_delayed_cbdata *)d; if (cbd->event) { /* Event has not been executed */ rspamd_session_remove_event (cbd->task->s, rspamd_symcache_delayed_item_fin, cbd); cbd->event = NULL; } } /** * Finalize the current async element potentially calling its deps */ void rspamd_symcache_finalize_item (struct rspamd_task *task, struct rspamd_symcache_item *item) { struct cache_savepoint *checkpoint = task->checkpoint; struct cache_dependency *rdep; struct rspamd_symcache_dynamic_item *dyn_item; gdouble diff; guint i; gboolean enable_slow_timer = FALSE; const gdouble slow_diff_limit = 300; /* Sanity checks */ g_assert (checkpoint->items_inflight > 0); dyn_item = rspamd_symcache_get_dynamic (checkpoint, item); if (dyn_item->async_events > 0) { /* * XXX: Race condition * * It is possible that some async event is still in flight, but we * already know its result, however, it is the responsibility of that * event to decrease async events count and call this function * one more time */ msg_debug_cache_task ("postpone finalisation of %s(%d) as there are %d " "async events pending", item->symbol, item->id, dyn_item->async_events); return; } msg_debug_cache_task ("process finalize for item %s(%d)", item->symbol, item->id); SET_FINISH_BIT (checkpoint, dyn_item); checkpoint->items_inflight --; checkpoint->cur_item = NULL; if (checkpoint->profile) { ev_now_update_if_cheap (task->event_loop); diff = ((ev_now (task->event_loop) - checkpoint->profile_start) * 1e3 - dyn_item->start_msec); if (diff > slow_diff_limit) { if (!checkpoint->has_slow) { checkpoint->has_slow = TRUE; enable_slow_timer = TRUE; msg_info_task ("slow rule: %s(%d): %.2f ms; enable slow timer delay", item->symbol, item->id, diff); } else { msg_info_task ("slow rule: %s(%d): %.2f ms", item->symbol, item->id, diff); } } if (G_UNLIKELY (RSPAMD_TASK_IS_PROFILING (task))) { rspamd_task_profile_set (task, item->symbol, diff); } if (rspamd_worker_is_scanner (task->worker)) { rspamd_set_counter (item->cd, diff); } } if (enable_slow_timer) { struct rspamd_symcache_delayed_cbdata *cbd = rspamd_mempool_alloc (task->task_pool,sizeof (*cbd)); /* Add timer to allow something else to be executed */ ev_timer *tm = &cbd->tm; cbd->event = rspamd_session_add_event (task->s, rspamd_symcache_delayed_item_fin, cbd, "symcache"); /* * If no event could be added, then we are already in the destruction * phase. So the main issue is to deal with has slow here */ if (cbd->event) { ev_timer_init (tm, rspamd_symcache_delayed_item_cb, 0.1, 0.0); ev_set_priority (tm, EV_MINPRI); rspamd_mempool_add_destructor (task->task_pool, rspamd_delayed_timer_dtor, cbd); cbd->task = task; cbd->item = item; tm->data = cbd; ev_timer_start (task->event_loop, tm); } else { /* Just reset as no timer is added */ checkpoint->has_slow = FALSE; } return; } /* Process all reverse dependencies */ PTR_ARRAY_FOREACH (item->rdeps, i, rdep) { if (rdep->item) { dyn_item = rspamd_symcache_get_dynamic (checkpoint, rdep->item); if (!CHECK_START_BIT (checkpoint, dyn_item)) { msg_debug_cache_task ("check item %d(%s) rdep of %s ", rdep->item->id, rdep->item->symbol, item->symbol); if (!rspamd_symcache_check_deps (task, task->cfg->cache, rdep->item, checkpoint, 0, FALSE)) { msg_debug_cache_task ("blocked execution of %d(%s) rdep of %s " "unless deps are resolved", rdep->item->id, rdep->item->symbol, item->symbol); } else { rspamd_symcache_check_symbol (task, task->cfg->cache, rdep->item, checkpoint); } } } } } guint rspamd_symcache_item_async_inc_full (struct rspamd_task *task, struct rspamd_symcache_item *item, const gchar *subsystem, const gchar *loc) { struct rspamd_symcache_dynamic_item *dyn_item; struct cache_savepoint *checkpoint = task->checkpoint; dyn_item = rspamd_symcache_get_dynamic (checkpoint, item); msg_debug_cache_task ("increase async events counter for %s(%d) = %d + 1; " "subsystem %s (%s)", item->symbol, item->id, dyn_item->async_events, subsystem, loc); return ++dyn_item->async_events; } guint rspamd_symcache_item_async_dec_full (struct rspamd_task *task, struct rspamd_symcache_item *item, const gchar *subsystem, const gchar *loc) { struct rspamd_symcache_dynamic_item *dyn_item; struct cache_savepoint *checkpoint = task->checkpoint; dyn_item = rspamd_symcache_get_dynamic (checkpoint, item); msg_debug_cache_task ("decrease async events counter for %s(%d) = %d - 1; " "subsystem %s (%s)", item->symbol, item->id, dyn_item->async_events, subsystem, loc); g_assert (dyn_item->async_events > 0); return --dyn_item->async_events; } gboolean rspamd_symcache_item_async_dec_check_full (struct rspamd_task *task, struct rspamd_symcache_item *item, const gchar *subsystem, const gchar *loc) { if (rspamd_symcache_item_async_dec_full (task, item, subsystem, loc) == 0) { rspamd_symcache_finalize_item (task, item); return TRUE; } return FALSE; } gboolean rspamd_symcache_add_symbol_flags (struct rspamd_symcache *cache, const gchar *symbol, guint flags) { struct rspamd_symcache_item *item; g_assert (cache != NULL); g_assert (symbol != NULL); item = rspamd_symcache_find_filter (cache, symbol, true); if (item) { item->type |= flags; return TRUE; } return FALSE; } gboolean rspamd_symcache_set_symbol_flags (struct rspamd_symcache *cache, const gchar *symbol, guint flags) { struct rspamd_symcache_item *item; g_assert (cache != NULL); g_assert (symbol != NULL); item = rspamd_symcache_find_filter (cache, symbol, true); if (item) { item->type = flags; return TRUE; } return FALSE; } void rspamd_symcache_get_symbol_details(struct rspamd_symcache *cache, const gchar *symbol, ucl_object_t *this_sym_ucl) { struct rspamd_symcache_item *item; g_assert (cache != NULL); g_assert (symbol != NULL); item = rspamd_symcache_find_filter (cache, symbol, false); if (item) { ucl_object_insert_key (this_sym_ucl, ucl_object_fromstring(item->type_descr), "type", strlen("type"), false); // any other data? } } guint rspamd_symcache_get_symbol_flags (struct rspamd_symcache *cache, const gchar *symbol) { struct rspamd_symcache_item *item; g_assert (cache != NULL); g_assert (symbol != NULL); item = rspamd_symcache_find_filter (cache, symbol, true); if (item) { return item->type; } return 0; } void rspamd_symcache_composites_foreach (struct rspamd_task *task, struct rspamd_symcache *cache, GHFunc func, gpointer fd) { guint i; struct rspamd_symcache_item *item; struct rspamd_symcache_dynamic_item *dyn_item; if (task->checkpoint == NULL) { return; } PTR_ARRAY_FOREACH (cache->composites, i, item) { dyn_item = rspamd_symcache_get_dynamic (task->checkpoint, item); if (!CHECK_START_BIT (task->checkpoint, dyn_item)) { /* Cannot do it due to 2 passes */ /* SET_START_BIT (task->checkpoint, dyn_item); */ func (item->symbol, item->specific.normal.user_data, fd); SET_FINISH_BIT (task->checkpoint, dyn_item); } } } bool rspamd_symcache_set_allowed_settings_ids (struct rspamd_symcache *cache, const gchar *symbol, const guint32 *ids, guint nids) { struct rspamd_symcache_item *item; item = rspamd_symcache_find_filter (cache, symbol, false); if (item == NULL) { return false; } if (nids <= G_N_ELEMENTS (item->allowed_ids.st)) { /* Use static version */ memset (&item->allowed_ids, 0, sizeof (item->allowed_ids)); for (guint i = 0; i < nids; i++) { item->allowed_ids.st[i] = ids[i]; } } else { /* Need to use a separate list */ item->allowed_ids.dyn.e = -1; /* Flag */ item->allowed_ids.dyn.n = rspamd_mempool_alloc (cache->static_pool, sizeof (guint32) * nids); item->allowed_ids.dyn.len = nids; item->allowed_ids.dyn.allocated = nids; for (guint i = 0; i < nids; i++) { item->allowed_ids.dyn.n[i] = ids[i]; } /* Keep sorted */ qsort (item->allowed_ids.dyn.n, nids, sizeof (guint32), rspamd_id_cmp); } return true; } bool rspamd_symcache_set_forbidden_settings_ids (struct rspamd_symcache *cache, const gchar *symbol, const guint32 *ids, guint nids) { struct rspamd_symcache_item *item; item = rspamd_symcache_find_filter (cache, symbol, false); if (item == NULL) { return false; } g_assert (nids < G_MAXUINT16); if (nids <= G_N_ELEMENTS (item->forbidden_ids.st)) { /* Use static version */ memset (&item->forbidden_ids, 0, sizeof (item->forbidden_ids)); for (guint i = 0; i < nids; i++) { item->forbidden_ids.st[i] = ids[i]; } } else { /* Need to use a separate list */ item->forbidden_ids.dyn.e = -1; /* Flag */ item->forbidden_ids.dyn.n = rspamd_mempool_alloc (cache->static_pool, sizeof (guint32) * nids); item->forbidden_ids.dyn.len = nids; item->forbidden_ids.dyn.allocated = nids; for (guint i = 0; i < nids; i++) { item->forbidden_ids.dyn.n[i] = ids[i]; } /* Keep sorted */ qsort (item->forbidden_ids.dyn.n, nids, sizeof (guint32), rspamd_id_cmp); } return true; } const guint32* rspamd_symcache_get_allowed_settings_ids (struct rspamd_symcache *cache, const gchar *symbol, guint *nids) { struct rspamd_symcache_item *item; guint cnt = 0; item = rspamd_symcache_find_filter (cache, symbol, false); if (item == NULL) { return NULL; } if (item->allowed_ids.dyn.e == -1) { /* Dynamic list */ *nids = item->allowed_ids.dyn.len; return item->allowed_ids.dyn.n; } else { while (item->allowed_ids.st[cnt] != 0 && cnt < G_N_ELEMENTS (item->allowed_ids.st)) { cnt ++; } *nids = cnt; return item->allowed_ids.st; } } const guint32* rspamd_symcache_get_forbidden_settings_ids (struct rspamd_symcache *cache, const gchar *symbol, guint *nids) { struct rspamd_symcache_item *item; guint cnt = 0; item = rspamd_symcache_find_filter (cache, symbol, false); if (item == NULL) { return NULL; } if (item->forbidden_ids.dyn.e == -1) { /* Dynamic list */ *nids = item->allowed_ids.dyn.len; return item->allowed_ids.dyn.n; } else { while (item->forbidden_ids.st[cnt] != 0 && cnt < G_N_ELEMENTS (item->allowed_ids.st)) { cnt ++; } *nids = cnt; return item->forbidden_ids.st; } } /* Insertion sort: usable for near-sorted ids list */ static inline void rspamd_ids_insertion_sort (guint *a, guint n) { for (guint i = 1; i < n; i++) { guint32 tmp = a[i]; guint j = i; while (j > 0 && tmp < a[j - 1]) { a[j] = a[j - 1]; j --; } a[j] = tmp; } } static inline void rspamd_symcache_add_id_to_list (rspamd_mempool_t *pool, struct rspamd_symcache_id_list *ls, guint32 id) { guint cnt = 0; guint *new_array; if (ls->st[0] == -1) { /* Dynamic array */ if (ls->dyn.len < ls->dyn.allocated) { /* Trivial, append + sort */ ls->dyn.n[ls->dyn.len++] = id; } else { /* Reallocate */ g_assert (ls->dyn.allocated <= G_MAXINT16); ls->dyn.allocated *= 2; new_array = rspamd_mempool_alloc (pool, ls->dyn.allocated * sizeof (guint32)); memcpy (new_array, ls->dyn.n, ls->dyn.len * sizeof (guint32)); ls->dyn.n = new_array; ls->dyn.n[ls->dyn.len++] = id; } rspamd_ids_insertion_sort (ls->dyn.n, ls->dyn.len); } else { /* Static part */ while (ls->st[cnt] != 0 && cnt < G_N_ELEMENTS (ls->st)) { cnt ++; } if (cnt < G_N_ELEMENTS (ls->st)) { ls->st[cnt] = id; } else { /* Switch to dynamic */ new_array = rspamd_mempool_alloc (pool, G_N_ELEMENTS (ls->st) * 2 * sizeof (guint32)); memcpy (new_array, ls->st, G_N_ELEMENTS (ls->st) * sizeof (guint32)); ls->dyn.n = new_array; ls->dyn.e = -1; ls->dyn.allocated = G_N_ELEMENTS (ls->st) * 2; ls->dyn.len = G_N_ELEMENTS (ls->st); /* Recursively jump to dynamic branch that will handle insertion + sorting */ rspamd_symcache_add_id_to_list (pool, ls, id); } } } void rspamd_symcache_process_settings_elt (struct rspamd_symcache *cache, struct rspamd_config_settings_elt *elt) { guint32 id = elt->id; ucl_object_iter_t iter; struct rspamd_symcache_item *item, *parent; const ucl_object_t *cur; if (elt->symbols_disabled) { /* Process denied symbols */ iter = NULL; while ((cur = ucl_object_iterate (elt->symbols_disabled, &iter, true)) != NULL) { const gchar *sym = ucl_object_key (cur); item = rspamd_symcache_find_filter (cache, sym, false); if (item) { if (item->is_virtual) { /* * Virtual symbols are special: * we ignore them in symcache but prevent them from being * inserted. */ rspamd_symcache_add_id_to_list (cache->static_pool, &item->forbidden_ids, id); msg_debug_cache ("deny virtual symbol %s for settings %ud (%s); " "parent can still be executed", sym, id, elt->name); } else { /* Normal symbol, disable it */ rspamd_symcache_add_id_to_list (cache->static_pool, &item->forbidden_ids, id); msg_debug_cache ("deny symbol %s for settings %ud (%s)", sym, id, elt->name); } } else { msg_warn_cache ("cannot find a symbol to disable %s " "when processing settings %ud (%s)", sym, id, elt->name); } } } if (elt->symbols_enabled) { iter = NULL; while ((cur = ucl_object_iterate (elt->symbols_enabled, &iter, true)) != NULL) { /* Here, we resolve parent and explicitly allow it */ const gchar *sym = ucl_object_key (cur); item = rspamd_symcache_find_filter (cache, sym, false); if (item) { if (item->is_virtual) { if (!(item->type & SYMBOL_TYPE_GHOST)) { parent = rspamd_symcache_find_filter (cache, sym, true); if (parent) { if (elt->symbols_disabled && ucl_object_lookup (elt->symbols_disabled, parent->symbol)) { msg_err_cache ("conflict in %s: cannot enable disabled symbol %s, " "wanted to enable symbol %s", elt->name, parent->symbol, sym); continue; } rspamd_symcache_add_id_to_list (cache->static_pool, &parent->exec_only_ids, id); msg_debug_cache ("allow just execution of symbol %s for settings %ud (%s)", parent->symbol, id, elt->name); } } /* Ignore ghosts */ } rspamd_symcache_add_id_to_list (cache->static_pool, &item->allowed_ids, id); msg_debug_cache ("allow execution of symbol %s for settings %ud (%s)", sym, id, elt->name); } else { msg_warn_cache ("cannot find a symbol to enable %s " "when processing settings %ud (%s)", sym, id, elt->name); } } } } gint rspamd_symcache_item_flags (struct rspamd_symcache_item *item) { if (item) { return item->type; } return 0; } const gchar* rspamd_symcache_item_name (struct rspamd_symcache_item *item) { return item ? item->symbol : NULL; } const struct rspamd_symcache_item_stat * rspamd_symcache_item_stat (struct rspamd_symcache_item *item) { return item ? item->st : NULL; } gboolean rspamd_symcache_item_is_enabled (struct rspamd_symcache_item *item) { if (item) { if (!item->enabled) { return FALSE; } if (item->is_virtual && item->specific.virtual.parent_item != NULL) { return rspamd_symcache_item_is_enabled (item->specific.virtual.parent_item); } return TRUE; } return FALSE; } struct rspamd_symcache_item * rspamd_symcache_item_get_parent ( struct rspamd_symcache_item *item) { if (item && item->is_virtual && item->specific.virtual.parent_item != NULL) { return item->specific.virtual.parent_item; } return NULL; } const GPtrArray* rspamd_symcache_item_get_deps (struct rspamd_symcache_item *item) { struct rspamd_symcache_item *parent; if (item) { parent = rspamd_symcache_item_get_parent (item); if (parent) { item = parent; } return item->deps; } return NULL; } const GPtrArray* rspamd_symcache_item_get_rdeps (struct rspamd_symcache_item *item) { struct rspamd_symcache_item *parent; if (item) { parent = rspamd_symcache_item_get_parent (item); if (parent) { item = parent; } return item->rdeps; } return NULL; } void rspamd_symcache_enable_profile (struct rspamd_task *task) { struct cache_savepoint *checkpoint = task->checkpoint; if (checkpoint && !checkpoint->profile) { ev_now_update_if_cheap (task->event_loop); ev_tstamp now = ev_now (task->event_loop); checkpoint->profile_start = now; msg_debug_cache_task ("enable profiling of symbols for task"); checkpoint->profile = TRUE; } }
24.834629
91
0.673517
[ "object" ]
d2a240e74228a330bc78a0c9b3d2b7f4c050a875
61,212
c
C
src/modules/fastHandler.c
luukp/appweb
3f2ca5a2366fc93c1de7086461bb1f3ac5d54ac7
[ "Apache-2.0", "BSD-2-Clause" ]
207
2015-02-05T02:25:37.000Z
2022-03-31T00:28:54.000Z
src/modules/fastHandler.c
luukp/appweb
3f2ca5a2366fc93c1de7086461bb1f3ac5d54ac7
[ "Apache-2.0", "BSD-2-Clause" ]
239
2015-01-13T09:40:40.000Z
2022-02-16T04:02:38.000Z
src/modules/fastHandler.c
luukp/appweb
3f2ca5a2366fc93c1de7086461bb1f3ac5d54ac7
[ "Apache-2.0", "BSD-2-Clause" ]
94
2015-01-01T00:15:31.000Z
2022-03-04T01:02:34.000Z
/* fastHandler.c -- FastCGI handler This handler supports the FastCGI spec: https://github.com/fast-cgi/spec/blob/master/spec.md It supports launching FastCGI applications and connecting to pre-existing FastCGI applications. It will multiplex multiple simultaneous requests to one or more FastCGI apps. <Route /fast> LoadModule fastHandler libmod_fast Action application/x-php /usr/local/bin/php-cgi AddHandler fastHandler php FastConnect 127.0.0.1:9991 launch min=1 max=2 count=500 timeout=5mins multiplex=1 </Route> Copyright (c) All Rights Reserved. See copyright notice at the bottom of the file. */ /*********************************** Includes *********************************/ #include "appweb.h" #if ME_COM_FAST && ME_UNIX_LIKE /************************************ Locals ***********************************/ #define FAST_VERSION 1 #define FAST_DEBUG 0 // For debugging (keeps filedes open in FastCGI for debug output) /* FastCGI spec packet types */ #define FAST_REAP 0 // Proxy has been reaped (not part of spec) #define FAST_BEGIN_REQUEST 1 // Start new request - sent to FastCGI #define FAST_ABORT_REQUEST 2 // Abort request - sent to FastCGI #define FAST_END_REQUEST 3 // End request - received from FastCGI #define FAST_PARAMS 4 // Send params to FastCGI #define FAST_STDIN 5 // Post body data #define FAST_STDOUT 6 // Response body #define FAST_STDERR 7 // FastCGI app errors #define FAST_DATA 8 // Additional data to application (unused) #define FAST_GET_VALUES 9 // Query FastCGI app (unused) #define FAST_GET_VALUES_RESULT 10 // Query result #define FAST_UNKNOWN_TYPE 11 // Unknown management request #define FAST_MAX 11 // Max type /* Pseudo types */ #define FAST_COMMS_ERROR 12 // Communications error static cchar *fastTypes[FAST_MAX + 1] = { "invalid", "begin", "abort", "end", "params", "stdin", "stdout", "stderr", "data", "get-values", "get-values-result", "unknown", }; /* FastCGI app types */ #define FAST_RESPONDER 1 // Supported web request responder #define FAST_AUTHORIZER 2 // Not supported #define FAST_FILTER 3 // Not supported #define FAST_MAGIC 0x2671825C /* Default constants. WARNING: this code does not yet support multiple requests per app */ #define FAST_MAX_APPS 1 // Max of one app #define FAST_MIN_APPS 0 // Min of zero apps to keep running if idle #define FAST_MAX_REQUESTS MAXINT64 // Max number of requests per app instance #define FAST_MAX_MULTIPLEX 1 // Max number of concurrent requests per app instance #define FAST_MAX_ID 0x10000 // Maximum request ID #define FAST_PACKET_SIZE 8 // Size of minimal FastCGI packet #define FAST_KEEP_CONN 1 // Flag to app to keep connection open #define FAST_Q_SIZE ((FAST_PACKET_SIZE + 65535 + 8) * 2) #define FAST_REQUEST_COMPLETE 0 // End Request response status for request complete #define FAST_CANT_MPX_CONN 1 // Request rejected -- FastCGI app cannot multiplex requests #define FAST_OVERLOADED 2 // Request rejected -- app server is overloaded #define FAST_UNKNOWN_ROLE 3 // Request rejected -- unknown role #ifndef FAST_WAIT_TIMEOUT #define FAST_WAIT_TIMEOUT (10 * TPS) // Time to wait for a app #endif #ifndef FAST_CONNECT_TIMEOUT #define FAST_CONNECT_TIMEOUT (10 * TPS) // Time to wait for FastCGI to respond to a connect #endif #ifndef FAST_APP_TIMEOUT #define FAST_APP_TIMEOUT (300 * TPS) // Default inactivity time to preserve idle app #endif #ifndef FAST_WATCHDOG_TIMEOUT #define FAST_WATCHDOG_TIMEOUT (60 * TPS) // Frequency to check on idle apps and then prune them #endif /* Top level FastCGI structure per route */ typedef struct Fast { uint magic; // Magic identifier cchar *endpoint; // Proxy listening endpoint cchar *launch; // Launch command int multiplex; // Maximum number of requests to send to each FastCGI app int minApps; // Minumum number of apps to maintain int maxApps; // Maximum number of apps to spawn uint64 keep; // Keep alive uint64 maxRequests; // Maximum number of requests for launched apps before respawning MprTicks appTimeout; // Timeout for an idle app to be maintained MprList *apps; // List of active apps MprList *idleApps; // Idle apps MprMutex *mutex; // Multithread sync MprCond *cond; // Condition to wait for available app MprEvent *timer; // Timer to check for idle apps cchar *ip; // Listening IP address int port; // Listening port } Fast; /* Per FastCGI app instance */ typedef struct FastApp { Fast *fast; // Parent pointer HttpTrace *trace; // Default tracing configuration MprTicks lastActive; // When last active MprSignal *signal; // Mpr signal handler for child death bool destroy; // Must destroy app bool destroyed; // App has been destroyed int inUse; // In use counter int pid; // Process ID of the FastCGI app uint64 nextID; // Next request ID for this app MprList *sockets; // Open sockets to apps MprList *requests; // Requests cchar *ip; // Bound IP address int port; // Bound listening port MprTicks lastActivity; // Last I/O activity } FastApp; /* Per FastCGI request instance. This is separate from the FastApp properties because the FastRequest executes on a different dispatcher. */ typedef struct FastRequest { Fast *fast; // Parent pointer FastApp *app; // Owning app MprSocket *socket; // I/O socket HttpStream *stream; // Owning client request stream HttpQueue *connWriteq; // Queue to write to the FastCGI app HttpQueue *connReadq; // Queue to hold read data from the FastCGI app HttpTrace *trace; // Default tracing configuration int id; // FastCGI request ID - assigned from FastApp.nextID % FAST_MAX_ID bool eof; // Socket is closed bool parsedHeaders; // Parsed the FastCGI app header response bool writeBlocked; // Socket is full of write data int eventMask; // Socket eventMask uint64 bytesRead; // Bytes read in response } FastRequest; /*********************************** Forwards *********************************/ static void addFastPacket(HttpNet *net, HttpPacket *packet); static void addToFastVector(HttpNet *net, char *ptr, ssize bytes); static void adjustFastVec(HttpNet *net, ssize written); static Fast *allocFast(void); static FastRequest *allocFastRequest(FastApp *app, HttpStream *stream, MprSocket *socket); static FastApp *allocFastApp(Fast *fast, HttpStream *stream); static void closeAppSockets(FastApp *app); static cchar *buildFastArgs(FastApp *app, HttpStream *stream, int *argcp, cchar ***argvp); static MprOff buildFastVec(HttpQueue *q); static void fastCloseRequest(HttpQueue *q); static void fastMaintenance(Fast *fast); static MprSocket *getFastSocket(FastApp *app); static void copyFastInner(HttpPacket *packet, cchar *key, cchar *value, cchar *prefix); static void copyFastParams(HttpPacket *packet, MprJson *params, cchar *prefix); static void copyFastVars(HttpPacket *packet, MprHash *vars, cchar *prefix); static HttpPacket *createFastPacket(HttpQueue *q, int type, HttpPacket *packet); static MprSocket *createListener(FastApp *app, HttpStream *stream); static void enableFastConnector(FastRequest *req); static int fastConnectDirective(MaState *state, cchar *key, cchar *value); static void fastConnectorIO(FastRequest *req, MprEvent *event); static void fastConnectorIncoming(HttpQueue *q, HttpPacket *packet); static void fastConnectorIncomingService(HttpQueue *q); static void fastConnectorOutgoingService(HttpQueue *q); static void fastHandlerReapResponse(FastRequest *req); static void fastHandlerResponse(FastRequest *req, int type, HttpPacket *packet); static void fastIncomingRequestPacket(HttpQueue *q, HttpPacket *packet); static void freeFastPackets(HttpQueue *q, ssize bytes); static Fast *getFast(HttpRoute *route); static char *getFastToken(MprBuf *buf, cchar *delim); static FastApp *getFastApp(Fast *fast, HttpStream *stream); static int getListenPort(MprSocket *socket); static void fastOutgoingService(HttpQueue *q); static void idleSocketIO(MprSocket *sp, MprEvent *event); static void killFastApp(FastApp *app); static void manageFast(Fast *fast, int flags); static void manageFastApp(FastApp *app, int flags); static void manageFastRequest(FastRequest *fastConnector, int flags); static int fastOpenRequest(HttpQueue *q); static bool parseFastHeaders(HttpPacket *packet); static bool parseFastResponseLine(HttpPacket *packet); static int prepFastEnv(HttpStream *stream, cchar **envv, MprHash *vars); static void prepFastRequestStart(HttpQueue *q); static void prepFastRequestParams(HttpQueue *q); static void reapSignalHandler(FastApp *app, MprSignal *sp); static FastApp *startFastApp(Fast *fast, HttpStream *stream); #if ME_DEBUG static void fastInfo(void *ignored, MprSignal *sp); #endif /************************************* Code ***********************************/ /* Loadable module initialization */ PUBLIC int httpFastInit(Http *http, MprModule *module) { HttpStage *handler, *connector; /* Add configuration file directives */ maAddDirective("FastConnect", fastConnectDirective); /* Create FastCGI handler to respond to client requests */ if ((handler = httpCreateHandler("fastHandler", module)) == 0) { return MPR_ERR_CANT_CREATE; } http->fastHandler = handler; handler->close = fastCloseRequest; handler->open = fastOpenRequest; handler->incoming = fastIncomingRequestPacket; handler->outgoingService = fastOutgoingService; /* Create FastCGI connector. The connector manages communication to the FastCGI application. The Fast handler is the head of the pipeline while the Fast connector is after the Http protocol and tailFilter. */ if ((connector = httpCreateConnector("fastConnector", NULL)) == 0) { return MPR_ERR_CANT_CREATE; } http->fastConnector = connector; connector->incoming = fastConnectorIncoming; connector->incomingService = fastConnectorIncomingService; connector->outgoingService = fastConnectorOutgoingService; #if ME_DEBUG mprAddRoot(mprAddSignalHandler(ME_SIGINFO, fastInfo, 0, 0, MPR_SIGNAL_AFTER)); #endif return 0; } /* Open the fastHandler for a new client request */ static int fastOpenRequest(HttpQueue *q) { Http *http; HttpNet *net; HttpStream *stream; MprSocket *socket; Fast *fast; FastApp *app; FastRequest *req; net = q->net; stream = q->stream; http = stream->http; httpTrimExtraPath(stream); httpMapFile(stream); httpCreateCGIParams(stream); /* Get a Fast instance for this route. First time, this will allocate a new Fast instance. Second and subsequent times, will reuse the existing instance. */ fast = getFast(stream->rx->route); /* Get a FastApp instance. This will reuse an existing FastCGI app if possible. Otherwise, it will launch a new FastCGI app if within limits. Otherwise it will wait until one becomes available. */ if ((app = getFastApp(fast, stream)) == 0) { httpError(stream, HTTP_CODE_NOT_FOUND, "Cannot allocate FastCGI app for route %s", stream->rx->route->pattern); return MPR_ERR_CANT_OPEN; } /* Open a dedicated client socket to the FastCGI app */ if ((socket = getFastSocket(app)) == NULL) { httpError(stream, HTTP_CODE_INTERNAL_SERVER_ERROR, "Cannot allocate socket to fast app: %d", errno); return MPR_ERR_CANT_CONNECT; } req = allocFastRequest(app, stream, socket); mprAddItem(app->requests, req); q->queueData = q->pair->queueData = req; /* Send a start request followed by the request parameters */ prepFastRequestStart(q); prepFastRequestParams(q); httpServiceQueue(req->connWriteq); enableFastConnector(req); return 0; } /* Release an app and req when the request completes. This closes the connection to the FastCGI app. It will destroy the FastCGI app on errors. */ static void fastCloseRequest(HttpQueue *q) { Fast *fast; FastRequest *req; FastApp *app; cchar *msg; req = q->queueData; fast = req->fast; app = req->app; lock(fast); if (req->socket) { if (!fast->keep) { mprCloseSocket(req->socket, 1); } else if (!(req->socket->flags & (MPR_SOCKET_EOF | MPR_SOCKET_DISCONNECTED))) { mprRemoveSocketHandler(req->socket); mprPushItem(app->sockets, req->socket); if (fast->keep) { mprAddSocketHandler(req->socket, MPR_READABLE, NULL, idleSocketIO, req->socket, 0); } } } mprRemoveItem(app->requests, req); if (--app->inUse <= 0) { if (mprRemoveItem(fast->apps, app) < 0) { httpLog(app->trace, "fast", "error", 0, "msg:Cannot find app in list"); } msg = "Release FastCGI app"; if (app->pid) { if (fast->maxRequests < MAXINT64 && app->nextID >= fast->maxRequests) { app->destroy = 1; } if (app->destroy) { msg = "Kill FastCGI app"; killFastApp(app); } } if (app->destroy) { closeAppSockets(app); } else { mprAddItem(fast->idleApps, app); app->lastActive = mprGetTicks(); } httpLog(app->trace, "fast", "context", 0, "msg:%s, pid:%d, idle:%d, active:%d, id:%d, destroy:%d, nextId:%lld", msg, app->pid, mprGetListLength(fast->idleApps), mprGetListLength(fast->apps), req->id, app->destroy, app->nextID); mprSignalCond(fast->cond); } unlock(fast); } static Fast *allocFast(void) { Fast *fast; fast = mprAllocObj(Fast, manageFast); fast->magic = FAST_MAGIC; fast->apps = mprCreateList(0, 0); fast->idleApps = mprCreateList(0, 0); fast->mutex = mprCreateLock(); fast->cond = mprCreateCond(); fast->multiplex = FAST_MAX_MULTIPLEX; fast->maxRequests = FAST_MAX_REQUESTS; fast->minApps = FAST_MIN_APPS; fast->maxApps = FAST_MAX_APPS; fast->ip = sclone("127.0.0.1"); fast->port = 0; fast->keep = 1; fast->appTimeout = FAST_APP_TIMEOUT; fast->timer = mprCreateTimerEvent(NULL, "fast-watchdog", FAST_WATCHDOG_TIMEOUT, fastMaintenance, fast, MPR_EVENT_QUICK); return fast; } static void manageFast(Fast *fast, int flags) { if (flags & MPR_MANAGE_MARK) { mprMark(fast->cond); mprMark(fast->endpoint); mprMark(fast->idleApps); mprMark(fast->ip); mprMark(fast->launch); mprMark(fast->mutex); mprMark(fast->apps); mprMark(fast->timer); } } static void fastMaintenance(Fast *fast) { FastApp *app; MprTicks now; int count, next; lock(fast); now = mprGetTicks(); count = mprGetListLength(fast->apps) + mprGetListLength(fast->idleApps); /* Prune idle apps. Rely on the HTTP service timer to prune inactive requests, then the app will be returned to idleApps. */ for (ITERATE_ITEMS(fast->idleApps, app, next)) { if (app->pid && app->destroy) { killFastApp(app); } else if (app->pid && ((now - app->lastActive) > fast->appTimeout)) { if (count-- > fast->minApps) { killFastApp(app); } } } unlock(fast); } /* Get the fast structure for a route and save in "eroute". Allocate if required. One Fast instance is shared by all using the route. */ static Fast *getFast(HttpRoute *route) { Fast *fast; if ((fast = route->eroute) == 0) { mprGlobalLock(); if ((fast = route->eroute) == 0) { fast = route->eroute = allocFast(); } mprGlobalUnlock(); } return fast; } /* POST/PUT incoming body data from the client destined for the CGI gateway. : For POST "form" requests, this will be called before the command is actually started. */ static void fastIncomingRequestPacket(HttpQueue *q, HttpPacket *packet) { HttpStream *stream; FastRequest *req; assert(q); assert(packet); stream = q->stream; if ((req = q->queueData) == 0) { return; } if (packet->flags & HTTP_PACKET_END) { /* End of input */ httpFinalizeInput(stream); if (stream->rx->remainingContent > 0) { httpError(stream, HTTP_CODE_BAD_REQUEST, "Client supplied insufficient body data"); packet = createFastPacket(q, FAST_ABORT_REQUEST, httpCreateDataPacket(0)); } } createFastPacket(q, FAST_STDIN, packet); httpPutForService(req->connWriteq, packet, HTTP_SCHEDULE_QUEUE); } static void fastOutgoingService(HttpQueue *q) { HttpPacket *packet; HttpStream *stream; FastRequest *req; req = q->queueData; stream = q->stream; for (packet = httpGetPacket(q); packet; packet = httpGetPacket(q)) { if (!httpWillNextQueueAcceptPacket(q, packet)) { httpPutBackPacket(q, packet); return; } httpPutPacketToNext(q, packet); } if (!(req->eventMask & MPR_READABLE)) { enableFastConnector(req); } } static void fastHandlerReapResponse(FastRequest *req) { fastHandlerResponse(req, FAST_REAP, NULL); } /* Handle response messages from the FastCGI app */ static void fastHandlerResponse(FastRequest *req, int type, HttpPacket *packet) { FastApp *app; HttpStream *stream; HttpRx *rx; MprBuf *buf; int status, protoStatus; stream = req->stream; app = req->app; if (stream->state <= HTTP_STATE_BEGIN || stream->rx->route == NULL) { /* Request already complete and stream has been recycled (prepared for next request) */ return; } if (type == FAST_COMMS_ERROR) { httpError(stream, HTTP_ABORT | HTTP_CODE_COMMS_ERROR, "FastRequest: comms error"); } else if (type == FAST_REAP) { httpError(stream, HTTP_ABORT | HTTP_CODE_COMMS_ERROR, "FastRequest: process killed error"); } else if (type == FAST_END_REQUEST && packet) { if (httpGetPacketLength(packet) < 8) { httpError(stream, HTTP_CODE_BAD_GATEWAY, "FastCGI bad request end packet"); return; } buf = packet->content; rx = stream->rx; status = mprGetCharFromBuf(buf) << 24 | mprGetCharFromBuf(buf) << 16 | mprGetCharFromBuf(buf) << 8 | mprGetCharFromBuf(buf); protoStatus = mprGetCharFromBuf(buf); mprAdjustBufStart(buf, 3); if (protoStatus == FAST_REQUEST_COMPLETE) { httpLog(stream->trace, "rx.fast", "context", "msg:Request complete, id:%d, status:%d", req->id, status); } else if (protoStatus == FAST_CANT_MPX_CONN) { httpError(stream, HTTP_CODE_BAD_GATEWAY, "FastCGI cannot multiplex requests %s", rx->uri); return; } else if (protoStatus == FAST_OVERLOADED) { httpError(stream, HTTP_CODE_SERVICE_UNAVAILABLE, "FastCGI overloaded %s", rx->uri); return; } else if (protoStatus == FAST_UNKNOWN_ROLE) { httpError(stream, HTTP_CODE_BAD_GATEWAY, "FastCGI unknown role %s", rx->uri); return; } httpLog(stream->trace, "rx.fast.eof", "detail", "msg:FastCGI end request, id:%d", req->id); httpFinalizeOutput(stream); } else if (type == FAST_STDOUT && packet) { if (!req->parsedHeaders) { if (!parseFastHeaders(packet)) { return; } req->parsedHeaders = 1; } if (httpGetPacketLength(packet) > 0) { // httpPutPacketToNext(stream->writeq, packet); httpPutForService(stream->writeq, packet, HTTP_SCHEDULE_QUEUE); httpServiceQueue(stream->writeq); } } } /* Parse the FastCGI app output headers. Sample FastCGI program output: Content-type: text/html <html..... */ static bool parseFastHeaders(HttpPacket *packet) { FastRequest *req; HttpStream *stream; MprBuf *buf; char *endHeaders, *headers, *key, *value; ssize blen, len; stream = packet->stream; req = packet->data; buf = packet->content; headers = mprGetBufStart(buf); value = 0; headers = mprGetBufStart(buf); blen = mprGetBufLength(buf); len = 0; if ((endHeaders = sncontains(headers, "\r\n\r\n", blen)) == NULL) { if ((endHeaders = sncontains(headers, "\n\n", blen)) == NULL) { if (slen(headers) < ME_MAX_HEADERS) { // Not EOF and less than max headers and have not yet seen an end of headers delimiter httpLog(stream->trace, "rx.fast", "detail", "msg:FastCGI incomplete headers, id:%d", req->id); return 0; } } len = 2; } else { len = 4; } /* Split the headers from the body. Add null to ensure we can search for line terminators. */ if (endHeaders) { endHeaders[len - 1] = '\0'; endHeaders += len; } /* Want to be tolerant of FastCGI programs that omit the status line. */ if (strncmp((char*) buf->start, "HTTP/1.", 7) == 0) { if (!parseFastResponseLine(packet)) { /* httpError already called */ return 0; } } if (endHeaders && strchr(mprGetBufStart(buf), ':')) { while (mprGetBufLength(buf) > 0 && buf->start[0] && (buf->start[0] != '\r' && buf->start[0] != '\n')) { if ((key = getFastToken(buf, ":")) == 0) { key = "Bad Header"; } value = getFastToken(buf, "\n"); while (isspace((uchar) *value)) { value++; } len = (int) strlen(value); while (len > 0 && (value[len - 1] == '\r' || value[len - 1] == '\n')) { value[len - 1] = '\0'; len--; } httpLog(stream->trace, "rx.fast", "detail", "key:%s, value: %s", key, value); if (scaselesscmp(key, "location") == 0) { httpRedirect(stream, HTTP_CODE_MOVED_TEMPORARILY, value); } else if (scaselesscmp(key, "status") == 0) { httpSetStatus(stream, atoi(value)); } else if (scaselesscmp(key, "content-type") == 0) { if (stream->tx->charSet && !scaselesscontains(value, "charset")) { httpSetHeader(stream, "Content-Type", "%s; charset=%s", value, stream->tx->charSet); } else { httpSetHeaderString(stream, "Content-Type", value); } } else if (scaselesscmp(key, "content-length") == 0) { httpSetContentLength(stream, (MprOff) stoi(value)); httpSetChunkSize(stream, 0); } else { /* Now pass all other headers back to the client */ key = ssplit(key, ":\r\n\t ", NULL); httpSetHeaderString(stream, key, value); } } buf->start = endHeaders; } return 1; } /* Parse the FCGI output first line */ static bool parseFastResponseLine(HttpPacket *packet) { MprBuf *buf; char *protocol, *status, *msg; buf = packet->content; protocol = getFastToken(buf, " "); if (protocol == 0 || protocol[0] == '\0') { httpError(packet->stream, HTTP_CODE_BAD_GATEWAY, "Bad FCGI HTTP protocol response"); return 0; } if (strncmp(protocol, "HTTP/1.", 7) != 0) { httpError(packet->stream, HTTP_CODE_BAD_GATEWAY, "Unsupported FCGI protocol"); return 0; } status = getFastToken(buf, " "); if (status == 0 || *status == '\0') { httpError(packet->stream, HTTP_CODE_BAD_GATEWAY, "Bad FCGI header response"); return 0; } msg = getFastToken(buf, "\n"); mprDebug("http cgi", 4, "FCGI response status: %s %s %s", protocol, status, msg); return 1; } /* Get the next input token. The content buffer is advanced to the next token. This routine always returns a non-zero token. The empty string means the delimiter was not found. */ static char *getFastToken(MprBuf *buf, cchar *delim) { char *token, *nextToken; ssize len; len = mprGetBufLength(buf); if (len == 0) { return ""; } token = mprGetBufStart(buf); nextToken = sncontains(mprGetBufStart(buf), delim, len); if (nextToken) { *nextToken = '\0'; len = (int) strlen(delim); nextToken += len; buf->start = nextToken; } else { buf->start = mprGetBufEnd(buf); } return token; } /************************************************ FastApp ***************************************************************/ /* The FastApp represents the connection to a single FastCGI app instance */ static FastApp *allocFastApp(Fast *fast, HttpStream *stream) { FastApp *app; app = mprAllocObj(FastApp, manageFastApp); app->fast = fast; app->trace = stream->net->trace; app->requests = mprCreateList(0, 0); app->sockets = mprCreateList(0, 0); app->port = fast->port; app->ip = fast->ip; /* The requestID must start at 1 by spec */ app->nextID = 1; return app; } static void closeAppSockets(FastApp *app) { MprSocket *socket; int next; for (ITERATE_ITEMS(app->sockets, socket, next)) { mprCloseSocket(socket, 1); } } static void manageFastApp(FastApp *app, int flags) { if (flags & MPR_MANAGE_MARK) { mprMark(app->fast); mprMark(app->signal); mprMark(app->sockets); mprMark(app->requests); mprMark(app->trace); mprMark(app->ip); } } static FastApp *getFastApp(Fast *fast, HttpStream *stream) { FastApp *app; MprTicks timeout; int next; lock(fast); app = NULL; timeout = mprGetTicks() + FAST_WAIT_TIMEOUT; /* Locate a FastApp to serve the request. Use an idle app first. If none available, start a new app if under the limits. Otherwise, wait for one to become available. */ while (!app && mprGetTicks() < timeout) { for (ITERATE_ITEMS(fast->idleApps, app, next)) { if (app->destroy || app->destroyed) { continue; } mprRemoveItemAtPos(fast->idleApps, next - 1); mprAddItem(fast->apps, app); break; } if (!app) { if (mprGetListLength(fast->apps) < fast->maxApps) { if ((app = startFastApp(fast, stream)) != 0) { mprAddItem(fast->apps, app); } break; } else { for (ITERATE_ITEMS(fast->apps, app, next)) { if (mprGetListLength(app->requests) < fast->multiplex) { break; } } if (app) { break; } unlock(fast); mprYield(MPR_YIELD_STICKY); mprWaitForCond(fast->cond, TPS); mprResetYield(); lock(fast); mprLog("fast", 0, "Waiting for fastCGI app to become available, running %d", mprGetListLength(fast->apps)); #if ME_DEBUG fastInfo(NULL, NULL); #endif } } } if (app) { app->lastActive = mprGetTicks(); app->inUse++; } else { mprLog("fast", 0, "Cannot acquire available fastCGI app, running %d", mprGetListLength(fast->apps)); } unlock(fast); return app; } /* Start a new FastCGI app process. Called with lock(fast) */ static FastApp *startFastApp(Fast *fast, HttpStream *stream) { FastApp *app; HttpRoute *route; HttpRx *rx; MprSocket *listen; cchar **argv, *command, **envv; int argc, i, count; rx = stream->rx; route = stream->rx->route; app = allocFastApp(fast, stream); if (fast->launch) { argc = 1; if ((command = buildFastArgs(app, stream, &argc, &argv)) == 0) { httpError(stream, HTTP_CODE_NOT_FOUND, "Cannot find Fast app command"); return NULL; } /* Build environment variables. Currently use only the server env vars. */ count = mprGetHashLength(rx->svars); if ((envv = mprAlloc((count + 2) * sizeof(char*))) != 0) { count = prepFastEnv(stream, envv, rx->svars); } httpLog(app->trace, "fast", "context", 0, "msg:Start FastCGI app, command:%s", command); if ((listen = createListener(app, stream)) == NULL) { return NULL; } if (!app->signal) { app->signal = mprAddSignalHandler(SIGCHLD, reapSignalHandler, app, NULL, MPR_SIGNAL_BEFORE); } if ((app->pid = fork()) < 0) { fprintf(stderr, "Fork failed for FastCGI"); return NULL; } else if (app->pid == 0) { /* Child */ dup2(listen->fd, 0); /* When debugging, keep stdout/stderr open so printf/fprintf from the FastCGI app will show in the console. */ for (i = FAST_DEBUG ? 3 : 1; i < 128; i++) { close(i); } envv = NULL; if (execve(command, (char**) argv, (char*const*) envv) < 0) { printf("Cannot exec fast app: %s\n", command); } return NULL; } else { httpLog(app->trace, "fast", "context", 0, "msg:FastCGI started app, command:%s, pid:%d", command, app->pid); mprCloseSocket(listen, 0); } } return app; } /* Build the command arguments for the FastCGI app */ static cchar *buildFastArgs(FastApp *app, HttpStream *stream, int *argcp, cchar ***argvp) { Fast *fast; HttpRx *rx; HttpTx *tx; cchar *actionProgram, *cp, *fileName, *query; char **argv, *tok; ssize len; int argc, argind; fast = app->fast; rx = stream->rx; tx = stream->tx; fileName = tx->filename; actionProgram = 0; argind = 0; argc = *argcp; if (fast->launch && fast->launch[0]) { if (mprMakeArgv(fast->launch, (cchar***) &argv, 0) != 1) { mprLog("fast error", 0, "Cannot parse FastCGI launch command %s", fast->launch); return 0; } actionProgram = argv[0]; argc++; } else if (tx->ext) { actionProgram = mprGetMimeProgram(rx->route->mimeTypes, tx->ext); if (actionProgram != 0) { argc++; } } /* Count the args for ISINDEX queries. Only valid if there is not a "=" in the query. If this is so, then we must not have these args in the query env also? */ query = (char*) rx->parsedUri->query; if (query && !schr(query, '=')) { argc++; for (cp = query; *cp; cp++) { if (*cp == '+') { argc++; } } } else { query = 0; } len = (argc + 1) * sizeof(char*); argv = mprAlloc(len); if (actionProgram) { argv[argind++] = sclone(actionProgram); } argv[argind++] = sclone(fileName); if (query) { cp = stok(sclone(query), "+", &tok); while (cp) { argv[argind++] = mprEscapeCmd(mprUriDecode(cp), 0); cp = stok(NULL, "+", &tok); } } assert(argind <= argc); argv[argind] = 0; *argcp = argc; *argvp = (cchar**) argv; return argv[0]; } /* Proxy process has died, so reap the status and inform relevant streams. WARNING: this may be called before all the data has been read from the socket, so we must not set eof = 1 here. WARNING: runs on the MPR dispatcher. Everyting must be "fast" locked. */ static void reapSignalHandler(FastApp *app, MprSignal *sp) { Fast *fast; FastRequest *req; int next, status; fast = app->fast; lock(fast); if (app->pid && waitpid(app->pid, &status, WNOHANG) == app->pid) { httpLog(app->trace, "fast", WEXITSTATUS(status) == 0 ? "context" : "error", 0, "msg:FastCGI exited, pid:%d, status:%d", app->pid, WEXITSTATUS(status)); if (app->signal) { mprRemoveSignalHandler(app->signal); app->signal = 0; } if (mprLookupItem(app->fast->idleApps, app) >= 0) { mprRemoveItem(app->fast->idleApps, app); } app->destroyed = 1; app->pid = 0; closeAppSockets(app); /* Notify all requests on their relevant dispatcher Introduce a short delay (1) in the unlikely event that a FastCGI program witout keep alive exits and we get notified before the I/O response is received. */ for (ITERATE_ITEMS(app->requests, req, next)) { mprCreateLocalEvent(req->stream->dispatcher, "fast-reap", 0, fastHandlerReapResponse, req, 10); } } unlock(fast); } /* Kill the FastCGI app due to error or maxRequests limit being exceeded */ static void killFastApp(FastApp *app) { lock(app->fast); if (app->pid) { httpLog(app->trace, "fast", "context", 0, "msg:Kill FastCGI process, pid:%d", app->pid); if (app->pid) { kill(app->pid, SIGTERM); app->destroyed = 1; } } unlock(app->fast); } /* Create a socket connection to the FastCGI app. Retry if the FastCGI is not yet ready. */ static MprSocket *getFastSocket(FastApp *app) { MprSocket *socket; MprTicks timeout; Fast *fast; int backoff, retries, connected; fast = app->fast; connected = 0; retries = 1; backoff = 1; while ((socket = mprPopItem(app->sockets)) != 0) { mprRemoveSocketHandler(socket); if (socket->flags & (MPR_SOCKET_EOF | MPR_SOCKET_DISCONNECTED)) { continue; } return socket; } timeout = mprGetTicks() + FAST_CONNECT_TIMEOUT; while (1) { httpLog(app->trace, "fast.rx", "request", 0, "FastCGI connect, ip:%s, port:%d", app->ip, app->port); socket = mprCreateSocket(); if (mprConnectSocket(socket, app->ip, app->port, MPR_SOCKET_NODELAY) == 0) { connected = 1; break; } if (mprGetTicks() >= timeout) { break; } // WARNING: yields mprSleep(backoff); backoff = backoff * 2; if (backoff > 50) { mprLog("fast", 2, "FastCGI retry connect to %s:%d", app->ip, app->port); if (backoff > 2000) { backoff = 2000; } } } if (!connected) { mprLog("fast error", 0, "Cannot connect to FastCGI at %s port %d", app->ip, app->port); socket = 0; } return socket; } /* Add the FastCGI spec packet header to the packet->prefix See the spec at https://github.com/fast-cgi/spec/blob/master/spec.md */ static HttpPacket *createFastPacket(HttpQueue *q, int type, HttpPacket *packet) { FastRequest *req; uchar *buf; ssize len, pad; req = q->queueData; if (!packet) { packet = httpCreateDataPacket(0); } len = httpGetPacketLength(packet); packet->prefix = mprCreateBuf(16, 16); buf = (uchar*) packet->prefix->start; *buf++ = FAST_VERSION; *buf++ = type; assert(req->id); *buf++ = (uchar) (req->id >> 8); *buf++ = (uchar) (req->id & 0xFF); *buf++ = (uchar) (len >> 8); *buf++ = (uchar) (len & 0xFF); /* Use 8 byte padding alignment */ pad = (len % 8) ? (8 - (len % 8)) : 0; assert(pad < 8); if (pad > 0) { if (mprGetBufSpace(packet->content) < pad) { mprGrowBuf(packet->content, pad); } mprAdjustBufEnd(packet->content, pad); } *buf++ = (uchar) pad; mprAdjustBufEnd(packet->prefix, 8); httpLog(req->trace, "tx.fast", "packet", "msg:FastCGI tx packet, type:%s, id:%d, lenth:%ld", fastTypes[type], req->id, len); return packet; } static void prepFastRequestStart(HttpQueue *q) { HttpPacket *packet; FastRequest *req; uchar *buf; req = q->queueData; packet = httpCreateDataPacket(16); buf = (uchar*) packet->content->start; *buf++= 0; *buf++= FAST_RESPONDER; *buf++ = req->fast->keep ? FAST_KEEP_CONN : 0; /* Reserved bytes */ buf += 5; mprAdjustBufEnd(packet->content, 8); httpPutForService(req->connWriteq, createFastPacket(q, FAST_BEGIN_REQUEST, packet), HTTP_SCHEDULE_QUEUE); } static void prepFastRequestParams(HttpQueue *q) { FastRequest *req; HttpStream *stream; HttpPacket *packet; HttpRx *rx; req = q->queueData; stream = q->stream; rx = stream->rx; packet = httpCreateDataPacket(stream->limits->headerSize); packet->data = req; // This is an Apache compatible hack for PHP 5.3 // mprAddKey(rx->headers, "REDIRECT_STATUS", itos(HTTP_CODE_MOVED_TEMPORARILY)); copyFastParams(packet, rx->params, rx->route->envPrefix); copyFastVars(packet, rx->svars, ""); copyFastVars(packet, rx->headers, "HTTP_"); httpPutForService(req->connWriteq, createFastPacket(q, FAST_PARAMS, packet), HTTP_SCHEDULE_QUEUE); httpPutForService(req->connWriteq, createFastPacket(q, FAST_PARAMS, 0), HTTP_SCHEDULE_QUEUE); } /************************************************ FastRequest ***********************************************************/ /* Setup the request. Must be called locked. */ static FastRequest *allocFastRequest(FastApp *app, HttpStream *stream, MprSocket *socket) { FastRequest *req; req = mprAllocObj(FastRequest, manageFastRequest); req->stream = stream; req->socket = socket; req->trace = stream->trace; req->fast = app->fast; req->app = app; if (app->nextID >= MAXINT64) { app->nextID = 1; } req->id = app->nextID++ % FAST_MAX_ID; if (req->id == 0) { req->id = app->nextID++ % FAST_MAX_ID; } assert(req->id); req->connReadq = httpCreateQueue(stream->net, stream, HTTP->fastConnector, HTTP_QUEUE_RX, 0); req->connWriteq = httpCreateQueue(stream->net, stream, HTTP->fastConnector, HTTP_QUEUE_TX, 0); req->connReadq->max = FAST_Q_SIZE; req->connWriteq->max = FAST_Q_SIZE; req->connReadq->queueData = req; req->connWriteq->queueData = req; req->connReadq->pair = req->connWriteq; req->connWriteq->pair = req->connReadq; return req; } static void manageFastRequest(FastRequest *req, int flags) { if (flags & MPR_MANAGE_MARK) { mprMark(req->fast); mprMark(req->app); mprMark(req->connReadq); mprMark(req->socket); mprMark(req->stream); mprMark(req->trace); mprMark(req->connWriteq); } } static void fastConnectorIncoming(HttpQueue *q, HttpPacket *packet) { FastRequest *req; req = q->queueData; httpPutForService(req->connWriteq, packet, HTTP_SCHEDULE_QUEUE); } /* Parse an incoming response packet from the FastCGI app */ static void fastConnectorIncomingService(HttpQueue *q) { FastRequest *req; FastApp *app; HttpPacket *packet, *tail; MprBuf *buf; ssize contentLength, len, padLength; int requestID, type, version; req = q->queueData; app = req->app; app->lastActive = mprGetTicks(); while ((packet = httpGetPacket(q)) != 0) { buf = packet->content; if (mprGetBufLength(buf) < FAST_PACKET_SIZE) { // Insufficient data httpPutBackPacket(q, packet); break; } version = mprGetCharFromBuf(buf); type = mprGetCharFromBuf(buf); requestID = (mprGetCharFromBuf(buf) << 8) | (mprGetCharFromBuf(buf) & 0xFF); contentLength = (mprGetCharFromBuf(buf) << 8) | (mprGetCharFromBuf(buf) & 0xFF); padLength = mprGetCharFromBuf(buf); /* reserved */ (void) mprGetCharFromBuf(buf); len = contentLength + padLength; if (version != FAST_VERSION) { httpLog(app->trace, "fast", "error", 0, "msg:Bad FastCGI response version"); break; } if (contentLength < 0 || contentLength > 65535) { httpLog(app->trace, "fast", "error", 0, "msg:Bad FastCGI content length, length:%ld", contentLength); break; } if (padLength < 0 || padLength > 255) { httpLog(app->trace, "fast", "error", 0, "msg:Bad FastCGI pad length, padding:%ld", padLength); break; } if (mprGetBufLength(buf) < len) { // Insufficient data mprAdjustBufStart(buf, -FAST_PACKET_SIZE); httpPutBackPacket(q, packet); break; } packet->type = type; httpLog(req->trace, "rx.fast", "packet", "msg:FastCGI rx packet, type:%s, id:%d, length:%ld, padding %ld", fastTypes[type], req->id, len, padLength); /* Split extra data off this packet */ if ((tail = httpSplitPacket(packet, len)) != 0) { httpPutBackPacket(q, tail); } if (padLength) { // Discard padding mprAdjustBufEnd(packet->content, -padLength); } if (type == FAST_STDOUT || type == FAST_END_REQUEST) { fastHandlerResponse(req, type, packet); } else if (type == FAST_STDERR) { // Log and discard stderr httpLog(app->trace, "fast", "error", 0, "msg:FastCGI stderr, uri:%s, error:%s", req->stream->rx->uri, mprBufToString(packet->content)); } else { httpLog(app->trace, "fast", "error", 0, "msg:FastCGI invalid packet, command:%s, type:%d", req->stream->rx->uri, type); app->destroy = 1; } } } /* Handle IO events on the network */ static void fastConnectorIO(FastRequest *req, MprEvent *event) { Fast *fast; HttpNet *net; HttpPacket *packet; ssize nbytes; fast = req->fast; net = req->stream->net; if (req->eof) { // Network connection to client has been destroyed return; } if (event->mask & MPR_WRITABLE) { httpServiceQueue(req->connWriteq); } if (event->mask & MPR_READABLE) { lock(fast); if (req->socket) { packet = httpCreateDataPacket(ME_PACKET_SIZE); nbytes = mprReadSocket(req->socket, mprGetBufEnd(packet->content), ME_PACKET_SIZE); req->eof = mprIsSocketEof(req->socket); if (nbytes > 0) { req->bytesRead += nbytes; mprAdjustBufEnd(packet->content, nbytes); httpJoinPacketForService(req->connReadq, packet, 0); httpServiceQueue(req->connReadq); } } unlock(fast); } req->app->lastActivity = net->http->now; httpServiceNetQueues(net, 0); if (!req->eof) { enableFastConnector(req); } } /* Detect FastCGI closing the idle socket */ static void idleSocketIO(MprSocket *sp, MprEvent *event) { mprCloseSocket(sp, 0); } static void enableFastConnector(FastRequest *req) { MprSocket *sp; HttpStream *stream; int eventMask; lock(req->fast); sp = req->socket; stream = req->stream; if (sp && !req->eof && !(sp->flags & MPR_SOCKET_CLOSED)) { eventMask = 0; if (req->connWriteq->count > 0) { eventMask |= MPR_WRITABLE; } /* We always ingest from the connector and packets are queued at the fastHandler head writeq. */ if (stream->writeq->count < stream->writeq->max) { eventMask |= MPR_READABLE; } if (eventMask) { if (sp->handler == 0) { mprAddSocketHandler(sp, eventMask, stream->dispatcher, fastConnectorIO, req, 0); } else { mprWaitOn(sp->handler, eventMask); } } else if (sp->handler) { mprWaitOn(sp->handler, eventMask); } req->eventMask = eventMask; } unlock(req->fast); } /* Send request and post body data to the fastCGI app */ static void fastConnectorOutgoingService(HttpQueue *q) { Fast *fast; FastApp *app; FastRequest *req, *cp; HttpNet *net; ssize written; int errCode, next; req = q->queueData; app = req->app; fast = app->fast; app->lastActive = mprGetTicks(); net = q->net; if (req->eof || req->socket == 0) { return; } lock(fast); req->writeBlocked = 0; while (q->first || net->ioIndex) { if (net->ioIndex == 0 && buildFastVec(q) <= 0) { freeFastPackets(q, 0); break; } written = mprWriteSocketVector(req->socket, net->iovec, net->ioIndex); if (written < 0) { errCode = mprGetError(); if (errCode == EAGAIN || errCode == EWOULDBLOCK) { /* Socket full, wait for an I/O event */ req->writeBlocked = 1; break; } mprSetSocketEof(req->socket, 1); req->eof = 1; app->destroy = 1; httpLog(req->app->trace, "fast", "error", 0, "msg:Write error, errno:%d", errCode); for (ITERATE_ITEMS(app->requests, cp, next)) { fastHandlerResponse(cp, FAST_COMMS_ERROR, NULL); } break; } else if (written > 0) { freeFastPackets(q, written); adjustFastVec(net, written); } else { /* Socket full */ break; } } req->app->lastActivity = q->net->http->now; enableFastConnector(req); unlock(fast); } /* Build the IO vector. Return the count of bytes to be written. Return -1 for EOF. */ static MprOff buildFastVec(HttpQueue *q) { HttpNet *net; HttpPacket *packet; net = q->net; /* Examine each packet and accumulate as many packets into the I/O vector as possible. Leave the packets on the queue for now, they are removed after the IO is complete for the entire packet. */ for (packet = q->first; packet; packet = packet->next) { if (net->ioIndex >= (ME_MAX_IOVEC - 2)) { break; } if (httpGetPacketLength(packet) > 0 || packet->prefix) { addFastPacket(net, packet); } } return net->ioCount; } /* Add a packet to the io vector. Return the number of bytes added to the vector. */ static void addFastPacket(HttpNet *net, HttpPacket *packet) { assert(net->ioIndex < (ME_MAX_IOVEC - 2)); if (packet->prefix && mprGetBufLength(packet->prefix) > 0) { addToFastVector(net, mprGetBufStart(packet->prefix), mprGetBufLength(packet->prefix)); } if (packet->content && mprGetBufLength(packet->content) > 0) { addToFastVector(net, mprGetBufStart(packet->content), mprGetBufLength(packet->content)); } } /* Add one entry to the io vector */ static void addToFastVector(HttpNet *net, char *ptr, ssize bytes) { assert(bytes > 0); net->iovec[net->ioIndex].start = ptr; net->iovec[net->ioIndex].len = bytes; net->ioCount += bytes; net->ioIndex++; } static void freeFastPackets(HttpQueue *q, ssize bytes) { HttpPacket *packet; ssize len; assert(q->count >= 0); assert(bytes >= 0); while ((packet = q->first) != 0) { if (packet->flags & HTTP_PACKET_END) { ; } else if (bytes > 0) { if (packet->prefix) { len = mprGetBufLength(packet->prefix); len = min(len, bytes); mprAdjustBufStart(packet->prefix, len); bytes -= len; /* Prefixes don't count in the q->count. No need to adjust */ if (mprGetBufLength(packet->prefix) == 0) { /* Ensure the prefix is not resent if all the content is not sent */ packet->prefix = 0; } } if (packet->content) { len = mprGetBufLength(packet->content); len = min(len, bytes); mprAdjustBufStart(packet->content, len); bytes -= len; q->count -= len; assert(q->count >= 0); } } if ((packet->flags & HTTP_PACKET_END) || (httpGetPacketLength(packet) == 0 && !packet->prefix)) { /* Done with this packet - consume it */ httpGetPacket(q); } else { /* Packet still has data to be written */ break; } } } /* Clear entries from the IO vector that have actually been transmitted. Support partial writes. */ static void adjustFastVec(HttpNet *net, ssize written) { MprIOVec *iovec; ssize len; int i, j; if (written == net->ioCount) { net->ioIndex = 0; net->ioCount = 0; } else { /* Partial write of an vector entry. Need to copy down the unwritten vector entries. */ net->ioCount -= written; assert(net->ioCount >= 0); iovec = net->iovec; for (i = 0; i < net->ioIndex; i++) { len = iovec[i].len; if (written < len) { iovec[i].start += written; iovec[i].len -= written; break; } else { written -= len; } } /* Compact the vector */ for (j = 0; i < net->ioIndex; ) { iovec[j++] = iovec[i++]; } net->ioIndex = j; } } /* FastCGI encoding of strings */ static void encodeFastLen(MprBuf *buf, cchar *s) { ssize len; len = slen(s); if (len <= 127) { mprPutCharToBuf(buf, (uchar) len); } else { mprPutCharToBuf(buf, (uchar) (((len >> 24) & 0x7f) | 0x80)); mprPutCharToBuf(buf, (uchar) ((len >> 16) & 0xff)); mprPutCharToBuf(buf, (uchar) ((len >> 8) & 0xff)); mprPutCharToBuf(buf, (uchar) (len & 0xff)); } } /* FastCGI encoding of names and values. Used to send params. */ static void encodeFastName(HttpPacket *packet, cchar *name, cchar *value) { MprBuf *buf; buf = packet->content; encodeFastLen(buf, name); encodeFastLen(buf, value); mprPutStringToBuf(buf, name); mprPutStringToBuf(buf, value); } static void copyFastInner(HttpPacket *packet, cchar *key, cchar *value, cchar *prefix) { FastRequest *req; req = packet->data; if (prefix) { key = sjoin(prefix, key, NULL); } httpLog(req->trace, "tx.fast", "detail", 0, "msg:FastCGI env, key:%s, value:%s", key, value); encodeFastName(packet, key, value); } static void copyFastVars(HttpPacket *packet, MprHash *vars, cchar *prefix) { MprKey *kp; for (ITERATE_KEYS(vars, kp)) { if (kp->data) { copyFastInner(packet, kp->key, kp->data, prefix); } } } static void copyFastParams(HttpPacket *packet, MprJson *params, cchar *prefix) { MprJson *param; int i; for (ITERATE_JSON(params, param, i)) { copyFastInner(packet, param->name, param->value, prefix); } } static int fastConnectDirective(MaState *state, cchar *key, cchar *value) { Fast *fast; cchar *endpoint, *args, *ip; char *option, *ovalue, *tok; int port; fast = getFast(state->route); if (!maTokenize(state, value, "%S ?*", &endpoint, &args)) { return MPR_ERR_BAD_SYNTAX; } fast->endpoint = endpoint; if (mprParseSocketAddress(fast->endpoint, &fast->ip, &fast->port, NULL, 0) < 0) { mprLog("fast", 0, "Cannot parse listening endpoint"); return MPR_ERR_BAD_SYNTAX; } if (args) { for (option = maGetNextArg(sclone(args), &tok); option; option = maGetNextArg(tok, &tok)) { option = ssplit(option, " =\t,", &ovalue); ovalue = strim(ovalue, "\"'", MPR_TRIM_BOTH); if (smatch(option, "maxRequests")) { fast->maxRequests = httpGetNumber(ovalue); if (fast->maxRequests < 1) { fast->maxRequests = 1; } } else if (smatch(option, "launch")) { fast->launch = sclone(httpExpandRouteVars(state->route, ovalue)); } else if (smatch(option, "keep")) { if (ovalue == NULL || smatch(ovalue, "true")) { fast->keep = 1; } else if (smatch(ovalue, "false")) { fast->keep = 0; } else { fast->keep = httpGetNumber(ovalue); } } else if (smatch(option, "max")) { fast->maxApps = httpGetInt(ovalue); if (fast->maxApps < 1) { fast->maxApps = 1; } } else if (smatch(option, "min")) { fast->minApps = httpGetInt(ovalue); if (fast->minApps < 1) { fast->minApps = 0; } } else if (smatch(option, "multiplex")) { fast->multiplex = httpGetInt(ovalue); if (fast->multiplex < 1) { fast->multiplex = 1; } } else if (smatch(option, "timeout")) { fast->appTimeout = httpGetTicks(ovalue); if (fast->appTimeout < (30 * TPS)) { fast->appTimeout = 30 * TPS; } } else { mprLog("fast error", 0, "Unknown FastCGI option %s", option); return MPR_ERR_BAD_SYNTAX; } } } /* Pre-test the endpoint */ if (mprParseSocketAddress(fast->endpoint, &ip, &port, NULL, 9128) < 0) { mprLog("fast error", 0, "Cannot bind FastCGI app address: %s", fast->endpoint); return MPR_ERR_BAD_SYNTAX; } return 0; } /* Create listening socket that is passed to the FastCGI app (and then closed after forking) */ static MprSocket *createListener(FastApp *app, HttpStream *stream) { Fast *fast; MprSocket *listen; int flags; fast = app->fast; listen = mprCreateSocket(); /* Port may be zero in which case a dynamic port number is used. If port specified and max > 1, then must reruse port. */ flags = MPR_SOCKET_BLOCK | MPR_SOCKET_NODELAY; if (fast->multiplex > 1 && fast->port) { flags |= MPR_SOCKET_REUSE_PORT; } if (mprListenOnSocket(listen, fast->ip, fast->port, flags) == SOCKET_ERROR) { if (mprGetError() == EADDRINUSE) { httpLog(app->trace, "fast", "error", 0, "msg:Cannot open listening socket for FastCGI. Already bound, address:%s, port:%d", fast->ip ? fast->ip : "*", fast->port); } else { httpLog(app->trace, "fast", "error", 0, "msg:Cannot open listening socket for FastCGI, address:%s port:%d", fast->ip ? fast->ip : "*", fast->port); } httpError(stream, HTTP_CODE_INTERNAL_SERVER_ERROR, "Cannot create listening endpoint"); return NULL; } app->ip = fast->ip; if (fast->port == 0) { app->port = getListenPort(listen); } else { app->port = fast->port; } httpLog(app->trace, "fast", "context", 0, "msg:Listening for FastCGI, endpoint: %s, port:%d", app->ip ? app->ip : "*", app->port); return listen; } static int getListenPort(MprSocket *socket) { struct sockaddr_in sin; socklen_t len; len = sizeof(sin); if (getsockname(socket->fd, (struct sockaddr *)&sin, &len) < 0) { return MPR_ERR_CANT_FIND; } return ntohs(sin.sin_port); } static int prepFastEnv(HttpStream *stream, cchar **envv, MprHash *vars) { HttpRoute *route; MprKey *kp; cchar *canonical; char *cp; int index = 0; route = stream->rx->route; for (ITERATE_KEYS(vars, kp)) { if (kp->data) { cp = sjoin(kp->key, "=", kp->data, NULL); if (stream->rx->route->flags & HTTP_ROUTE_ENV_ESCAPE) { // This will escape: "&;`'\"|*?~<>^()[]{}$\\\n" and also on windows \r% cp = mprEscapeCmd(cp, 0); } envv[index] = cp; for (; *cp != '='; cp++) { if (*cp == '-') { *cp = '_'; } else { *cp = toupper((uchar) *cp); } } index++; } } canonical = route->canonical ? httpUriToString(route->canonical, 0) : route->host->defaultEndpoint->ip; envv[index++] = sfmt("FCGI_WEB_SERVER_ADDRS=%s", canonical); envv[index] = 0; #if KEEP int i; for (i = 0; i < index; i++) { print("ENV[%d] = %s", i, envv[i]); } #endif return index; } #if ME_DEBUG static void fastInfo(void *ignored, MprSignal *sp) { Fast *fast; FastApp *app; FastRequest *req; Http *http; HttpHost *host; HttpRoute *route; HttpStream *stream; HttpRx *rx; int nextHost, nextRoute, nextApp, nextReq; http = HTTP; print("\nFast Report:"); for (ITERATE_ITEMS(http->hosts, host, nextHost)) { for (ITERATE_ITEMS(host->routes, route, nextRoute)) { if ((fast = route->eroute) == 0 || fast->magic != FAST_MAGIC) { continue; } print("\nRoute %-40s ip %s:%d", route->pattern, fast->ip, fast->port); for (ITERATE_ITEMS(fast->apps, app, nextApp)) { print("\n App free sockets %d, requests %d, ip %s:%d\n", app->sockets->length, app->requests->length, app->ip, app->port); for (ITERATE_ITEMS(app->requests, req, nextReq)) { stream = req->stream; rx = stream->rx; print(" Req %p ID %d, socket %p flags 0x%x, req eof %d, state %d, finalized output %d, input %d, bytes %d, error %d, netMask 0x%x reqMask 0x%x", req, (int) req->id, req->socket, req->socket->flags, req->eof, stream->state, stream->tx->finalizedOutput, stream->tx->finalizedInput, (int) req->bytesRead, stream->error, stream->net->eventMask, req->eventMask); } } } } } #endif #endif /* ME_COM_FAST */ /* Copyright (c) Embedthis Software. All Rights Reserved. This software is distributed under a commercial license. Consult the LICENSE.md distributed with this software for full details and copyrights. */
31.914494
171
0.561164
[ "vector" ]
d2adadd5cd72b66eabda8d38550159d9a15340c1
4,006
h
C
Sources/Elastos/LibCore/inc/elastos/utility/MiniEnumSet.h
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/LibCore/inc/elastos/utility/MiniEnumSet.h
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/LibCore/inc/elastos/utility/MiniEnumSet.h
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos 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 __ELASTOS_UTILITY_MINIENUMSET_H__ #define __ELASTOS_UTILITY_MINIENUMSET_H__ #include "EnumSet.h" namespace Elastos { namespace Utility { class MiniEnumSet : public EnumSet , public IMiniEnumSet { private: class MiniEnumSetIterator : public Object , public IIterator { public: CAR_INTERFACE_DECL() MiniEnumSetIterator( /* [in] */ IMiniEnumSet* host); CARAPI HasNext( /* [out] */ Boolean* has); CARAPI GetNext( /* [out] */ IInterface** object); CARAPI Remove(); private: IMiniEnumSet* mHost; Int64 mCurrentBits; Int64 mMask; AutoPtr<IInterface> mLast; }; protected: MiniEnumSet(); MiniEnumSet( /* [in] */ const InterfaceID& cls, /* [in] */ ArrayOf<IInterface *> * enums); public: CAR_INTERFACE_DECL() CARAPI constructor(); CARAPI constructor( /* [in] */ const InterfaceID& cls, /* [in] */ ArrayOf<IInterface *> * enums); CARAPI Add( /* [in] */ IInterface* object, /* [out] */ Boolean* modified); CARAPI AddAll( /* [in] */ ICollection* collection, /* [out] */ Boolean* modified); CARAPI Clear(); CARAPI GetSize( /* [out] */ Int32* size); CARAPI GetIterator( /* [out] */ IIterator** it); CARAPI Contains( /* [in] */ IInterface* object, /* [out] */ Boolean* result); CARAPI ContainsAll( /* [in] */ ICollection* collection, /* [out] */ Boolean* result); CARAPI RemoveAll( /* [in] */ ICollection* collection, /* [out] */ Boolean* modified); CARAPI RetainAll( /* [in] */ ICollection* collection, /* [out] */ Boolean* modified); CARAPI Remove( /* [in] */ IInterface* object, /* [out] */ Boolean* modified); CARAPI Equals( /* [in] */ IInterface* object, /* [out] */ Boolean* result); CARAPI Complement(); CARAPI SetRange( /* [in] */ IInterface* start, /* [in] */ IInterface* end); CARAPI Clone( /* [out] */ IInterface** object); CARAPI GetEnums( /*[out, callee]*/ ArrayOf<IInterface*>** arrays); CARAPI GetBits( /*[out]*/ Int64* bits); CARAPI Remove( /* [in] */ IInterface* object); CARAPI RemoveAll( /* [in] */ ICollection* collection); CARAPI RetainAll( /* [in] */ ICollection* collection); CARAPI Add(/* [in] */ IInterface* object); CARAPI AddAll(/* [in] */ ICollection* collection); CARAPI GetHashCode(/* [out] */ Int32* result); CARAPI IsEmpty(/* [out] */ Boolean* result); CARAPI ToArray( /* [out, callee] */ ArrayOf<IInterface*>** array); CARAPI ToArray( /* [in] */ ArrayOf<IInterface*>* inarray, /* [out, callee] */ ArrayOf<IInterface*>** outarray); protected: CARAPI_(String) GetClassName() { return String("MiniEnumSet"); } private: static const Int32 MAX_ELEMENTS;// = 64; AutoPtr< ArrayOf<IInterface*> > mEnums; Int32 mSize; Int64 mBits; }; } // namespace Utility } // namespace Elastos #endif //__ELASTOS_UTILITY_MINIENUMSET_H__
24.13253
75
0.565901
[ "object" ]
d2b04afbf30171506e65a6241c95fde6ec44bff6
7,233
c
C
kore.c
krakjoe/kore
cbcdb6e6a8b2453200583885174c7a376b59c585
[ "PHP-3.01" ]
5
2017-01-30T20:04:32.000Z
2018-12-23T11:01:11.000Z
kore.c
krakjoe/kore
cbcdb6e6a8b2453200583885174c7a376b59c585
[ "PHP-3.01" ]
null
null
null
kore.c
krakjoe/kore
cbcdb6e6a8b2453200583885174c7a376b59c585
[ "PHP-3.01" ]
2
2017-01-31T14:20:58.000Z
2018-12-18T11:49:09.000Z
/* +----------------------------------------------------------------------+ | PHP Version 7 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2017 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: krakjoe | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "ext/spl/spl_exceptions.h" #include "php_kore.h" #include "zend_exceptions.h" #if PHP_VERSION_ID >= 70200 ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(func_get_named_args_info, 0, 0, IS_ARRAY, 0) #else ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(func_get_named_args_info, 0, 0, IS_ARRAY, NULL, 0) #endif ZEND_ARG_TYPE_INFO(0, format, IS_CALLABLE, 0) ZEND_END_ARG_INFO() /* {{{ proto array func_get_named_args([callable format]) */ PHP_FUNCTION(func_get_named_args) { zend_execute_data *frame = EX(prev_execute_data); zval *arg = ZEND_CALL_ARG(frame, 1); zval *end = arg + ZEND_CALL_NUM_ARGS(frame); zend_arg_info *info = frame->func->common.arg_info; zend_fcall_info fci = empty_fcall_info; zend_fcall_info_cache fcc = empty_fcall_info_cache; if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "|f", &fci, &fcc) != SUCCESS) { return; } array_init(return_value); if (frame->func->type == ZEND_INTERNAL_FUNCTION) { return; } while (arg < end && info) { if (ZEND_NUM_ARGS()) { zval name, rv; ZVAL_STR(&name, info->name); fci.retval = &rv; fci.params = &name; fci.param_count = 1; if (zend_call_function(&fci, &fcc) != SUCCESS) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "failed to call format function for %s", ZSTR_VAL(info->name)); return; } if (zend_hash_add(Z_ARRVAL_P(return_value), Z_STR(rv), arg)) { Z_TRY_ADDREF_P(arg); } zval_dtor(&rv); } else { if (zend_hash_add(Z_ARRVAL_P(return_value), info->name, arg)) { Z_TRY_ADDREF_P(arg); } } #if PHP_VERSION_ID >= 80000 if (ZEND_ARG_IS_VARIADIC(info)) { #else if (info->is_variadic) { #endif break; } arg++; info++; } } /* }}} */ #if PHP_VERSION_ID >= 70200 ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(func_get_return_type_info, 0, 0, IS_STRING, 1) #else ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(func_get_return_type_info, 0, 0, IS_STRING, NULL, 1) #endif ZEND_END_ARG_INFO() /* {{{ proto ?string func_get_return_type(void) */ PHP_FUNCTION(func_get_return_type) { zend_execute_data *frame = EX(prev_execute_data); zend_arg_info *info; if (!(frame->func->common.fn_flags & ZEND_ACC_HAS_RETURN_TYPE)) { return; } if (frame->func->type == ZEND_INTERNAL_FUNCTION) { return; } info = frame->func->common.arg_info - 1; #if PHP_VERSION_ID >= 80000 if (ZEND_TYPE_IS_ONLY_MASK(info->type)) { switch (ZEND_TYPE_PURE_MASK(info->type)) { case MAY_BE_STRING: RETURN_STRING(zend_get_type_by_const(IS_STRING)); case MAY_BE_LONG: RETURN_STRING(zend_get_type_by_const(IS_LONG)); case MAY_BE_DOUBLE: RETURN_STRING(zend_get_type_by_const(IS_DOUBLE)); case MAY_BE_ARRAY: RETURN_STRING(zend_get_type_by_const(IS_ARRAY)); case MAY_BE_NULL: case MAY_BE_VOID: RETURN_STRING("void"); default: return; } } RETURN_STR_COPY(ZEND_TYPE_NAME(info->type)); #elif PHP_VERSION_ID >= 70200 if (!ZEND_TYPE_IS_CLASS(info->type)) { RETURN_STRING(zend_get_type_by_const(ZEND_TYPE_CODE(info->type))); } RETURN_STR(ZEND_TYPE_NAME(info->type)); #else if (info->type_hint != IS_OBJECT) { RETURN_STRING(zend_get_type_by_const(info->type_hint)); } RETURN_STR(info->class_name); #endif } /* }}} */ #if PHP_VERSION_ID >= 70200 ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(object_dump_info, 0, 0, IS_ARRAY, 1) #else ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(object_dump_info, 0, 0, IS_ARRAY, NULL, 1) #endif ZEND_ARG_TYPE_INFO(0, object, IS_OBJECT, 0) ZEND_END_ARG_INFO() /* {{{ proto array object_dump(object $object) */ PHP_FUNCTION(object_dump) { zval *object = NULL, *v = NULL; HashTable *table, *ht; zend_string *k = NULL; if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "o", &object) != SUCCESS) { return; } if (!Z_OBJ_HANDLER_P(object, get_properties)) { return; } #if PHP_VERSION_ID >= 80000 table = Z_OBJ_HANDLER_P(object, get_properties)(Z_OBJ_P(object)); #else table = Z_OBJ_HANDLER_P(object, get_properties)(object); #endif if (!table) { return; } array_init(return_value); ZEND_HASH_FOREACH_STR_KEY_VAL(table, k, v) { const char *class_name, *prop_name; zend_long class_name_len, prop_name_len; zend_unmangle_property_name_ex(k, &class_name, &prop_name, &prop_name_len); if (Z_TYPE_P(v) == IS_INDIRECT) { v = Z_INDIRECT_P(v); } if (class_name) { if (class_name[0] == '*') { if (zend_hash_str_add(Z_ARRVAL_P(return_value), prop_name, prop_name_len, v)) { Z_TRY_ADDREF_P(v); } } else { zend_string *pk = strpprintf(0, "%s::%s", class_name, prop_name); if (zend_hash_add(Z_ARRVAL_P(return_value), pk, v)) { Z_TRY_ADDREF_P(v); } zend_string_release(pk); } } else { if (zend_hash_add(Z_ARRVAL_P(return_value), k, v)) { Z_TRY_ADDREF_P(v); } } } ZEND_HASH_FOREACH_END(); } /* }}} */ /* {{{ PHP_RINIT_FUNCTION */ PHP_RINIT_FUNCTION(kore) { #if defined(COMPILE_DL_KORE) && defined(ZTS) ZEND_TSRMLS_CACHE_UPDATE(); #endif return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(kore) { php_info_print_table_start(); php_info_print_table_header(2, "kore support", "enabled"); php_info_print_table_end(); } /* }}} */ /* {{{ kore_functions[] */ const zend_function_entry kore_functions[] = { PHP_FE(func_get_named_args, func_get_named_args_info) PHP_FE(func_get_return_type, func_get_return_type_info) PHP_FE(object_dump, object_dump_info) PHP_FE_END }; /* }}} */ /* {{{ kore_module_entry */ zend_module_entry kore_module_entry = { STANDARD_MODULE_HEADER, "kore", kore_functions, NULL, NULL, PHP_RINIT(kore), NULL, PHP_MINFO(kore), PHP_KORE_VERSION, STANDARD_MODULE_PROPERTIES }; /* }}} */ #ifdef COMPILE_DL_KORE #ifdef ZTS ZEND_TSRMLS_CACHE_DEFINE() #endif ZEND_GET_MODULE(kore) #endif /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
24.770548
92
0.641642
[ "object" ]
d2b0e15a961fdc4835cea7bbbfeb97387adcb6b6
2,568
h
C
c_wrapper/include/clambdacommon/lstring.h
AperLambda/AperCommon
f35deee3784c2e3995fe8442c338aa2f7700142b
[ "MIT" ]
7
2017-08-14T10:40:19.000Z
2022-01-17T16:11:45.000Z
c_wrapper/include/clambdacommon/lstring.h
AperLambda/lambdacommon
f35deee3784c2e3995fe8442c338aa2f7700142b
[ "MIT" ]
null
null
null
c_wrapper/include/clambdacommon/lstring.h
AperLambda/lambdacommon
f35deee3784c2e3995fe8442c338aa2f7700142b
[ "MIT" ]
null
null
null
/* * Copyright © 2019 LambdAurora <aurora42lambda@gmail.com> * * This file is part of λcommon. * * Licensed under the MIT license. For more information, * see the LICENSE file. */ #ifndef CLAMBDACOMMON_LSTRING_H #define CLAMBDACOMMON_LSTRING_H #include "clambdacommon.h" #include <inttypes.h> #ifdef __cplusplus extern "C" { #endif /*! * Splits a string into a vector with a delimiter. * @param s String to split. * @param delim Delimiter. * @return The split string count. */ //uint64_t lc_str_split(const char *s, char delim, char **output); /*! * Checks if two chars are equal with case insensitive. * @param a One of two chars. * @param b One of two chars. * @return True if they are equal with case insensitive else false. */ bool lc_char_equals_ignore_case(char a, char b); /*! * Checks if two strings are equal. * @param a One of two strings. * @param b One of two strings. * @return True if they are equal else false. */ bool lc_str_equals(const char* a, const char* b); /*! * Checks if two strings are equal with case insensitive. * @param a One of two strings. * @param b One of two strings. * @return True if they are equal with case insensitive else false. */ bool lc_str_equals_ignore_case(const char* a, const char* b); /*! * Transforms a string to a full lower case string. * @param from The string to transform. * @return The new string. */ //std::string to_lower_case(const char *from); /*! * Transforms a string to a full lower case string. * @param from The string to transform. * @return The new string. */ //std::string to_upper_case(const char *from); //std::string replace_all(std::string subject, const char &from, const char &to); /*std::string replace_all(std::string subject, const char *from, const char *to );*/ /*! * Transforms a boolean value into a string value. * @param value A boolean value. * @return The boolean value as a string. */ const char* lc_bool_to_string(bool value); /*! * Transforms a pointer address into a string value. * @param pointer The pointer address. * @return The pointer address as a string. */ const char* lc_pointer_to_string(const void* pointer); bool lc_str_ends_with(const char* str, const char* suffix); bool lc_str_starts_with(const char* str, const char* prefix); int lc_str_parse_int(const char* integer); int lc_str_parse_int_base(const char* integer, int base); long lc_str_parse_long(const char* longNumber); long lc_str_parse_long_base(const char* longNumber, int base); #ifdef __cplusplus } #endif #endif //CLAMBDACOMMON_LSTRING_H
24
81
0.723131
[ "vector", "transform" ]
d2b0faa5990f2ca389474f18a2c16c4f1a5f8387
1,888
h
C
lib/seismic/libseispp/HFArray.h
jreyes1108/antelope_contrib
be2354605d8463d6067029eb16464a0bf432a41b
[ "BSD-2-Clause", "MIT" ]
30
2015-02-20T21:44:29.000Z
2021-09-27T02:53:14.000Z
lib/seismic/libseispp/HFArray.h
jreyes1108/antelope_contrib
be2354605d8463d6067029eb16464a0bf432a41b
[ "BSD-2-Clause", "MIT" ]
14
2015-07-07T19:17:24.000Z
2020-12-19T19:18:53.000Z
lib/seismic/libseispp/HFArray.h
jreyes1108/antelope_contrib
be2354605d8463d6067029eb16464a0bf432a41b
[ "BSD-2-Clause", "MIT" ]
46
2015-02-06T16:22:41.000Z
2022-03-30T11:46:37.000Z
#include <vector> #include <map> #include "slowness.h" #include "RegionalCoordinates.h" #include "dbpp.h" using namespace SEISPP; using namespace std; class HFArray { public: HFArray(){}; /*! \brief Construct from a text file. Format is: line 1: ORIGIN lon lat elev(km) line 2+" staname lon lat elev(km) for geo coords OR staname x y z for cartesian coordinates \param fname - file name of text file \param geocoords - if true assume input is geographic coordinates (default is cartesian) */ HFArray(string fname,bool geocoords=false); /*! \brief Construct from a css3.0 database. The antelope css3.0 schema database uses a site table to define locations. This constructor uses only the dnorth and deast attributes to define array coordinates. \param dbh is a handle the Antelope db (does not need to point at site \param net is SEED netname to limit db site selection. If this is empty the entire site table will be loaded. */ HFArray(DatascopeHandle& dbh,string net); /*! Standard copy constructor. */ HFArray(const HFArray& parent); /*! Return Cartesian coordinates (in km) as e,n,z vector. */ vector<double> x(string sta); /* Compute moveout for surface array */ double moveout(string sta, SlownessVector u); /* Compute moveout for 3D array with large elevation variations */ double moveout(string sta, SlownessVector u, double v0); Geographic_point origin(); Geographic_point geographic_location(string sta); HFArray& operator=(const HFArray& parent); private: map<string,vector<double> > stations; RegionalCoordinates coords; };
36.307692
74
0.625
[ "vector", "3d" ]
d2b377473a701e2f3f5c8fff4ca0539ed184fb4f
9,326
h
C
be/src/storage/txn_manager.h
gengjun-git/starrocks
62ab1625d71bbdc82ccbc00a8a46b1458fb0d2f8
[ "Apache-2.0" ]
1
2021-12-10T08:41:10.000Z
2021-12-10T08:41:10.000Z
be/src/storage/txn_manager.h
gengjun-git/starrocks
62ab1625d71bbdc82ccbc00a8a46b1458fb0d2f8
[ "Apache-2.0" ]
null
null
null
be/src/storage/txn_manager.h
gengjun-git/starrocks
62ab1625d71bbdc82ccbc00a8a46b1458fb0d2f8
[ "Apache-2.0" ]
null
null
null
// This file is made available under Elastic License 2.0. // This file is based on code available under the Apache license here: // https://github.com/apache/incubator-doris/blob/master/be/src/olap/txn_manager.h // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #ifndef STARROCKS_BE_SRC_OLAP_TXN_MANAGER_H #define STARROCKS_BE_SRC_OLAP_TXN_MANAGER_H #include <pthread.h> #include <rapidjson/document.h> #include <condition_variable> #include <list> #include <map> #include <mutex> #include <set> #include <string> #include <thread> #include <unordered_map> #include <unordered_set> #include <vector> #include "agent/status.h" #include "common/status.h" #include "gen_cpp/AgentService_types.h" #include "gen_cpp/BackendService_types.h" #include "gen_cpp/MasterService_types.h" #include "storage/kv_store.h" #include "storage/lru_cache.h" #include "storage/olap_common.h" #include "storage/olap_define.h" #include "storage/options.h" #include "storage/rowset/rowset.h" #include "storage/rowset/rowset_meta.h" #include "storage/tablet.h" #include "util/time.h" namespace starrocks { struct TabletTxnInfo { PUniqueId load_id; RowsetSharedPtr rowset; int64_t creation_time; TabletTxnInfo(PUniqueId load_id, RowsetSharedPtr rowset) : load_id(load_id), rowset(rowset), creation_time(UnixSeconds()) {} TabletTxnInfo() {} }; // txn manager is used to manage mapping between tablet and txns class TxnManager { public: TxnManager(int32_t txn_map_shard_size, int32_t txn_shard_size); ~TxnManager() { delete[] _txn_tablet_maps; delete[] _txn_partition_maps; delete[] _txn_map_locks; delete[] _txn_mutex; } OLAPStatus prepare_txn(TPartitionId partition_id, const TabletSharedPtr& tablet, TTransactionId transaction_id, const PUniqueId& load_id); OLAPStatus commit_txn(TPartitionId partition_id, const TabletSharedPtr& tablet, TTransactionId transaction_id, const PUniqueId& load_id, const RowsetSharedPtr& rowset_ptr, bool is_recovery); OLAPStatus publish_txn(TPartitionId partition_id, const TabletSharedPtr& tablet, TTransactionId transaction_id, const Version& version, VersionHash version_hash); // publish_txn for updatable tablet OLAPStatus publish_txn2(TTransactionId transaction_id, TPartitionId partition_id, const TabletSharedPtr& tablet, int64_t version); // delete the txn from manager if it is not committed(not have a valid rowset) OLAPStatus rollback_txn(TPartitionId partition_id, const TabletSharedPtr& tablet, TTransactionId transaction_id); OLAPStatus delete_txn(TPartitionId partition_id, const TabletSharedPtr& tablet, TTransactionId transaction_id); // add a txn to manager // partition id is useful in publish version stage because version is associated with partition OLAPStatus prepare_txn(TPartitionId partition_id, TTransactionId transaction_id, TTabletId tablet_id, SchemaHash schema_hash, TabletUid tablet_uid, const PUniqueId& load_id); OLAPStatus commit_txn(KVStore* meta, TPartitionId partition_id, TTransactionId transaction_id, TTabletId tablet_id, SchemaHash schema_hash, TabletUid tablet_uid, const PUniqueId& load_id, const RowsetSharedPtr& rowset_ptr, bool is_recovery); // remove a txn from txn manager & persist rowset meta OLAPStatus publish_txn(KVStore* meta, TPartitionId partition_id, TTransactionId transaction_id, TTabletId tablet_id, SchemaHash schema_hash, TabletUid tablet_uid, const Version& version, VersionHash version_hash); // delete the txn from manager if it is not committed(not have a valid rowset) OLAPStatus rollback_txn(TPartitionId partition_id, TTransactionId transaction_id, TTabletId tablet_id, SchemaHash schema_hash, TabletUid tablet_uid); // remove the txn from txn manager // delete the related rowset if it is not null // delete rowset related data if it is not null OLAPStatus delete_txn(KVStore* meta, TPartitionId partition_id, TTransactionId transaction_id, TTabletId tablet_id, SchemaHash schema_hash, TabletUid tablet_uid); void get_tablet_related_txns(TTabletId tablet_id, SchemaHash schema_hash, TabletUid tablet_uid, int64_t* partition_id, std::set<int64_t>* transaction_ids); void get_txn_related_tablets(const TTransactionId transaction_id, TPartitionId partition_ids, std::map<TabletInfo, RowsetSharedPtr>* tablet_infos); void get_all_related_tablets(std::set<TabletInfo>* tablet_infos); // just check if the txn exists bool has_txn(TPartitionId partition_id, TTransactionId transaction_id, TTabletId tablet_id, SchemaHash schema_hash, TabletUid tablet_uid); // get all expired txns and save tham in expire_txn_map. // This is currently called before reporting all tablet info, to avoid iterating txn map for every tablets. void build_expire_txn_map(std::map<TabletInfo, std::vector<int64_t>>* expire_txn_map); void force_rollback_tablet_related_txns(KVStore* meta, TTabletId tablet_id, SchemaHash schema_hash, TabletUid tablet_uid); void get_partition_ids(const TTransactionId transaction_id, std::vector<TPartitionId>* partition_ids); private: using TxnKey = std::pair<int64_t, int64_t>; // partition_id, transaction_id; // implement TxnKey hash function to support TxnKey as a key for unordered_map struct TxnKeyHash { template <typename T, typename U> size_t operator()(const std::pair<T, U>& e) const { return std::hash<T>()(e.first) ^ std::hash<U>()(e.second); } }; // implement TxnKey equal function to support TxnKey as a key for unordered_map struct TxnKeyEqual { template <class T, typename U> bool operator()(const std::pair<T, U>& l, const std::pair<T, U>& r) const { return l.first == r.first && l.second == r.second; } }; typedef std::unordered_map<TxnKey, std::map<TabletInfo, TabletTxnInfo>, TxnKeyHash, TxnKeyEqual> txn_tablet_map_t; typedef std::unordered_map<int64_t, std::unordered_set<int64_t>> txn_partition_map_t; inline std::shared_mutex& _get_txn_map_lock(TTransactionId transactionId); inline txn_tablet_map_t& _get_txn_tablet_map(TTransactionId transactionId); inline txn_partition_map_t& _get_txn_partition_map(TTransactionId transactionId); inline std::mutex& _get_txn_lock(TTransactionId transactionId); // insert or remove (transaction_id, partition_id) from _txn_partition_map // get _txn_map_lock before calling void _insert_txn_partition_map_unlocked(int64_t transaction_id, int64_t partition_id); void _clear_txn_partition_map_unlocked(int64_t transaction_id, int64_t partition_id); private: const int32_t _txn_map_shard_size; const int32_t _txn_shard_size; // _txn_map_locks[i] protect _txn_tablet_maps[i], i=0,1,2...,and i < _txn_map_shard_size txn_tablet_map_t* _txn_tablet_maps; // transaction_id -> corresponding partition ids // This is mainly for the clear txn task received from FE, which may only has transaction id, // so we need this map to find out which partitions are corresponding to a transaction id. // The _txn_partition_maps[i] should be constructed/deconstructed/modified alongside with '_txn_tablet_maps[i]' txn_partition_map_t* _txn_partition_maps; std::shared_mutex* _txn_map_locks; std::mutex* _txn_mutex; DISALLOW_COPY_AND_ASSIGN(TxnManager); }; // TxnManager inline std::shared_mutex& TxnManager::_get_txn_map_lock(TTransactionId transactionId) { return _txn_map_locks[transactionId & (_txn_map_shard_size - 1)]; } inline TxnManager::txn_tablet_map_t& TxnManager::_get_txn_tablet_map(TTransactionId transactionId) { return _txn_tablet_maps[transactionId & (_txn_map_shard_size - 1)]; } inline TxnManager::txn_partition_map_t& TxnManager::_get_txn_partition_map(TTransactionId transactionId) { return _txn_partition_maps[transactionId & (_txn_map_shard_size - 1)]; } inline std::mutex& TxnManager::_get_txn_lock(TTransactionId transactionId) { return _txn_mutex[transactionId & (_txn_shard_size - 1)]; } } // namespace starrocks #endif // STARROCKS_BE_SRC_OLAP_TXN_MANAGER_H
43.579439
120
0.73665
[ "vector" ]
d2b656c5e4d0ac4e300fa040287c4f9de358e873
8,585
h
C
Source/Framework/Core/Mesh/TeMeshData.h
fabsgc/TweedeFrameworkRedux
2c61e6f31c43db36a20d3288e45047586a503725
[ "Zlib" ]
57
2019-09-02T01:10:37.000Z
2022-01-11T06:28:10.000Z
Source/Framework/Core/Mesh/TeMeshData.h
fabsgc/TweedeFrameworkRedux
2c61e6f31c43db36a20d3288e45047586a503725
[ "Zlib" ]
null
null
null
Source/Framework/Core/Mesh/TeMeshData.h
fabsgc/TweedeFrameworkRedux
2c61e6f31c43db36a20d3288e45047586a503725
[ "Zlib" ]
6
2020-02-29T17:19:30.000Z
2021-10-30T04:29:22.000Z
#pragma once #include "TeCorePrerequisites.h" #include "Resources/TeGpuResourceData.h" #include "RenderAPI/TeVertexDeclaration.h" #include "Math/TeBounds.h" namespace te { /** Contains per-vertex bone weights and indexes used for skinning, for up to four bones. */ struct BoneWeight { int Index0; int Index1; int Index2; int Index3; float Weight0; float Weight1; float Weight2; float Weight3; }; /** Contains mesh vertex and index data used for initializing, updating and reading mesh data from Mesh. */ class TE_CORE_EXPORT MeshData : public GpuResourceData { public: /** * Constructs a new object that can hold number of vertices described by the provided vertex data description. As * well as a number of indices of the provided type. */ MeshData(UINT32 numVertices, UINT32 numIndexes, const SPtr<VertexDataDesc>& vertexData, IndexType indexType = IT_32BIT); ~MeshData(); /** * Copies data from @p data parameter into the internal buffer for the specified semantic. * * @param[in] semantic Semantic that allows the engine to connect the data to a shader input slot. * @param[in] data Vertex data, containing at least @p size bytes. * @param[in] size The size of the data. Must be the size of the vertex element type * number of * vertices. * @param[in] semanticIdx (optional) If there are multiple semantics with the same name, use different index * to differentiate between them. * @param[in] streamIdx (optional) Zero-based index of the stream. Each stream will internally be * represented as a single vertex buffer. */ void SetVertexData(VertexElementSemantic semantic, void* data, UINT32 size, UINT32 semanticIdx = 0, UINT32 streamIdx = 0); /** * Copies data from the internal buffer to the pre-allocated buffer for the specified semantic. * * @param[in] semantic Semantic that allows the engine to connect the data to a shader input slot. * @param[in] data Buffer that will receive vertex data, of at least @p size bytes. * @param[in] size The size of the data. Must be the size of the vertex element type * number of * vertices. * @param[in] semanticIdx (optional) If there are multiple semantics with the same name, use different index * to differentiate between them. * @param[in] streamIdx (optional) Zero-based index of the stream. Each stream will internally be * represented as a single vertex buffer. */ void GetVertexData(VertexElementSemantic semantic, void* data, UINT32 size, UINT32 semanticIdx = 0, UINT32 streamIdx = 0); /** Returns the total number of vertices this object can hold. */ UINT32 GetNumVertices() const { return _numVertices; } /** Returns the total number of indices this object can hold. */ UINT32 GetNumIndices() const; /** Returns a 16-bit pointer to the start of the internal index buffer. */ UINT16* GetIndices16() const; /** Returns a 32-bit pointer to the start of the internal index buffer. */ UINT32* GetIndices32() const; /** Returns the size of an index element in bytes. */ UINT32 GetIndexElementSize() const; /** Returns the type of an index element. */ IndexType GetIndexType() const { return _indexType; } /** * Returns the pointer to the first element of the specified type. If you want to iterate over all elements you * need to call getVertexStride() to get the number of bytes you need to advance between each element. * * @param[in] semantic Semantic that allows the engine to connect the data to a shader input slot. * @param[in] semanticIdx (optional) If there are multiple semantics with the same name, use different index * to differentiate between them. * @param[in] streamIdx (optional) Zero-based index of the stream. Each stream will internally be * represented as a single vertex buffer. * @return null if it fails, else the element data. */ UINT8* GetElementData(VertexElementSemantic semantic, UINT32 semanticIdx = 0, UINT32 streamIdx = 0) const; /** * Returns an offset into the internal buffer where this element with the provided semantic starts. Offset is * provided in number of bytes. * * @param[in] semantic Semantic that allows the engine to connect the data to a shader input slot. * @param[in] semanticIdx (optional) If there are multiple semantics with the same name, use different index * to differentiate between them. * @param[in] streamIdx (optional) Zero-based index of the stream. Each stream will internally be * represented as a single vertex buffer. */ UINT32 GetElementOffset(VertexElementSemantic semantic, UINT32 semanticIdx = 0, UINT32 streamIdx = 0) const; /** Returns a pointer to the start of the index buffer. */ UINT8* GetIndexData() const { return GetData(); } /** Returns a pointer to the start of the specified vertex stream. */ UINT8* GetStreamData(UINT32 streamIdx) const; /** Returns the size of the specified stream in bytes. */ UINT32 GetStreamSize(UINT32 streamIdx) const; /** Returns the size of all the streams in bytes. */ UINT32 GetStreamSize() const; /** Returns an object that describes data contained in a single vertex. */ const SPtr<VertexDataDesc>& GetVertexDesc() const { return _vertexData; } /** Return the size (in bytes) of the entire buffer. */ UINT32 GetSize() const { return GetInternalBufferSize(); } /** Calculates the bounds of all vertices corresponding to the range from indexOffset with indexCount elements */ Bounds CalculateBounds(UINT32 indexOffset, UINT32 indexCount) const; /** Calculates the bounds of all vertices stored in the internal buffer. */ Bounds CalculateBounds() const; /** * Combines a number of submeshes and their mesh data into one large mesh data buffer. * * @param[in] elements Data containing vertices and indices referenced by the submeshes. Number of elements * must be the same as number of submeshes. * @param[in] allSubMeshes Submeshes representing vertex and index range to take from mesh data and combine. * Number of submeshes must match the number of provided MeshData elements. * @param[out] subMeshes Outputs all combined sub-meshes with their new index and vertex offsets referencing * the newly created MeshData. * @return Combined mesh data containing all vertices and indexes references by the provided * sub-meshes. */ static SPtr<MeshData> Combine(const Vector<SPtr<MeshData>>& elements, const Vector<Vector<SubMesh>>& allSubMeshes, Vector<SubMesh>& subMeshes); /** * Constructs a new object that can hold number of vertices described by the provided vertex data description. As * well as a number of indices of the provided type. */ static SPtr<MeshData> Create(UINT32 numVertices, UINT32 numIndexes, const SPtr<VertexDataDesc>& vertexData, IndexType indexType = IT_32BIT) { return te_shared_ptr_new<MeshData>(numVertices, numIndexes, vertexData, indexType); } protected: /** Returns the size of the internal buffer in bytes. */ UINT32 GetInternalBufferSize() const override; public: /** Returns an offset in bytes to the start of the index buffer from the start of the internal buffer. */ UINT32 GetIndexBufferOffset() const; /** Returns an offset in bytes to the start of the stream from the start of the internal buffer. */ UINT32 GetStreamOffset(UINT32 streamIdx = 0) const; /** Returns the size of the index buffer in bytes. */ UINT32 GetIndexBufferSize() const; private: friend class Mesh; UINT32 _numVertices; UINT32 _numIndices; IndexType _indexType; SPtr<VertexDataDesc> _vertexData; }; }
47.960894
130
0.653232
[ "mesh", "object", "vector" ]
d2c191740f71a5f10ae6d1e3fe3e8dee7485fd22
4,414
h
C
Includes/Core/Grid/VertexCenteredScalarGrid2.h
utilForever/CubbyFlow-v1
d85c136d8eaa91ecce456c3356c7e578dda5d5bd
[ "MIT" ]
3
2020-04-15T13:41:16.000Z
2020-12-29T11:23:59.000Z
Includes/Core/Grid/VertexCenteredScalarGrid2.h
utilForever/CubbyFlow-v1
d85c136d8eaa91ecce456c3356c7e578dda5d5bd
[ "MIT" ]
null
null
null
Includes/Core/Grid/VertexCenteredScalarGrid2.h
utilForever/CubbyFlow-v1
d85c136d8eaa91ecce456c3356c7e578dda5d5bd
[ "MIT" ]
null
null
null
/************************************************************************* > File Name: VertexCenteredScalarGrid2.h > Project Name: CubbyFlow > Author: Chan-Ho Chris Ohk > Purpose: 2-D Vertex-centered scalar grid structure. > Created Time: 2017/07/07 > Copyright (c) 2018, Chan-Ho Chris Ohk *************************************************************************/ #ifndef CUBBYFLOW_VERTEX_CENTERED_SCALAR_GRID2_H #define CUBBYFLOW_VERTEX_CENTERED_SCALAR_GRID2_H #include <Core/Grid/ScalarGrid2.h> namespace CubbyFlow { //! //! \brief 2-D Vertex-centered scalar grid structure. //! //! This class represents 2-D vertex-centered scalar grid which extends //! ScalarGrid2. As its name suggests, the class defines the data point at the //! grid vertices (corners). Thus, A x B grid resolution will have (A+1) x (B+1) //! data points. //! class VertexCenteredScalarGrid2 final : public ScalarGrid2 { public: CUBBYFLOW_GRID2_TYPE_NAME(VertexCenteredScalarGrid2) class Builder; //! Constructs zero-sized grid. VertexCenteredScalarGrid2(); //! Constructs a grid with given resolution, grid spacing, origin and //! initial value. VertexCenteredScalarGrid2( size_t resolutionX, size_t resolutionY, double gridSpacingX = 1.0, double gridSpacingY = 1.0, double originX = 0.0, double originY = 0.0, double initialValue = 0.0); //! Constructs a grid with given resolution, grid spacing, origin and //! initial value. VertexCenteredScalarGrid2( const Size2& resolution, const Vector2D& gridSpacing = Vector2D(1.0, 1.0), const Vector2D& origin = Vector2D(), double initialValue = 0.0); //! Copy constructor. VertexCenteredScalarGrid2(const VertexCenteredScalarGrid2& other); //! Returns the actual data point size. Size2 GetDataSize() const override; //! Returns data position for the grid point at (0, 0). //! Note that this is different from origin() since origin() returns //! the lower corner point of the bounding box. Vector2D GetDataOrigin() const override; //! Returns the copy of the grid instance. std::shared_ptr<ScalarGrid2> Clone() const override; //! //! \brief Swaps the contents with the given \p other grid. //! //! This function swaps the contents of the grid instance with the given //! grid object \p other only if \p other has the same type with this grid. //! void Swap(Grid2* other) override; //! Sets the contents with the given \p other grid. void Set(const VertexCenteredScalarGrid2& other); //! Sets the contents with the given \p other grid. VertexCenteredScalarGrid2& operator=(const VertexCenteredScalarGrid2& other); //! Returns builder fox VertexCenteredScalarGrid2. static Builder GetBuilder(); }; //! Shared pointer for the VertexCenteredScalarGrid2 type. using VertexCenteredScalarGrid2Ptr = std::shared_ptr<VertexCenteredScalarGrid2>; //! A grid builder class that returns 2-D vertex-centered scalar grid. class VertexCenteredScalarGrid2::Builder final : public ScalarGridBuilder2 { public: //! Returns builder with resolution. Builder& WithResolution(const Size2& resolution); //! Returns builder with resolution. Builder& WithResolution(size_t resolutionX, size_t resolutionY); //! Returns builder with grid spacing. Builder& WithGridSpacing(const Vector2D& gridSpacing); //! Returns builder with grid spacing. Builder& WithGridSpacing(double gridSpacingX, double gridSpacingY); //! Returns builder with grid origin. Builder& WithOrigin(const Vector2D& gridOrigin); //! Returns builder with grid origin. Builder& WithOrigin(double gridOriginX, double gridOriginY); //! Returns builder with initial value. Builder& WithInitialValue(double initialVal); //! Builds VertexCenteredScalarGrid2 instance. VertexCenteredScalarGrid2 Build() const; //! Builds shared pointer of VertexCenteredScalarGrid2 instance. VertexCenteredScalarGrid2Ptr MakeShared() const; //! //! \brief Builds shared pointer of VertexCenteredScalarGrid2 instance. //! //! This is an overriding function that implements ScalarGridBuilder2. //! ScalarGrid2Ptr Build( const Size2& resolution, const Vector2D& gridSpacing, const Vector2D& gridOrigin, double initialVal) const override; private: Size2 m_resolution{ 1, 1 }; Vector2D m_gridSpacing{ 1, 1 }; Vector2D m_gridOrigin{ 0, 0 }; double m_initialVal = 0.0; }; } #endif
32.696296
81
0.71681
[ "object" ]
d2c3d6efc3d03d3934839ecdf0d1411d85a97e04
685
h
C
src/cetech/mesh/static_mesh.h
OndraVoves/cetech
09857e278ba1596fc1b0e790164bd4dbf843bc5d
[ "CC0-1.0" ]
163
2015-12-10T21:43:15.000Z
2022-01-21T09:19:35.000Z
src/cetech/mesh/static_mesh.h
OndraVoves/cetech
09857e278ba1596fc1b0e790164bd4dbf843bc5d
[ "CC0-1.0" ]
145
2015-11-27T06:24:44.000Z
2017-06-06T07:16:15.000Z
src/cetech/mesh/static_mesh.h
OndraVoves/cetech
09857e278ba1596fc1b0e790164bd4dbf843bc5d
[ "CC0-1.0" ]
21
2015-12-01T09:03:13.000Z
2021-10-02T03:24:29.000Z
#ifndef CETECH_MESH_RENDERER_H #define CETECH_MESH_RENDERER_H #ifdef __cplusplus extern "C" { #endif #include <stdint.h> typedef struct ct_mesh_component { uint64_t material; uint64_t scene; uint64_t node; uint64_t mesh; } ct_mesh_component; #define STATIC_MESH_COMPONENT \ CE_ID64_0("static_mesh", 0x7445bff74058f566ULL) #define PROP_SCENE_ID \ CE_ID64_0("scene", 0x9d0a795bfe818d19ULL) #define PROP_MATERIAL \ CE_ID64_0("material", 0xeac0b497876adedfULL) #define PROP_NODE \ CE_ID64_0("node", 0x5ae0930b5138a928ULL) #define PROP_MESH \ CE_ID64_0("mesh", 0x48ff313713a997a1ULL) #ifdef __cplusplus }; #endif #endif //CETECH_MESH_RENDERER_H
19.027778
51
0.763504
[ "mesh" ]
d2cf8aa4105b5d4c45b31aeef32b7a2c38f14586
6,755
h
C
src/common/definitions.h
asivokon/marian-dev
ab6b8260835a9f77a7b3cd48e3af4e4039280384
[ "MIT" ]
143
2017-08-27T19:01:38.000Z
2022-03-16T18:13:44.000Z
src/common/definitions.h
asivokon/marian-dev
ab6b8260835a9f77a7b3cd48e3af4e4039280384
[ "MIT" ]
732
2017-07-21T15:32:27.000Z
2022-03-22T10:26:09.000Z
src/common/definitions.h
asivokon/marian-dev
ab6b8260835a9f77a7b3cd48e3af4e4039280384
[ "MIT" ]
124
2017-08-31T13:51:21.000Z
2022-03-23T13:58:17.000Z
#pragma once #include "common/logging.h" #include "common/shape.h" #include "common/intrusive_ptr.h" #include <functional> #include <iostream> #include <memory> #include <string> #include <vector> #define THREAD_GUARD(body) [&]() { body; }() // test if THREAD_GUARD is neccessary, remove if no problems occur. #define NodeOp(op) [=]() { op; } // helper macro to disable optimization (gcc only) // To use this, just insert DONT_OPTIMIZE right before the function definition // (e.g. where the "static" keyword would go). #ifdef __GNUC__ #define DONT_OPTIMIZE __attribute__((optimize("O0"))) #else #define DONT_OPTIMIZE // silently ignore on Visual Studio, where this is less of a problem #endif // Use these macros to enable faster floating-point math. Put them around one // or more functions. // // Usage: // MARIAN_FFAST_MATH_BEGIN // void LayerNormalization(float *arg) { *arg += 1.0; } // void SomethingElse() {} // MARIAN_FFAST_MATH_END // // ffast-math allows the compiler to assume associative arithmetic and finite // values. // // Associative arithmetic is particularly important to vectorize i.e. a sum: // for (const float f : range) sum += f; // Without ffast-math, the sum will be done one value at a time. On x86 it // still uses vector math, but only uses the first slot and wastes the rest. // // With ffast-math, the compiler can sum in batches of 4, 8, or 16 floats. // Also, it can run multiple adds in parallel e.g. vaddps has latency 4 and // throughput 0.5 on Skylake so multiple vector adds can run at once. // // On average, a vectorized sum is more numerically stable because it sums in // batches. Vectorized floats can still produce NaNs and infs (remember even // scalar operations are implemented with vector instructions). // // Allowing the compiler to assume finite values means functions like isnan or // isinf do not work as expected. Do not enable this for a function that // depends upon fully standard float behavior. // // It can also change the sign of zeros. // // Fast math also makes results more architecture dependent because different // register widths mean different results. They also depend on the compiler // and compiler version more. For example, clang <= 10 does not support the // float_control pragma below so it will still be conservative. // // There is a more conservative option for just associativity: // llvm introduced "#pragma clang fp reassociate" that goes inside a function. // However, llvm <11 considers that pragma an error so we'd need some ugly // version test (which they don't recommend) or a compilation test. Moreover, // it has to be in the function to keep scope. // gcc supports "-fassociative-math" that has to be outside a function. // I didn't find a MSVC equivalent. #if defined(_MSC_VER) #define MARIAN_FFAST_MATH_BEGIN __pragma(float_control(precise, off, push)) #define MARIAN_FFAST_MATH_END __pragma(float_control(pop)) #elif defined(__clang__) #define MARIAN_FFAST_MATH_BEGIN _Pragma("float_control(precise, off, push)") #define MARIAN_FFAST_MATH_END _Pragma("float_control(pop)") #elif defined(__GNUC__) // Also available as __attribute__((optimize("-ffast-math"))) but done as pragmas for consistency #define MARIAN_FFAST_MATH_BEGIN _Pragma("GCC push_options") _Pragma("GCC optimize(\"-ffast-math\")") #define MARIAN_FFAST_MATH_END _Pragma("GCC pop_options") #endif namespace marian { // Type to be used for all index types, e.g. for integer tensors for rows operator. // size_t would seem to be the natural choice over uint32_t but has usually 8 bytes // while uint32_t has 4 bytes. This type will be often exchanged between CPU and GPU. // This minimizes bandwith at little cost. typedef uint32_t IndexType; // @TODO: come up with better short name. "I..." stands for interface now. Here it stands // for "intrusive". Not a good overlap. template <class T> using IPtr = IntrusivePtr<T>; template <class T> using UPtr = std::unique_ptr<T>; // @TODO: come up with better short name. "I..." stands for interface now. template <class T> using IWeak = T*; template <class T> using Ptr = std::shared_ptr<T>; template <class T> using Weak = std::weak_ptr<T>; /** @brief Creates shared_ptr of any type, passes all arguments to any available * constructor */ template <class T, typename... Args> Ptr<T> New(Args&&... args) { return Ptr<T>(new T(std::forward<Args>(args)...)); } template <class T> Ptr<T> New(Ptr<T> p) { return Ptr<T>(p); } /** @brief Creates InstrusivePtr of any type, passes all arguments to any available * constructor */ template <class T, typename... Args> IPtr<T> INew(Args&&... args) { return IPtr<T>(new T(std::forward<Args>(args)...)); } template <class T> IPtr<T> INew(Ptr<T> p) { return IPtr<T>(p); } /// enum class DeviceType: defines which device is used for computation enum class DeviceType : size_t { gpu = 0, cpu = 1 }; struct DeviceId { size_t no{0}; DeviceType type{DeviceType::gpu}; DeviceId() : no{0}, type{DeviceType::gpu} {} DeviceId(size_t no_, DeviceType type_) : no(no_), type(type_) {} std::string typeAsString() const { return (type == DeviceType::gpu ? "gpu" : "cpu"); } operator std::string() const { return typeAsString() + std::to_string(no); } friend std::ostream& operator<<(std::ostream& out, DeviceId deviceId) { out << std::string(deviceId); return out; } friend bool operator==(DeviceId id1, DeviceId id2) { return id1.no == id2.no && id1.type == id2.type; } friend bool operator!=(DeviceId id1, DeviceId id2) { return !(id1 == id2); } }; // predefine a couple of devices for easier manual use const DeviceId CPU0{0, DeviceType::cpu}; const DeviceId CPU1{1, DeviceType::cpu}; const DeviceId CPU2{2, DeviceType::cpu}; const DeviceId CPU3{3, DeviceType::cpu}; const DeviceId CPU4{4, DeviceType::cpu}; const DeviceId CPU5{5, DeviceType::cpu}; const DeviceId CPU6{6, DeviceType::cpu}; const DeviceId CPU7{7, DeviceType::cpu}; const DeviceId GPU0{0, DeviceType::gpu}; const DeviceId GPU1{1, DeviceType::gpu}; const DeviceId GPU2{2, DeviceType::gpu}; const DeviceId GPU3{3, DeviceType::gpu}; const DeviceId GPU4{4, DeviceType::gpu}; const DeviceId GPU5{5, DeviceType::gpu}; const DeviceId GPU6{6, DeviceType::gpu}; const DeviceId GPU7{7, DeviceType::gpu}; // These are many small objects, hence use IntrusivePtr class TensorBase; typedef IPtr<TensorBase> Tensor; // These are many small objects, hence use IntrusivePtr template <class DataType> class Chainable; typedef IPtr<Chainable<Tensor>> Expr; class OptimizerBase; typedef Ptr<OptimizerBase> OptimizerBasePtr; class ClipperBase; typedef Ptr<ClipperBase> ClipperBasePtr; class RunBase; typedef Ptr<RunBase> RunBasePtr; const float NEMATUS_LN_EPS = 1e-5f; } // namespace marian
33.944724
112
0.731458
[ "shape", "vector" ]
d2d0bf50d9dcc49e41f05eb77f476c1fdaa40819
3,678
h
C
Source/FrequalizerEditor.h
rockyplum/Frequalizer
c851d907d1cb7d939244c8587c55feeab710b1d1
[ "BSD-3-Clause" ]
5
2020-10-27T16:14:54.000Z
2021-03-09T20:03:47.000Z
Source/FrequalizerEditor.h
rockyplum/Frequalizer
c851d907d1cb7d939244c8587c55feeab710b1d1
[ "BSD-3-Clause" ]
null
null
null
Source/FrequalizerEditor.h
rockyplum/Frequalizer
c851d907d1cb7d939244c8587c55feeab710b1d1
[ "BSD-3-Clause" ]
1
2021-03-09T19:42:20.000Z
2021-03-09T19:42:20.000Z
/* ============================================================================== This is the Frequalizer UI editor ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" #include "FrequalizerProcessor.h" //============================================================================== /** */ class FrequalizerAudioProcessorEditor : public AudioProcessorEditor, public ChangeListener, public Timer { public: FrequalizerAudioProcessorEditor (FrequalizerAudioProcessor&); ~FrequalizerAudioProcessorEditor(); //============================================================================== void paint (Graphics&) override; void resized() override; void changeListenerCallback (ChangeBroadcaster* sender) override; void timerCallback() override; void mouseDown (const MouseEvent& e) override; void mouseMove (const MouseEvent& e) override; void mouseDrag (const MouseEvent& e) override; void mouseDoubleClick (const MouseEvent& e) override; //============================================================================== class BandEditor : public Component, public Button::Listener { public: BandEditor (size_t i, FrequalizerAudioProcessor& processor); void resized () override; void updateControls (FrequalizerAudioProcessor::FilterType type); void updateSoloState (bool isSolo); void setFrequency (float frequency); void setGain (float gain); void setType (int type); void buttonClicked (Button* b) override; Path frequencyResponse; private: JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BandEditor) size_t index; FrequalizerAudioProcessor& processor; GroupComponent frame; ComboBox filterType; Slider frequency; Slider quality; Slider gain; TextButton solo; TextButton activate; OwnedArray<AudioProcessorValueTreeState::ComboBoxAttachment> boxAttachments; OwnedArray<AudioProcessorValueTreeState::SliderAttachment> attachments; OwnedArray<AudioProcessorValueTreeState::ButtonAttachment> buttonAttachments; }; private: void updateFrequencyResponses (); static float getPositionForFrequency (float freq); static float getFrequencyForPosition (float pos); static float getPositionForGain (float gain, float top, float bottom); static float getGainForPosition (float pos, float top, float bottom); // This reference is provided as a quick way for your editor to // access the processor object that created it. FrequalizerAudioProcessor& processor; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FrequalizerAudioProcessorEditor) #ifdef JUCE_OPENGL OpenGLContext openGLContext; #endif OwnedArray<BandEditor> bandEditors; Rectangle<int> plotFrame; Rectangle<int> brandingFrame; Path frequencyResponse; Path analyserPath; GroupComponent frame; Slider output; SocialButtons socialButtons; int draggingBand = -1; bool draggingGain = false; OwnedArray<AudioProcessorValueTreeState::SliderAttachment> attachments; SharedResourcePointer<TooltipWindow> tooltipWindow; PopupMenu contextMenu; };
29.66129
85
0.579935
[ "object" ]
d2d0c75f461fd1f6ace4b443572c459172a8d53e
24,179
c
C
src/uz80as.c
vipoo/uz80as
7cf5c353a5c1ceeaf5ba7b502e220fb41e7d9fb0
[ "MIT" ]
1
2021-09-30T08:42:43.000Z
2021-09-30T08:42:43.000Z
src/uz80as.c
vipoo/uz80as
7cf5c353a5c1ceeaf5ba7b502e220fb41e7d9fb0
[ "MIT" ]
null
null
null
src/uz80as.c
vipoo/uz80as
7cf5c353a5c1ceeaf5ba7b502e220fb41e7d9fb0
[ "MIT" ]
null
null
null
/* =========================================================================== * uz80as, an assembler for the Zilog Z80 and several other microprocessors. * * Assembler. * =========================================================================== */ #include "uz80as.h" #include "err.h" #include "expr.h" #include "exprint.h" #include "incl.h" #include "list.h" #include "options.h" #include "pp.h" #include "sym.h" #include "targets.h" #include "utils.h" #include <config.h> #ifndef ASSERT_H #include <assert.h> #endif #ifndef CTYPE_H #include <ctype.h> #endif #ifndef STDIO_H #include <stdio.h> #endif #ifndef STDLIB_H #include <stdlib.h> #endif #ifndef STRING_H #include <string.h> #endif static const char *d_align(const char *); static const char *d_block(const char *); static const char *d_byte(const char *); static const char *d_chk(const char *); static const char *d_codes(const char *); static const char *d_ds(const char *); static const char *d_echo(const char *); static const char *d_eject(const char *); static const char *d_end(const char *); static const char *d_equ(const char *); static const char *d_export(const char *); static const char *d_fill(const char *); static const char *d_list(const char *); static const char *d_lsfirst(const char *); static const char *d_module(const char *); static const char *d_msfirst(const char *); static const char *d_nocodes(const char *); static const char *d_nolist(const char *); static const char *d_null(const char *); static const char *d_org(const char *); static const char *d_set(const char *); static const char *d_text(const char *); static const char *d_title(const char *); static const char *d_word(const char *); int verbose; /* * Directives. * This table must be sorted, to allow for binary search. */ /* clang-format off */ static struct direc { const char *name; const char *(*fun)(const char *); } s_directab[] = { { "ALIGN", d_align }, { "BLOCK", d_block }, { "BYTE", d_byte }, { "CHK", d_chk }, { "CODES", d_codes }, { "DB", d_byte }, { "DS", d_ds }, { "DW", d_word }, { "ECHO", d_echo }, { "EJECT", d_eject }, { "END", d_end }, { "EQU", d_equ }, { "EXPORT", d_export }, { "FILL", d_fill }, { "LIST", d_list }, { "LSFIRST", d_lsfirst }, { "MODULE", d_module }, { "MSFIRST", d_msfirst }, { "NOCODES", d_nocodes }, { "NOLIST", d_nolist }, { "NOPAGE", d_null }, { "ORG", d_org }, { "PAGE", d_null }, { "SET", d_set }, { "TEXT", d_text }, { "TITLE", d_title }, { "WORD", d_word }, }; /* clang-format on */ /* The target. */ const struct target *s_target; /* The z80 addressable memory. The object code. */ static unsigned char s_mem[64 * 1024]; /* Program counter min and max ([s_minpc, s_maxpc[). */ static int s_minpc, s_maxpc; /* Original input line. */ static char s_line[LINESZ]; /* Label defined on this line. */ static struct sym *s_lastsym; /* Output words the most significant byte first */ static int s_msbword; /* If we have seen the .END directive. */ static int s_end_seen; /* We have issued the error of generating things after an .END. */ static int s_gen_after_end; /* The empty line, to pass to listing, for compatibility with TASM. */ static const char *s_empty_line = ""; /* Pointer in s_pline for error reporting. */ const char *s_pline_ep; /* We skip characters until endline or backslash or comment. */ static const char *sync(const char *p) { while (*p != '\0' && *p != '\\' && *p != ';') p++; return p; } /* * Generates a byte to the output and updates s_pc, s_minpc and s_maxpc. * Will issue a fatal error if we write beyong 64k. */ void genb(int b, const char *ep) { if (s_pass == 0 && s_end_seen && !s_gen_after_end) { s_gen_after_end = 1; eprint(_("generating code after .END\n")); eprcol(s_pline, ep); newerr(); } if (s_minpc < 0) s_minpc = s_pc; if (s_pc >= 65536) { eprint(_("generating code beyond address 65535\n")); eprcol(s_pline, ep); exit(EXIT_FAILURE); } s_mem[s_pc] = (unsigned char)b; if (s_pass == 1) list_genb(b); if (s_pc < s_minpc) s_minpc = s_pc; s_pc++; if (s_pc > s_maxpc) s_maxpc = s_pc; } /* * Generate 'n' as a 16 bit word, little endian or big endian depending on * s_msbword. */ static void genw(int n, const char *ep) { if (s_msbword) genb(n >> 8, ep); genb(n, ep); if (!s_msbword) genb(n >> 8, ep); } /* * We have matched an instruction in the table. * Generate the machine code for the instruction using the generation * pattern 'p. 'vs are the arguments generated during the matching process. */ static void gen(const char *p, const int *vs) { // int w, b, i, savepc; int b, i, savepc; const char *p_orig; savepc = s_pc; p_orig = p; b = 0; loop: i = hexvalu(*p); if (i >= 0) { p++; b = (i << 4) | hexval(*p); } else if (*p == '.') { genb(b, s_pline_ep); b = 0; } else if (*p == '\0') { return; } else { i = *(p + 1) - '0'; switch (*p) { case 'b': b |= (vs[i] << 3); break; case 'c': b |= vs[i]; break; case 'd': b = vs[i]; break; case 'e': genb(vs[i] & 0xff, s_pline_ep); genb(vs[i] >> 8, s_pline_ep); break; default: if (s_target->genf(&b, *p, vs, i, savepc) == -1) { eprogname(); fprintf(stderr, _("fatal: bad pattern %s ('%c')"), p_orig, *p); enl(); exit(EXIT_FAILURE); } } p++; } p++; goto loop; } /* * Tries to match *p with any of the strings in list. * If matched, returns the index in list and r points to the position * in p past the matched string. */ int mreg(const char *p, const char *const list[], const char **r) { const char *s; const char *q; int i; i = 0; while ((s = list[i++]) != NULL) { if (*s == '\0') continue; q = p; while (toupper(*q++) == *s++) { if (*s == '\0') { if (!isalnum(*q)) { *r = q; return i - 1; } else { break; } } } } return -1; } static int isoctal(int c) { return c >= '0' && c <= '7'; } /* * Read an octal of 3 digits, being the maximum value 377 (255 decimal); * Return -1 if there is an error in the syntax. */ static int readoctal(const char *p) { int n; const char *q; if (*p >= '0' && *p <= '3' && isoctal(*(p + 1)) && isoctal(*(p + 2))) { n = 0; q = p + 3; while (p < q) { n *= 8; n += (*p - '0'); p++; } return n; } return -1; } enum strmode { STRMODE_ECHO, STRMODE_NULL, STRMODE_BYTE, STRMODE_WORD }; /* * Generate the string bytes until double quote or null char. * Return a pointer to the ending double quote character or '\0'. * 'p must point to the starting double quote. * If mode: * STRMODE_ECHO only echo to stderr the characters. * STRMODE_NULL only parses the string. * STRMODE_BYTE generate the characters in the binary file as bytes. * STRMODE_WORD generate the characters in the binary file as words. */ static const char *genstr(const char *p, enum strmode mode) { int c; for (p = p + 1; *p != '\0' && *p != '\"'; p++) { c = *p; if (c == '\\') { p++; switch (*p) { case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 'b': c = '\b'; break; case 't': c = '\t'; break; case 'f': c = '\f'; break; case '\\': c = '\\'; break; case '\"': c = '\"'; break; default: c = readoctal(p); if (c < 0) { eprint(_("bad character escape " "sequence\n")); eprcol(s_pline, p - 1); newerr(); p--; } else { p += 2; } } } switch (mode) { case STRMODE_ECHO: fputc(c, stderr); break; case STRMODE_NULL: break; case STRMODE_BYTE: genb(c, p); break; case STRMODE_WORD: genw(c, p); break; } } return p; } /* Match an instruction. * If no match returns NULL; else returns one past end of match. * p should point to no whitespace. */ static const char *match(const char *p) { const struct matchtab *mtab; const char * s, *pp, *q; int v, n, vi, linepc; int vs[4]; assert(!isspace(*p)); mtab = s_target->matcht; linepc = s_pc; pp = p; n = -1; next: n++; s = mtab[n].pat; if (s == NULL) { return NULL; } else if ((s_target->mask & mtab[n].mask) == 0) { goto next; } else if (!s_undocumented_op && (s_target->mask & mtab[n].undoc)) { goto next; } p = pp; vi = 0; loop: if (*s == '\0') { p = skipws(p); if (*p != ';' && *p != '\0' && *p != '\\') goto next; else goto found; } else if (*s == ' ') { if (!isspace(*p)) goto next; p = skipws(p); } else if ((*s == ',' || *s == '(' || *s == ')') && isspace(*p)) { p = skipws(p); if (*s != *p) goto next; p = skipws(p + 1); } else if (*s == 'a') { p = expr(p, &v, linepc, s_pass == 0, NULL, NULL); if (p == NULL) return NULL; vs[vi++] = v; } else if (*s >= 'b' && *s <= 'z') { v = s_target->matchf(*s, p, &q); goto reg; } else if (*p == *s && *p == ',') { p = skipws(p + 1); } else if (toupper(*p) == *s) { p++; } else { goto next; } freg: s++; goto loop; reg: if (v < 0) { goto next; } else { assert(vi < sizeof(vs)); vs[vi++] = v; p = q; } goto freg; found: // printf("%s\n", s_matchtab[n].pat); gen(mtab[n].gen, vs); return p; } static const char *d_null(const char *p) { while (*p != '\0' && *p != '\\') { if (!isspace(*p)) { wprint(_("invalid characters after directive\n")); eprcol(s_pline, p); return sync(p); } else { p++; } } return p; } static const char *d_end(const char *p) { enum expr_ecode ecode; const char * q; const char * ep; if (s_pass == 0) { if (s_end_seen) { eprint(_("duplicate .END\n")); eprcol(s_pline, s_pline_ep); newerr(); } else { s_end_seen = 1; } } q = expr(p, NULL, s_pc, s_pass == 0, &ecode, &ep); if (q == NULL && ecode == EXPR_E_NO_EXPR) { return p; } else if (q == NULL) { exprint(ecode, s_pline, ep); newerr(); return NULL; } else { return q; } } static const char *d_module(const char *p) { p = sync(p); while (*p != '\0' && *p != '\\') { if (!isspace(*p)) { wprint(_("invalid characters after directive\n")); eprcol(s_pline, p); return sync(p); } else { p++; } } return p; } static const char *d_codes(const char *p) { s_codes = 1; return p; } static const char *d_ds(const char *p) { int n, v, er; const char * q; enum expr_ecode ecode; const char * ep, *eps; eps = p; er = 0; p = expr(p, &n, s_pc, 0, &ecode, &ep); if (p == NULL) { exprint(ecode, s_pline, ep); newerr(); return NULL; } if (n < 0) { eprint(_("number of positions to space over is negative (%d)\n"), n); eprcol(s_pline, eps); exit(EXIT_FAILURE); } v = 255; p = skipws(p); if (*p == ',') { p = skipws(p + 1); q = expr(p, &v, s_pc, s_pass == 0, &ecode, &ep); if (q == NULL) { er = 1; exprint(ecode, s_pline, ep); newerr(); } else { p = q; } } s_pc += n; if (er) return NULL; else return p; } static const char *d_nocodes(const char *p) { s_codes = 0; return p; } static const char *d_list(const char *p) { s_list_on = 1; return p; } static const char *d_nolist(const char *p) { s_list_on = 0; return p; } static const char *d_eject(const char *p) { list_eject(); return p; } static const char *d_echo(const char *p) { int n; int mode; enum expr_ecode ecode; const char * ep; mode = (s_pass == 0) ? STRMODE_NULL : STRMODE_ECHO; if (*p == '\"') { p = genstr(p, mode); if (*p == '\"') { p++; } else if (s_pass == 0) { wprint(_("no terminating quote\n")); eprcol(s_pline, p); } } else if (*p != '\0') { p = expr(p, &n, s_pc, s_pass == 0, &ecode, &ep); if (p == NULL) { exprint(ecode, s_pline, ep); newerr(); return NULL; } if (mode == STRMODE_ECHO) { fprintf(stderr, "%d", n); } } return p; } static const char *d_equ(const char *p) { int n; enum expr_ecode ecode; const char * ep; p = expr(p, &n, s_pc, 0, &ecode, &ep); if (p == NULL) { exprint(ecode, s_pline, ep); newerr(); return NULL; } if (s_lastsym == NULL) { eprint(_(".EQU without label\n")); eprcol(s_pline, s_pline_ep); newerr(); } else { /* TODO: check label misalign? */ s_lastsym->val = n; s_lastsym->isequ = 1; } return p; } static const char *d_set(const char *p) { int n; enum expr_ecode ecode; const char * ep; p = expr(p, &n, s_pc, 0, &ecode, &ep); if (p == NULL) { exprint(ecode, s_pline, ep); newerr(); return NULL; } if (s_lastsym == NULL) { eprint(_(".EQU without label\n")); eprcol(s_pline, s_pline_ep); newerr(); } else { /* TODO: check label misalign? */ s_lastsym->val = n; s_lastsym->isequ = 1; } return p; } static const char *d_export(const char *p) { /* TODO */ return NULL; } static const char *d_fill(const char *p) { int n, v, er; const char * q; enum expr_ecode ecode; const char * ep, *eps; eps = p; er = 0; p = expr(p, &n, s_pc, 0, &ecode, &ep); if (p == NULL) { exprint(ecode, s_pline, ep); newerr(); return NULL; } if (n < 0) { eprint(_("number of positions to fill is negative (%d)\n"), n); eprcol(s_pline, eps); exit(EXIT_FAILURE); } v = 255; p = skipws(p); if (*p == ',') { p = skipws(p + 1); q = expr(p, &v, s_pc, s_pass == 0, &ecode, &ep); if (q == NULL) { er = 1; exprint(ecode, s_pline, ep); newerr(); } else { p = q; } } while (n--) genb(v, eps); if (er) return NULL; else return p; } static const char *d_lsfirst(const char *p) { s_msbword = 0; return p; } static const char *d_msfirst(const char *p) { s_msbword = 1; return p; } static const char *d_org(const char *p) { int n; enum expr_ecode ecode; const char * ep, *eps; eps = p; p = expr(p, &n, s_pc, 0, &ecode, &ep); if (p == NULL) { exprint(ecode, s_pline, ep); newerr(); return NULL; } if (n < 0 || n > 65536) { eprint(_(".ORG address (%d) is not in range [0, 65536]\n"), n); eprcol(s_pline, eps); exit(EXIT_FAILURE); } s_pc = n; /* Change the listing PC so in orgs we print the changed PC. */ if (s_pass > 0) list_setpc(s_pc); if (s_lastsym != NULL) { /* TODO: check label misalign? */ s_lastsym->val = s_pc; s_lastsym->isequ = 1; } return p; } static const char *d_lst(const char *p, int w) { enum strmode mode; int n, linepc; enum expr_ecode ecode; const char * ep, *eps; if (w) mode = STRMODE_WORD; else mode = STRMODE_BYTE; linepc = s_pc; dnlst: if (*p == '\"') { p = genstr(p, mode); if (*p == '\"') { p++; } else { wprint(_("no terminating quote\n")); eprcol(s_pline, p); } } else { eps = p; p = expr(p, &n, linepc, s_pass == 0, &ecode, &ep); if (p == NULL) { exprint(ecode, s_pline, ep); newerr(); return NULL; } if (w) genw(n, eps); else genb(n, eps); } p = skipws(p); if (*p == ',') { p++; p = skipws(p); goto dnlst; } return p; } static const char *d_byte(const char *p) { return d_lst(p, 0); } static const char *d_word(const char *p) { return d_lst(p, 1); } static const char *d_text(const char *p) { if (*p == '\"') { p = genstr(p, STRMODE_BYTE); if (*p == '\"') { p++; } else { wprint(_("no terminating quote\n")); eprcol(s_pline, p); } return p; } else { eprint(_(".TEXT directive needs a quoted string argument\n")); eprcol(s_pline, p); newerr(); return NULL; } } static const char *d_title(const char *p) { return NULL; } static const char *d_align(const char *p) { int n; enum expr_ecode ecode; const char * ep, *eps; eps = p; p = expr(p, &n, s_pc, 0, &ecode, &ep); if (p == NULL) { exprint(ecode, s_pline, ep); newerr(); return NULL; } if (n < 0) { eprint(_("align is negative (%d)\n"), n); eprcol(s_pline, eps); exit(EXIT_FAILURE); } while (s_pc % n) { genb(0, eps); } return p; } static const char *d_block(const char *p) { int n; enum expr_ecode ecode; const char * ep, *eps; eps = p; p = expr(p, &n, s_pc, 0, &ecode, &ep); if (p == NULL) { exprint(ecode, s_pline, ep); newerr(); return NULL; } s_pc += n; if (s_pc < 0 || s_pc > 65536) { eprint(_("address (%d) set by .BLOCK is not in range " "[0, 65536]\n"), s_pc); eprcol(s_pline, eps); exit(EXIT_FAILURE); } return p; } /* a must be < b. */ static int checksum(int a, int b) { int n; assert(a < b); n = 0; while (a < b) n += s_mem[a++]; return n; } static const char *d_chk(const char *p) { int n; enum expr_ecode ecode; const char * ep, *eps; eps = p; p = expr(p, &n, s_pc, s_pass == 0, &ecode, &ep); if (p == NULL) { exprint(ecode, s_pline, ep); newerr(); genb(0, eps); return NULL; } if (s_pass == 0) { genb(0, s_pline_ep); } else if (n < 0 || n >= s_pc) { eprint(_(".CHK address (%d) is not in range [0, %d[\n"), n, s_pc); eprcol(s_pline, eps); newerr(); genb(0, eps); } else { genb(checksum(n, s_pc), eps); } return p; } /* Parses an internal directive (those that start with '.'). * Returns NULL on error; * If no error returns position past the parsed directive and arguments. */ static const char *parse_direc(const char *cp) { const char *cq, *p; int a, b, m = 0; a = 0; b = NELEMS(s_directab) - 1; while (a <= b) { m = (a + b) / 2; cq = cp; p = s_directab[m].name; while (*p != '\0' && toupper(*cq) == *p) { p++; cq++; } if (*p == '\0' && (*cq == '\0' || isspace(*cq))) break; else if (toupper(*cq) < *p) b = m - 1; else a = m + 1; } if (a <= b) { cq = skipws(cq); return s_directab[m].fun(cq); } else { eprint(_("unrecognized directive\n")); eprcol(s_pline, s_pline_ep); newerr(); return NULL; } } static void parselin(const char *cp) { int col0, alloweq; const char *q; s_pline_ep = cp; start: s_lastsym = NULL; alloweq = 0; col0 = 1; loop: if (*cp == '\0' || *cp == ';') { return; } else if (*cp == '\\') { if (s_pass == 1) { list_endln(); list_startln(s_empty_line, curfile()->linenum, s_pc, nfiles()); } cp++; goto start; } else if (*cp == '.') { s_pline_ep = cp; cp++; q = parse_direc(cp); if (q == NULL) { cp = sync(cp); } else { cp = d_null(q); } } else if ((*cp == '$' || *cp == '*') && cp[1] == '=') { /* Alternative form of .ORG: *= or $= */ cp += 2; q = d_org(cp); if (q == NULL) { cp = sync(cp); } else { cp = d_null(q); } } else if (*cp == '=' && alloweq) { /* equ */ s_pline_ep = cp; cp++; q = d_equ(cp); if (q == NULL) { cp = sync(cp); } else { cp = d_null(q); } } else if (isidc0(*cp)) { if (col0 && *cp != '.') { /* take label */ s_pline_ep = cp; q = cp; col0 = 0; while (isidc(*cp)) cp++; s_lastsym = lookup(q, cp, s_pass == 0, s_pc); if (*cp == ':' || isspace(*cp)) { alloweq = 1; cp++; } else if (*cp == '=') { alloweq = 1; } if (s_pass == 1 && !s_lastsym->isequ && s_lastsym->val != s_pc) { eprint(_("misaligned label %s\n"), s_lastsym->name); fprintf(stderr, _(" Previous value was %XH, " "new value %XH."), s_lastsym->val, s_pc); eprcol(s_pline, s_pline_ep); newerr(); } } else { cp = skipws(cp); s_pline_ep = cp; q = match(cp); if (q == NULL) { eprint(_("syntax error\n")); newerr(); cp = sync(cp); } else { cp = d_null(q); } } } else if (isspace(*cp)) { col0 = 0; while (isspace(*cp)) cp++; } else { eprint(_("unexpected character (%c)\n"), *cp); eprcol(s_pline, cp); newerr(); cp = sync(cp + 1); } goto loop; } /* * Gets a new line into 's_line from 'fin. * Terminates the line with '\0'. * Does not read more than LINESZ - 1 characters. * Does not add a '\n' character, thus a line of length 0 it's possible. * Always advances to the next line. * Returns -1 for EOF or the line length. */ static int getlin(FILE *fin) { int i, c; c = EOF; i = 0; while (i < LINESZ - 1) { c = getc(fin); if (c == EOF || c == '\n') break; s_line[i++] = (char)c; } if (c != EOF && c != '\n') { wprint(_("line too long, truncated to %d characters\n"), LINESZ); } while (c != EOF && c != '\n') c = getc(fin); if (i == 0 && c == EOF) return -1; s_line[i] = '\0'; return i; } /* Preinstall the macros defined in the command line. */ static void install_predefs(void) { struct predef *pdef; for (pdef = s_predefs; pdef != NULL; pdef = pdef->next) pp_define(pdef->name); } /* Do a pass through the source. */ static void dopass(const char *fname) { if (verbose) fprintf(stderr, "start pass %d\n", s_pass); /* Fill memory with default value. */ if ((s_pass == 0 && s_mem_fillval != 0) || s_pass > 0) { memset(s_mem, s_mem_fillval, sizeof(s_mem)); } if (s_pass > 0) { pp_reset(); list_open(s_lstfname); s_codes = 1; s_list_on = 1; } install_predefs(); s_minpc = -1; s_maxpc = -1; s_pc = 0; s_lastsym = NULL; s_msbword = 0; pushfile(fname, fname + strlen(fname)); while (nfiles() > 0) { curfile()->linenum++; if (getlin(curfile()->fin) >= 0) { if (s_pass == 1) { list_startln(s_line, curfile()->linenum, s_pc, nfiles()); } pp_line(s_line); if (s_pass == 1) list_skip(s_skipon); parselin(s_pline); if (s_pass == 1) list_endln(); } else { popfile(); } } list_close(); } /* Write the object file. */ static void output() { FILE *fout; fout = efopen(s_objfname, "wb"); if (s_minpc < 0) s_minpc = 0; if (s_maxpc < 0) s_maxpc = 0; fwrite(s_mem + s_minpc, 1, s_maxpc - s_minpc, fout); if (ferror(fout)) { eprint(_("cannot write to file %s\n"), s_objfname); clearerr(fout); } if (fclose(fout) == EOF) { eprint(_("cannot close file %s\n"), s_objfname); } } /* Start the assembly using the config in options.c. */ void uz80as(void) { s_target = find_target(s_target_id); if (s_target == NULL) { eprint(_("target '%s' not supported\n"), s_target_id); exit(EXIT_FAILURE); } for (s_pass = 0; s_nerrors == 0 && s_pass < 2; s_pass++) { dopass(s_asmfname); if (s_pass == 0 && !s_end_seen) { wprint(_("no .END statement in the source\n")); } if (s_nerrors == 0) { if (verbose) printf("Pass %d completed.\n", s_pass + 1); } } if (s_nerrors > 0) { exit(EXIT_FAILURE); } output(); }
21.025217
78
0.513958
[ "object" ]
d2d7306334548a33de5e2783792c79762f0b57dd
4,373
h
C
include/mif/serialization/boost.h
paceholder/mif
ff3c18f577048c94887220bb92477ce102f01599
[ "MIT" ]
4
2018-03-26T11:49:13.000Z
2019-12-22T06:18:35.000Z
include/mif/serialization/boost.h
paceholder/mif
ff3c18f577048c94887220bb92477ce102f01599
[ "MIT" ]
null
null
null
include/mif/serialization/boost.h
paceholder/mif
ff3c18f577048c94887220bb92477ce102f01599
[ "MIT" ]
1
2018-10-01T09:16:29.000Z
2018-10-01T09:16:29.000Z
//------------------------------------------------------------------- // MetaInfo Framework (MIF) // https://github.com/tdv/mif // Created: 10.2016 // Copyright (C) 2016-2017 tdv //------------------------------------------------------------------- #ifndef __MIF_SERIALIZATION_BOOST_H__ #define __MIF_SERIALIZATION_BOOST_H__ // STD #include <cstdint> #include <tuple> // BOOST #include <boost/serialization/array.hpp> #include <boost/serialization/bitset.hpp> //#include <boost/serialization/boost_unordered_map.hpp> //#include <boost/serialization/boost_unordered_set.hpp> #include <boost/serialization/deque.hpp> #include <boost/serialization/list.hpp> #include <boost/serialization/map.hpp> #include <boost/serialization/optional.hpp> #include <boost/serialization/queue.hpp> #include <boost/serialization/scoped_ptr.hpp> #include <boost/serialization/set.hpp> #include <boost/serialization/shared_ptr.hpp> #include <boost/serialization/stack.hpp> #include <boost/serialization/string.hpp> #include <boost/serialization/unique_ptr.hpp> #include <boost/serialization/unordered_map.hpp> #include <boost/serialization/unordered_set.hpp> #include <boost/serialization/variant.hpp> #include <boost/serialization/vector.hpp> #include <boost/serialization/weak_ptr.hpp> // MIF #include "mif/reflection/reflection.h" namespace Mif { namespace Serialization { namespace Boost { namespace Detail { template <std::size_t I> struct Serializer; template <typename TBases, std::size_t I = std::tuple_size<TBases>::value> struct BasesSerializer { template <typename TArchive, typename T> static void Serialize(TArchive &archive, T &object) { BasesSerializer<TBases, I - 1>::Serialize(archive, object); using BaseType = typename std::tuple_element<I - 1, TBases>::type; archive & boost::serialization::make_nvp(Reflection::Reflect<BaseType>::Name::GetString().c_str(), boost::serialization::base_object<BaseType>(object)); } }; template <typename TBases> struct BasesSerializer<TBases, 0> { template <typename TArchive, typename T> static void Serialize(TArchive &, T &) { } }; template <std::size_t I> struct Serializer { template <typename TArchive, typename T> static void Serialize(TArchive &archive, T &object) { Serializer<I - 1>::Serialize(archive, object); using FieldType = typename Reflection::Reflect<T>::Fields::template Field<I - 1>; archive & boost::serialization::make_nvp(FieldType::Name::GetString().c_str(), object.*FieldType::Access()); } }; template <> struct Serializer<0> { template <typename TArchive, typename T> static void Serialize(TArchive &, T &) { } }; } // namespace Detail template <typename TArchive, typename T> inline void Serialize(TArchive &archive, T &object) { Detail::BasesSerializer<typename Reflection::Reflect<T>::Base>::Serialize(archive, object); Detail::Serializer<Reflection::Reflect<T>::Fields::Count>::Serialize(archive, object); } } // namespace Boost } // namespace Serialization } // namespace Mif #undef MIF_BOOST_TYPE_SERIALIZER #define MIF_BOOST_TYPE_SERIALIZER(type_) \ namespace boost \ { \ namespace serialization \ { \ template<typename TArchive> \ inline void serialize(TArchive &archive, type_ &object, unsigned int) \ { \ ::Mif::Serialization::Boost::Serialize(archive, object); \ } \ } \ } #endif // !__MIF_SERIALIZATION_BOOST_H__
35.266129
122
0.552252
[ "object", "vector" ]
d2da633d98a9c0ecd5ba003d0cad143634c0c382
14,400
c
C
packages/openscap/openscap-1.2.1/src/OVAL/oval_sysModel.c
mpalmi/clip
e31b7a673dc11837222cb009000caf04f0dcd03b
[ "Apache-2.0" ]
1
2016-01-06T15:42:52.000Z
2016-01-06T15:42:52.000Z
packages/openscap/openscap-1.2.1/src/OVAL/oval_sysModel.c
rprevette/clip
e02c0e6e98563365fb81507304ebe716605d94c7
[ "Apache-2.0" ]
null
null
null
packages/openscap/openscap-1.2.1/src/OVAL/oval_sysModel.c
rprevette/clip
e02c0e6e98563365fb81507304ebe716605d94c7
[ "Apache-2.0" ]
null
null
null
/** * @file oval_sysModel.c * \brief Open Vulnerability and Assessment Language * * See more details at http://oval.mitre.org/ */ /* * Copyright 2009--2014 Red Hat Inc., Durham, North Carolina. * All Rights Reserved. * * 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 * * Authors: * "David Niemoller" <David.Niemoller@g2-inc.com> * Šimon Lukašík */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <string.h> #include <time.h> #include "oval_definitions_impl.h" #include "oval_agent_api_impl.h" #include "oval_parser_impl.h" #include "adt/oval_string_map_impl.h" #include "adt/oval_smc_impl.h" #include "adt/oval_smc_iterator_impl.h" #include "oval_system_characteristics_impl.h" #include "oval_probe_impl.h" #include "common/util.h" #include "common/debug_priv.h" #include "common/_error.h" #include "common/elements.h" #include "oscap_source.h" #include "source/oscap_source_priv.h" typedef struct oval_syschar_model { struct oval_generator *generator; struct oval_sysinfo *sysinfo; struct oval_definition_model *definition_model; struct oval_smc *syschar_map; ///< Represents objects within <collected_objects> element struct oval_string_map *sysitem_map; ///< Represents items within <system_data> element char *schema; } oval_syschar_model_t; ///< Represents <oval_system_characteristics> element /* failed - NULL * success - oval_syschar_model * */ struct oval_syschar_model *oval_syschar_model_new(struct oval_definition_model *definition_model) { oval_syschar_model_t *newmodel = (oval_syschar_model_t *) oscap_alloc(sizeof(oval_syschar_model_t)); if (newmodel == NULL) return NULL; newmodel->generator = oval_generator_new(); struct oval_generator *generator = oval_definition_model_get_generator(definition_model); char * schema_version = oval_generator_get_schema_version(generator); oval_generator_set_schema_version(newmodel->generator, schema_version); newmodel->sysinfo = NULL; newmodel->definition_model = definition_model; newmodel->syschar_map = oval_smc_new(); newmodel->sysitem_map = oval_string_map_new(); newmodel->schema = oscap_strdup(OVAL_SYS_SCHEMA_LOCATION); /* check possible allocation problems */ if ((newmodel->syschar_map == NULL) || (newmodel->sysitem_map == NULL) ) { oval_syschar_model_free(newmodel); return NULL; } return newmodel; } typedef void (*_oval_clone_func) (void *, struct oval_syschar_model *); static void _oval_syschar_model_clone(struct oval_string_map *oldmap, struct oval_syschar_model *newmodel, _oval_clone_func cloner) { struct oval_string_iterator *keys = (struct oval_string_iterator *)oval_string_map_keys(oldmap); while (oval_string_iterator_has_more(keys)) { char *key = oval_string_iterator_next(keys); void *olditem = oval_string_map_get_value(oldmap, key); (*cloner) (newmodel, olditem); } oval_string_iterator_free(keys); } static void _oval_syschar_model_clone_helper(struct oval_smc *oldmap, struct oval_syschar_model *newmodel, _oval_clone_func cloner) { struct oval_smc_iterator *it = oval_smc_iterator_new(oldmap); while (oval_smc_iterator_has_more(it)) { void *olditem = oval_smc_iterator_next(it); (*cloner) (newmodel, olditem); } oval_smc_iterator_free(it); } struct oval_syschar_model *oval_syschar_model_clone(struct oval_syschar_model *old_model) { __attribute__nonnull__(old_model); struct oval_syschar_model *new_model = oval_syschar_model_new(old_model->definition_model); _oval_syschar_model_clone_helper(old_model->syschar_map, new_model, (_oval_clone_func) oval_syschar_clone); _oval_syschar_model_clone(old_model->sysitem_map, new_model, (_oval_clone_func) oval_sysitem_clone); struct oval_sysinfo *old_sysinfo = oval_syschar_model_get_sysinfo(old_model); struct oval_sysinfo *new_sysinfo = oval_sysinfo_clone(new_model, old_sysinfo); oval_syschar_model_set_sysinfo(new_model, new_sysinfo); oval_sysinfo_free(new_sysinfo); new_model->schema = oscap_strdup(old_model->schema); return new_model; } void oval_syschar_model_free(struct oval_syschar_model *model) { __attribute__nonnull__(model); if (model->sysinfo) oval_sysinfo_free(model->sysinfo); if (model->syschar_map) oval_smc_free(model->syschar_map, (oscap_destruct_func) oval_syschar_free); if (model->sysitem_map) oval_string_map_free(model->sysitem_map, (oscap_destruct_func) oval_sysitem_free); if (model->schema) oscap_free(model->schema); model->sysinfo = NULL; model->definition_model = NULL; model->syschar_map = NULL; model->sysitem_map = NULL; model->schema = NULL; oval_generator_free(model->generator); oscap_free(model); } void oval_syschar_model_reset(struct oval_syschar_model *model) { if (model->syschar_map) oval_smc_free(model->syschar_map, (oscap_destruct_func) oval_syschar_free); if (model->sysitem_map) oval_string_map_free(model->sysitem_map, (oscap_destruct_func) oval_sysitem_free); model->syschar_map = oval_smc_new(); model->sysitem_map = oval_string_map_new(); } struct oval_generator *oval_syschar_model_get_generator(struct oval_syschar_model *model) { return model->generator; } void oval_syschar_model_set_generator(struct oval_syschar_model *model, struct oval_generator *generator) { oval_generator_free(model->generator); model->generator = generator; } struct oval_definition_model *oval_syschar_model_get_definition_model(struct oval_syschar_model *model) { __attribute__nonnull__(model); return model->definition_model; } struct oval_syschar_iterator *oval_syschar_model_get_syschars(struct oval_syschar_model *model) { __attribute__nonnull__(model); return oval_syschar_iterator_new(model->syschar_map); } struct oval_sysinfo *oval_syschar_model_get_sysinfo(struct oval_syschar_model *model) { __attribute__nonnull__(model); return model->sysinfo; } const char * oval_syschar_model_get_schema(struct oval_syschar_model * model) { __attribute__nonnull__(model); return model->schema; } void oval_syschar_model_set_sysinfo(struct oval_syschar_model *model, struct oval_sysinfo *sysinfo) { __attribute__nonnull__(model); if (model->sysinfo) oval_sysinfo_free(model->sysinfo); model->sysinfo = oval_sysinfo_clone(model, sysinfo); } void oval_syschar_model_set_schema(struct oval_syschar_model *model, const char * schema) { __attribute__nonnull__(model); model->schema = oscap_strdup(schema); } void oval_syschar_model_add_syschar(struct oval_syschar_model *model, struct oval_syschar *syschar) { __attribute__nonnull__(model); const char *id = oval_syschar_get_id(syschar); if (id != NULL) oval_smc_put_last(model->syschar_map, id, syschar); } void oval_syschar_model_add_sysitem(struct oval_syschar_model *model, struct oval_sysitem *sysitem) { __attribute__nonnull__(model); char *id = oval_sysitem_get_id(sysitem); if (id != NULL) { oval_string_map_put(model->sysitem_map, id, sysitem); } } int oval_syschar_model_import_source(struct oval_syschar_model *model, struct oscap_source *source) { int ret = 0; /* setup context */ struct oval_parser_context context; context.reader = oscap_source_get_xmlTextReader(source); if (context.reader == NULL) { return -1; } context.definition_model = oval_syschar_model_get_definition_model(model); context.syschar_model = model; context.user_data = NULL; /* jump into oval_system_characteristics */ xmlTextReaderRead(context.reader); /* make sure this is syschar */ char *tagname = (char *)xmlTextReaderLocalName(context.reader); char *namespace = (char *)xmlTextReaderNamespaceUri(context.reader); int is_ovalsys = strcmp((const char *)OVAL_SYSCHAR_NAMESPACE, namespace) == 0; /* start parsing */ if (is_ovalsys && (strcmp(tagname, OVAL_ROOT_ELM_SYSCHARS) == 0)) { ret = oval_syschar_model_parse(context.reader, &context); } else { oscap_seterr(OSCAP_EFAMILY_OSCAP, "Missing \"oval_system_characteristics\" element"); dE("Unprocessed tag: <%s:%s>.\n", namespace, tagname); ret = -1; } oscap_free(tagname); oscap_free(namespace); xmlFreeTextReader(context.reader); return ret; } /* -1 error; 0 OK; 1 warning */ int oval_syschar_model_import(struct oval_syschar_model *model, const char *file) { __attribute__nonnull__(model); struct oscap_source *source = oscap_source_new_from_file(file); int ret = oval_syschar_model_import_source(model, source); oscap_source_free(source); return ret; } int oval_syschar_model_bind_variable_model(struct oval_syschar_model *sysmodel, struct oval_variable_model *varmodel) { __attribute__nonnull__(sysmodel); return oval_definition_model_bind_variable_model(sysmodel->definition_model, varmodel); } struct oval_syschar *oval_syschar_model_get_syschar(struct oval_syschar_model *model, const char *object_id) { __attribute__nonnull__(model); return (struct oval_syschar *)oval_smc_get_last(model->syschar_map, object_id); } struct oval_sysitem *oval_syschar_model_get_sysitem(struct oval_syschar_model *model, const char *id) { __attribute__nonnull__(model); return (struct oval_sysitem *)oval_string_map_get_value(model->sysitem_map, id); } struct oval_syschar *oval_syschar_model_get_new_syschar(struct oval_syschar_model *model, struct oval_object *object) { char *object_id = oval_object_get_id(object); struct oval_syschar *syschar = oval_syschar_model_get_syschar(model, object_id); if (syschar == NULL) { syschar = oval_syschar_new(model, object); } return syschar; } struct oval_sysitem *oval_syschar_model_get_new_sysitem(struct oval_syschar_model *model, const char *id) { struct oval_sysitem *sysitem = oval_syschar_model_get_sysitem(model, id); if (sysitem == NULL) { sysitem = oval_sysitem_new(model, id); } return sysitem; } xmlNode *oval_syschar_model_to_dom(struct oval_syschar_model * syschar_model, xmlDocPtr doc, xmlNode * parent, oval_syschar_resolver resolver, void *user_arg) { xmlNodePtr root_node = NULL; if (parent) { /* result file */ root_node = xmlNewTextChild(parent, NULL, BAD_CAST OVAL_ROOT_ELM_SYSCHARS, NULL); } else { /* system characteristics file, we are the root */ root_node = xmlNewNode(NULL, BAD_CAST OVAL_ROOT_ELM_SYSCHARS); xmlDocSetRootElement(doc, root_node); } xmlNewNsProp(root_node, lookup_xsi_ns(doc), BAD_CAST "schemaLocation", BAD_CAST syschar_model->schema); xmlNs *ns_common = xmlNewNs(root_node, OVAL_COMMON_NAMESPACE, BAD_CAST "oval"); xmlNs *ns_unix = xmlNewNs(root_node, OVAL_SYSCHAR_UNIX_NS, BAD_CAST "unix-sys"); xmlNs *ns_ind = xmlNewNs(root_node, OVAL_SYSCHAR_IND_NS, BAD_CAST "ind-sys"); xmlNs *ns_lin = xmlNewNs(root_node, OVAL_SYSCHAR_LIN_NS, BAD_CAST "lin-sys"); xmlNs *ns_syschar = xmlNewNs(root_node, OVAL_SYSCHAR_NAMESPACE, NULL); xmlSetNs(root_node, ns_common); xmlSetNs(root_node, ns_unix); xmlSetNs(root_node, ns_ind); xmlSetNs(root_node, ns_lin); xmlSetNs(root_node, ns_syschar); /* Always report the generator */ oval_generator_to_dom(syschar_model->generator, doc, root_node); /* Report sysinfo */ oval_sysinfo_to_dom(oval_syschar_model_get_sysinfo(syschar_model), doc, root_node); struct oval_smc *resolved_smc = NULL; struct oval_syschar_iterator *syschars = oval_syschar_model_get_syschars(syschar_model); if (resolver) { resolved_smc = oval_smc_new(); while (oval_syschar_iterator_has_more(syschars)) { struct oval_syschar *syschar = oval_syschar_iterator_next(syschars); if ((*resolver) (syschar, user_arg)) { oval_smc_put_last(resolved_smc, oval_syschar_get_id(syschar), syschar); } } oval_syschar_iterator_free(syschars); syschars = oval_syschar_iterator_new(resolved_smc); } struct oval_string_map *sysitem_map = oval_string_map_new(); if (oval_syschar_iterator_has_more(syschars)) { xmlNode *tag_objects = xmlNewTextChild(root_node, ns_syschar, BAD_CAST "collected_objects", NULL); while (oval_syschar_iterator_has_more(syschars)) { struct oval_syschar *syschar = oval_syschar_iterator_next(syschars); struct oval_object *object = oval_syschar_get_object(syschar); if (oval_syschar_get_flag(syschar) == SYSCHAR_FLAG_UNKNOWN /* Skip unneeded syschars */ || oval_object_get_base_obj(object)) /* Skip internal objects */ continue; oval_syschar_to_dom(syschar, doc, tag_objects); struct oval_sysitem_iterator *sysitems = oval_syschar_get_sysitem(syschar); while (oval_sysitem_iterator_has_more(sysitems)) { struct oval_sysitem *sysitem = oval_sysitem_iterator_next(sysitems); oval_string_map_put(sysitem_map, oval_sysitem_get_id(sysitem), sysitem); } oval_sysitem_iterator_free(sysitems); } } oval_smc_free0(resolved_smc); oval_syschar_iterator_free(syschars); struct oval_iterator *sysitems = oval_string_map_values(sysitem_map); if (oval_collection_iterator_has_more(sysitems)) { xmlNode *tag_items = xmlNewTextChild(root_node, ns_syschar, BAD_CAST "system_data", NULL); while (oval_collection_iterator_has_more(sysitems)) { struct oval_sysitem *sysitem = (struct oval_sysitem *) oval_collection_iterator_next(sysitems); oval_sysitem_to_dom(sysitem, doc, tag_items); } } oval_collection_iterator_free(sysitems); oval_string_map_free(sysitem_map, NULL); return root_node; } int oval_syschar_model_export(struct oval_syschar_model *model, const char *file) { __attribute__nonnull__(model); LIBXML_TEST_VERSION; xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0"); if (doc == NULL) { oscap_setxmlerr(xmlGetLastError()); return -1; } oval_syschar_model_to_dom(model, doc, NULL, NULL, NULL); return oscap_xml_save_filename_free(file, doc); }
33.410673
131
0.774167
[ "object", "model" ]
d2da67bd1a68189c1f76baff17c3a222af4f4248
359
h
C
Particles.h
Pro-Prietary/Defenduino
72999d3ba454733f95c7cd991d36ce7b9adcf65f
[ "BSD-3-Clause" ]
null
null
null
Particles.h
Pro-Prietary/Defenduino
72999d3ba454733f95c7cd991d36ce7b9adcf65f
[ "BSD-3-Clause" ]
null
null
null
Particles.h
Pro-Prietary/Defenduino
72999d3ba454733f95c7cd991d36ce7b9adcf65f
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include "GameObject.h" #define PARTICLES_EXPLOSION 0 #define PARTICLES_SPAWN 1 #define PARTICLES_SPAWN_BAITER 2 #define PARTICLES_PLAYER 3 #define PARTICLES_SPAWN_PLAYER 4 class Particles : public GameObject { public: void show(byte type); void update(); void render(Vector2Int cameraPos); private: byte distance; };
17.095238
36
0.743733
[ "render" ]
d2e369575762c64fc91cb452cc6e2aaaecf66d34
2,828
h
C
lib/quickflux/qfappdispatcher.h
denLaure/DictionaryTrainer
fc6d85e0b755eeca7870312653fd03e62447fffb
[ "MIT" ]
null
null
null
lib/quickflux/qfappdispatcher.h
denLaure/DictionaryTrainer
fc6d85e0b755eeca7870312653fd03e62447fffb
[ "MIT" ]
null
null
null
lib/quickflux/qfappdispatcher.h
denLaure/DictionaryTrainer
fc6d85e0b755eeca7870312653fd03e62447fffb
[ "MIT" ]
1
2019-07-04T09:24:16.000Z
2019-07-04T09:24:16.000Z
#ifndef QFAPPDISPATCHER_H #define QFAPPDISPATCHER_H #include <QObject> #include <QVariantMap> #include <QJSValue> #include <QQueue> #include <QPair> #include <QQmlEngine> #include <QPointer> #include "priv/qflistener.h" /// Message Dispatcher class QFAppDispatcher : public QObject { Q_OBJECT public: explicit QFAppDispatcher(QObject *parent = 0); ~QFAppDispatcher(); signals: /// Listeners should listen on this signal to get the latest dispatched message from AppDispatcher void dispatched(QString type,QJSValue message); public slots: /// Dispatch a message via Dispatcher /** @param type The type of the message @param message The message content @reentrant Dispatch a message with type via the AppDispatcher. Listeners should listen on the "dispatched" signal to be notified. Usually, it will emit "dispatched" signal immediately after calling dispatch(). However, if AppDispatcher is still dispatching messages, the new messages will be placed on a queue, and wait until it is finished. It guarantees the order of messages are arrived in sequence to listeners */ Q_INVOKABLE void dispatch(QString type,QJSValue message = QJSValue()); Q_INVOKABLE void waitFor(QList<int> ids); Q_INVOKABLE int addListener(QJSValue callback); Q_INVOKABLE void removeListener(int id); public: void dispatch(const QString& type, const QVariant& message); int addListener(QFListener* listener); /// Obtain the singleton instance of AppDispatcher for specific QQmlEngine static QFAppDispatcher* instance(QQmlEngine* engine); /// Obtain a singleton object from package for specific QQmlEngine static QObject* singletonObject(QQmlEngine* engine,QString package, int versionMajor, int versionMinor, QString typeName); QQmlEngine *engine() const; void setEngine(QQmlEngine *engine); private: void emitDispatched(QString type,QJSValue message); void invokeListeners(QList<int> ids); bool m_dispatching; QPointer<QQmlEngine> m_engine; // Queue for dispatching messages QQueue<QPair<QString,QJSValue > > m_queue; // Next id for listener. int nextListenerId; // Registered listener QMap<int, QPointer<QFListener> > m_listeners; // Current dispatching listener id int dispatchingListenerId; // Current dispatching message QJSValue dispatchingMessage; // Current dispatching message type QString dispatchingMessageType; // List of listeners pending to be invoked. QMap<int,bool> pendingListeners; // List of listeners blocked in waitFor() QMap<int,bool> waitingListeners; }; #endif // APPDISPATCHER_H
27.192308
102
0.702263
[ "object" ]
d2e9a42972256a8fc05121ab4aad52e3fe459229
7,195
h
C
PWGLF/NUCLEX/Hypernuclei/Vertexer2Body/AliVertexerHyperTriton2Body.h
eciesla/AliPhysics
a9a6dc33c8793ea999348c57cebbce445797e8e4
[ "BSD-3-Clause" ]
null
null
null
PWGLF/NUCLEX/Hypernuclei/Vertexer2Body/AliVertexerHyperTriton2Body.h
eciesla/AliPhysics
a9a6dc33c8793ea999348c57cebbce445797e8e4
[ "BSD-3-Clause" ]
null
null
null
PWGLF/NUCLEX/Hypernuclei/Vertexer2Body/AliVertexerHyperTriton2Body.h
eciesla/AliPhysics
a9a6dc33c8793ea999348c57cebbce445797e8e4
[ "BSD-3-Clause" ]
null
null
null
#ifndef AliVertexerHyperTriton2Body_H #define AliVertexerHyperTriton2Body_H #include <TNamed.h> #include <vector> #include <AliESDtrackCuts.h> #include <AliESDv0.h> class AliPIDResponse; class AliMCEvent; class AliVertexerHyperTriton2Body : public TNamed { public: AliVertexerHyperTriton2Body(); virtual ~AliVertexerHyperTriton2Body() {} void SetResetInitialPositions(Bool_t lOpt = kTRUE) { //Highly experimental, use with care! fkResetInitialPositions = lOpt; } void SetDoImprovedDCAV0DauPropagation(Bool_t lOpt = kTRUE) { //Highly experimental, use with care! fkDoImprovedDCAV0DauPropagation = lOpt; } void SetDoMaterialCorrections(Bool_t lOpt = kTRUE) { //Highly experimental, use with care! fkDoMaterialCorrection = lOpt; } void SetXYCase1Preoptimization(Bool_t lOpt = kTRUE) { //Highly experimental, use with care! fkXYCase1 = lOpt; } void SetXYCase2Preoptimization(Bool_t lOpt = kTRUE) { //Highly experimental, use with care! fkXYCase2 = lOpt; } void SetDoV0Refit(Bool_t lDoV0Refit = kTRUE) { fkDoV0Refit = lDoV0Refit; } //--------------------------------------------------------------------------------------- //Setters for the V0 Vertexer Parameters void SetV0VertexerMaxChisquare(Double_t lParameter) { fV0VertexerSels[0] = lParameter; } void SetV0VertexerDCAFirstToPV(Double_t lParameter) { fV0VertexerSels[1] = lParameter; } void SetV0VertexerDCASecondToPV(Double_t lParameter) { fV0VertexerSels[2] = lParameter; } void SetV0VertexerDCAV0Daughters(Double_t lParameter) { fV0VertexerSels[3] = lParameter; } void SetV0VertexerCosinePA(Double_t lParameter) { fV0VertexerSels[4] = lParameter; } void SetV0VertexerMinRadius(Double_t lParameter) { fV0VertexerSels[5] = lParameter; } void SetV0VertexerMaxRadius(Double_t lParameter) { fV0VertexerSels[6] = lParameter; } //--------------------------------------------------------------------------------------- void SetMinPtV0(Float_t lMinPt) { fMinPtV0 = lMinPt; } void SetMaxPtV0(Float_t lMaxPt) { fMaxPtV0 = lMaxPt; } //--------------------------------------------------------------------------------------- void SetUseImprovedFinding() { fkDoImprovedDCAV0DauPropagation = kTRUE; fkDoV0Refit = kTRUE; fkXYCase1 = kTRUE; fkXYCase2 = kTRUE; } //--------------------------------------------------------------------------------------- void SetUseDefaultFinding() { fkDoImprovedDCAV0DauPropagation = kFALSE; fkDoV0Refit = kFALSE; fkXYCase1 = kFALSE; fkXYCase2 = kFALSE; } //--------------------------------------------------------------------------------------- AliESDtrackCuts *SetPionTPCTrackCuts() { AliESDtrackCuts *esdTrackCuts = new AliESDtrackCuts; esdTrackCuts->SetMinNClustersTPC(50); esdTrackCuts->SetMaxChi2PerClusterTPC(4); esdTrackCuts->SetAcceptKinkDaughters(kFALSE); esdTrackCuts->SetMaxDCAToVertexZ(50); esdTrackCuts->SetMaxDCAToVertexXY(50); esdTrackCuts->SetDCAToVertex2D(kTRUE); return esdTrackCuts; } AliESDtrackCuts *SetHe3TPCTrackCuts() { AliESDtrackCuts *esdTrackCuts = new AliESDtrackCuts; esdTrackCuts->SetMinNClustersTPC(50); esdTrackCuts->SetMaxChi2PerClusterTPC(4); esdTrackCuts->SetAcceptKinkDaughters(kFALSE); esdTrackCuts->SetMaxDCAToVertexZ(8); esdTrackCuts->SetMaxDCAToVertexXY(8); esdTrackCuts->SetDCAToVertex2D(kTRUE); return esdTrackCuts; } //--------------------------------------------------------------------------------------- void SetUseMCAssociation(bool lAssoc = kTRUE) { fMC = lAssoc; } //--------------------------------------------------------------------------------------- //Functions for analysis Bookkeepinp // 1- Configure standard vertexing void SetupStandardVertexing(); void SetupLooseVertexing(); //--------------------------------------------------------------------------------------- //Re-vertex V0s void SelectTracks(AliESDEvent *event, std::vector<int> indices[2][2]); void SelectTracksMC(AliESDEvent *event, AliMCEvent *mcEvent, std::vector<int> indices[2][2]); std::vector<AliESDv0> Tracks2V0vertices(AliESDEvent *event, AliPIDResponse *pid, AliMCEvent *mcEvent = 0x0); //Helper functions Double_t Det(Double_t a00, Double_t a01, Double_t a10, Double_t a11) const; Double_t Det(Double_t a00, Double_t a01, Double_t a02, Double_t a10, Double_t a11, Double_t a12, Double_t a20, Double_t a21, Double_t a22) const; void Evaluate(const Double_t *h, Double_t t, Double_t r[3], //radius vector Double_t g[3], //first defivatives Double_t gg[3]); //second derivatives void CheckChargeV0(AliESDv0 *v0); //--------------------------------------------------------------------------------------- //Improved DCA V0 Dau Double_t GetDCAV0Dau(AliExternalTrackParam *pt, AliExternalTrackParam *nt, Double_t &xp, Double_t &xn, Double_t b, Double_t lNegMassForTracking = 0.139, Double_t lPosMassForTracking = 0.139); void GetHelixCenter(const AliExternalTrackParam *track, Double_t center[2], Double_t b); //--------------------------------------------------------------------------------------- Bool_t GetMonteCarloStatus(){ return fMC; } //---------------------------------------------------------------------------------------- AliESDtrackCuts *fHe3Cuts; //-> AliESDtrackCuts *fPiCuts; //-> private: bool fMC; Bool_t fkDoV0Refit; int fMaxIterationsWhenMinimizing; bool fkPreselectX; Bool_t fkXYCase1; //Circles-far-away case pre-optimization switch Bool_t fkXYCase2; //Circles-touch case pre-optimization switch (cowboy/sailor duality resolution) Bool_t fkResetInitialPositions; Bool_t fkDoImprovedDCAV0DauPropagation; Bool_t fkDoMaterialCorrection; //Replace AliExternalTrackParam::PropagateTo with AliTrackerBase::PropagateTrackTo Float_t fMinPtV0; //minimum pt above which we keep candidates in TTree output Float_t fMaxPtV0; //maximum pt below which we keep candidates in TTree output Double_t fMinXforXYtest; //min X allowed for XY-plane preopt test Double_t fV0VertexerSels[7]; // Array to store the 7 values for the different selections V0 related double fMagneticField; double fPrimaryVertexX; double fPrimaryVertexY; double fPrimaryVertexZ; AliPIDResponse *fPID; AliVertexerHyperTriton2Body(const AliVertexerHyperTriton2Body &); // not implemented AliVertexerHyperTriton2Body &operator=(const AliVertexerHyperTriton2Body &); // not implemented ClassDef(AliVertexerHyperTriton2Body, 2); //1: first implementation }; #endif
34.425837
195
0.589576
[ "vector" ]
d2ed6840758d0d915dbc8fc3130d89bcdcbb1d73
3,909
h
C
common/heap/monotone/ukvm/bucket_queue.h
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
4
2018-06-05T14:15:52.000Z
2022-02-08T05:14:23.000Z
common/heap/monotone/ukvm/bucket_queue.h
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
null
null
null
common/heap/monotone/ukvm/bucket_queue.h
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
1
2018-10-21T11:01:35.000Z
2018-10-21T11:01:35.000Z
#pragma once #include "common/base.h" #include "common/heap/ukvm/data.h" #include <vector> namespace heap { namespace monotone { namespace ukvm { // P - max priority // Memory -- O(N + P) // Add -- O(1) // DecV -- O(1) // IncV -- O(1) // Top -- O(1 + P / N) amortized // Pop -- O(1 + P / N) amortized class BucketQueue { public: static const unsigned not_in_queue = -1u; using TValue = unsigned; using TData = heap::ukvm::Data<TValue>; using TSelf = BucketQueue; protected: std::vector<unsigned> priority; std::vector<unsigned> position; std::vector<std::vector<unsigned>> queue; unsigned top_priority; unsigned size; public: void Reset(unsigned ukey_size) { priority.clear(); priority.resize(ukey_size, -1u); position.clear(); position.resize(ukey_size, -1u); queue.clear(); top_priority = 0; size = 0; } explicit BucketQueue(unsigned ukey_size) { Reset(ukey_size); } BucketQueue(const std::vector<unsigned>& v, bool skip_heap) { Reset(v.size()); priority = v; if (!skip_heap) { for (unsigned i = 0; i < v.size(); ++i) { unsigned p = v[i]; AdjustQueueSize(p); position[i] = queue[p].size(); queue[p].push_back(i); } size = v.size(); } } bool Empty() const { return size == 0; } unsigned Size() const { return size; } unsigned UKeySize() const { return unsigned(priority.size()); } bool InHeap(unsigned key) const { return position[key] != not_in_queue; } unsigned Get(unsigned key) const { return priority[key]; } const std::vector<TValue>& GetValues() const { return priority; } public: void AddNewKey(unsigned key, unsigned _priority, bool skip_heap = false) { assert(!InHeap(key)); AddNewKeyI(key, _priority, skip_heap); } void Set(unsigned key, unsigned new_priority) { if (InHeap(key)) SetI(key, new_priority); else AddNewKeyI(key, new_priority, false); } void DecreaseValue(unsigned key, unsigned new_priority) { Set(key, new_priority); } void DecreaseValueIfLess(unsigned key, unsigned new_priority) { if (new_priority < priority[key]) Set(key, new_priority); } void IncreaseValue(unsigned key, unsigned new_priority) { Set(key, new_priority); } void Add(const TData& x) { Set(x.key, x.value); } unsigned TopKey() { ShiftPriority(); return queue[top_priority].back(); } unsigned TopValue() { ShiftPriority(); return top_priority; } TData Top() { ShiftPriority(); return {queue[top_priority].back(), top_priority}; } void Pop() { DeleteKey(TopKey()); } unsigned ExtractKey() { unsigned key = TopKey(); DeleteKey(key); return key; } unsigned ExtractValue() { Pop(); return top_priority; } TData Extract() { TData t = Top(); Pop(); return t; } void DeleteKey(unsigned key) { DeleteI(key); position[key] = not_in_queue; } protected: void AdjustQueueSize(unsigned p) { if (queue.size() <= p) queue.resize(p + 1); } void ShiftPriority() { assert(!Empty()); for (; queue[top_priority].size() == 0;) ++top_priority; } void AddNewKeyI(unsigned key, unsigned p, bool skip_heap) { priority[key] = p; if (!skip_heap) { AdjustQueueSize(p); position[key] = queue[p].size(); queue[p].push_back(key); ++size; } } void SetI(unsigned key, unsigned new_priority) { if (priority[key] != new_priority) { DeleteI(key); AddNewKeyI(key, new_priority, false); } } void DeleteI(unsigned key) { unsigned pos = position[key]; assert(pos != not_in_queue); auto& qp = queue[priority[key]]; if (pos < qp.size() - 1) { qp[pos] = qp.back(); position[qp.back()] = pos; } qp.pop_back(); --size; } }; } // namespace ukvm } // namespace monotone } // namespace heap
22.465517
76
0.616526
[ "vector" ]
d2f07599811ad19cf4cad338acb5861a3b7bebf8
5,762
h
C
paddle/fluid/operators/sequence_ops/sequence_expand_as_op.h
zmxdream/Paddle
04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c
[ "Apache-2.0" ]
17,085
2016-11-18T06:40:52.000Z
2022-03-31T22:52:32.000Z
paddle/fluid/operators/sequence_ops/sequence_expand_as_op.h
zmxdream/Paddle
04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c
[ "Apache-2.0" ]
29,769
2016-11-18T06:35:22.000Z
2022-03-31T16:46:15.000Z
paddle/fluid/operators/sequence_ops/sequence_expand_as_op.h
zmxdream/Paddle
04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c
[ "Apache-2.0" ]
4,641
2016-11-18T07:43:33.000Z
2022-03-31T15:15:02.000Z
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <numeric> // std::iota #include <sstream> #include <vector> #include "glog/logging.h" #include "paddle/fluid/framework/op_registry.h" namespace paddle { namespace operators { template <typename DeviceContext, typename T> struct SequenceExpandAsFunctor { void operator()( const DeviceContext &ctx, const framework::LoDTensor &x, const framework::Vector<size_t> &ref_lod, /*expand referenced lod*/ framework::LoDTensor *out); }; template <typename DeviceContext, typename T> struct SequenceExpandAsGradFunctor { void operator()( const DeviceContext &ctx, const framework::LoDTensor &dout, const framework::Vector<size_t> &ref_lod, /*expand referenced lod*/ framework::LoDTensor *dx); }; template <typename T> struct SequenceExpandAsFunctor<platform::CPUDeviceContext, T> { void operator()( const platform::CPUDeviceContext &context, const framework::LoDTensor &x, const framework::Vector<size_t> &ref_lod, /*expand referenced lod*/ framework::LoDTensor *out) { int64_t height = x.dims()[0]; int64_t width = framework::product(x.dims()) / height; const T *in_data = x.data<T>(); T *out_data = out->mutable_data<T>(context.GetPlace()); for (int h_id = 0; h_id < height; ++h_id) { size_t span = ref_lod[h_id + 1] - ref_lod[h_id]; if (span == 0) continue; const T *src = in_data + h_id * width; for (int64_t w_id = 0; w_id < width; ++w_id) { T ele = src[w_id]; size_t offset = ref_lod[h_id] * width; for (size_t k = 0; k < span; ++k) { out_data[offset + k * width + w_id] = ele; } } } } }; template <typename DeviceContext, typename T> class SequenceExpandAsKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext &context) const override { auto *x = context.Input<framework::LoDTensor>("X"); auto *y = context.Input<framework::LoDTensor>("Y"); auto *out = context.Output<framework::LoDTensor>("Out"); PADDLE_ENFORCE_EQ( y->lod().empty(), false, platform::errors::InvalidArgument( "Input(Y) of SequenceExpandAsOp has wrong LoD information. " "Expected Y's lod is not empty, but received empty lod.")); auto &y_lod = y->lod(); PADDLE_ENFORCE_EQ(y_lod.size(), 1, platform::errors::InvalidArgument( "Input(Y) of SequenceExpandAsOp has wrong LoD " "information. Expected Y's lod level = 1, but " "received lod level = %d.", y_lod.size())); PADDLE_ENFORCE_GT(y_lod[0].size(), 1, platform::errors::InvalidArgument( "Input(Y) of SequenceExpandAsOp has wrong LoD " "information. Expected the size of Y's lod[0] > 1, " "but received lod[0].size = %d.", y_lod[0].size())); out->mutable_data<T>(context.GetPlace()); auto &dev_ctx = context.template device_context<DeviceContext>(); SequenceExpandAsFunctor<DeviceContext, T> seq_espand_functor; seq_espand_functor(dev_ctx, *x, y_lod[0], out); } }; /* *Given Grad(Out) * * Grad(Out).lod = [[0, 3, 6]] * Grad(Out).data = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6] * Then * Grad(X).data = [(0.1 + 0.2 + 0.3), (0.4 + 0.5 + 0.6)] * = [0.6, 1.5] * Grad(X).lod = Input(X).lod * * */ template <typename T> struct SequenceExpandAsGradFunctor<platform::CPUDeviceContext, T> { void operator()( const platform::CPUDeviceContext &context, const framework::LoDTensor &dout, const framework::Vector<size_t> &ref_lod, /*expand referenced lod*/ framework::LoDTensor *dx) { int64_t height = dx->dims()[0]; int64_t width = framework::product(dx->dims()) / height; const T *dout_data = dout.data<T>(); T *dx_data = dx->mutable_data<T>(context.GetPlace()); for (int64_t h_id = 0; h_id < height; ++h_id) { T *dst = dx_data + h_id * width; size_t span = ref_lod[h_id + 1] - ref_lod[h_id]; for (int64_t w_id = 0; w_id < width; ++w_id) { T result = 0; for (size_t k = 0; k < span; ++k) { size_t offset = (ref_lod[h_id] + k) * width; result += dout_data[offset + w_id]; } dst[w_id] = result; } } } }; template <typename DeviceContext, typename T> class SequenceExpandAsGradKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext &context) const override { auto *g_out = context.Input<framework::LoDTensor>(framework::GradVarName("Out")); auto *y = context.Input<framework::LoDTensor>("Y"); auto *g_x = context.Output<framework::LoDTensor>(framework::GradVarName("X")); g_x->mutable_data<T>(context.GetPlace()); SequenceExpandAsGradFunctor<DeviceContext, T> functor; functor(context.template device_context<DeviceContext>(), *g_out, y->lod()[0], g_x); } }; } // namespace operators } // namespace paddle
35.134146
79
0.625651
[ "vector" ]
d2f3cd8394b506ff17e60b6bf35e95a79dda360f
18,384
h
C
tools/fidl/fidlc/include/fidl/flat/types.h
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
[ "BSD-2-Clause" ]
210
2019-02-05T12:45:09.000Z
2022-03-28T07:59:06.000Z
tools/fidl/fidlc/include/fidl/flat/types.h
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
[ "BSD-2-Clause" ]
56
2021-06-03T03:16:25.000Z
2022-03-20T01:07:44.000Z
tools/fidl/fidlc/include/fidl/flat/types.h
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
[ "BSD-2-Clause" ]
73
2019-03-06T18:55:23.000Z
2022-03-26T12:04:51.000Z
// Copyright 2020 The Fuchsia 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 TOOLS_FIDL_FIDLC_INCLUDE_FIDL_FLAT_TYPES_H_ #define TOOLS_FIDL_FIDLC_INCLUDE_FIDL_FLAT_TYPES_H_ #include "name.h" #include "object.h" #include "values.h" namespace fidl { namespace flat { struct CreateInvocation; struct Decl; struct TypeDecl; struct Struct; class LibraryMediator; struct LayoutInvocation; struct TypeConstraints; struct Resource; class TypeTemplate; struct Type : public Object { virtual ~Type() {} enum struct Kind { kArray, kBox, kVector, kString, kHandle, // TODO(fxbug.dev/70247): Delete this kRequestHandle, kTransportSide, kPrimitive, kIdentifier, }; explicit Type(const Name& name, Kind kind, types::Nullability nullability) : name(name), kind(kind), nullability(nullability) {} const Name name; const Kind kind; // TODO(fxbug.dev/70247): This is temporarily not-const so that we can modify // any boxed structs' nullability to always be nullable, in order to share code // paths between the old and new syntax. types::Nullability nullability; // Returns the nominal resourceness of the type per the FTP-057 definition. // For IdentifierType, can only be called after the Decl has been compiled. types::Resourceness Resourceness() const; // Comparison helper object. class Comparison { public: Comparison() = default; template <class T> Comparison Compare(const T& a, const T& b) const { if (result_ != 0) return Comparison(result_); if (a < b) return Comparison(-1); if (b < a) return Comparison(1); return Comparison(0); } bool IsLessThan() const { return result_ < 0; } private: Comparison(int result) : result_(result) {} const int result_ = 0; }; bool operator<(const Type& other) const { if (kind != other.kind) return kind < other.kind; return Compare(other).IsLessThan(); } // Compare this object against 'other'. // It's guaranteed that this->kind == other.kind. // Return <0 if *this < other, ==0 if *this == other, and >0 if *this > other. // Derived types should override this, but also call this implementation. virtual Comparison Compare(const Type& other) const { assert(kind == other.kind); return Comparison().Compare(nullability, other.nullability); } // The old syntax's CreateInvocation contains both what would considered to be // layout arguments and constraints in the new syntax. These are applied to // the current type to produce a new type - this is the old syntax equivalent // of ApplyConstraints virtual bool ApplySomeLayoutParametersAndConstraints(const flat::LibraryMediator& lib, const CreateInvocation& create_invocation, const flat::TypeTemplate* layout, std::unique_ptr<Type>* out_type, LayoutInvocation* out_params) const = 0; // Apply the provided constraints to this type, returning the newly constrained // Type and recording the invocation inside resolved_args. // For types in the new syntax, we receive the unresolved TypeConstraints. // TODO(fxbug.dev/74193): We currently require a pointer to the calling TypeTemplate // for error reporting purposes, since all of the constraint related errors are // still tied to TypeTemplates. As we fully separate out the constraints and // layout parameter (TypeTemplate::Create) code, we'll be able to remove this // extraneous parameter. virtual bool ApplyConstraints(const flat::LibraryMediator& lib, const TypeConstraints& constraints, const flat::TypeTemplate* layout, std::unique_ptr<Type>* out_type, LayoutInvocation* out_params) const = 0; }; struct ArrayType final : public Type { ArrayType(const Name& name, const Type* element_type, const Size* element_count) : Type(name, Kind::kArray, types::Nullability::kNonnullable), element_type(element_type), element_count(element_count) {} const Type* element_type; const Size* element_count; std::any AcceptAny(VisitorAny* visitor) const override; Comparison Compare(const Type& other) const override { const auto& o = static_cast<const ArrayType&>(other); return Type::Compare(o) .Compare(element_count->value, o.element_count->value) .Compare(*element_type, *o.element_type); } bool ApplySomeLayoutParametersAndConstraints(const flat::LibraryMediator& lib, const CreateInvocation& create_invocation, const flat::TypeTemplate* layout, std::unique_ptr<Type>* out_type, LayoutInvocation* out_params) const override; bool ApplyConstraints(const flat::LibraryMediator& lib, const TypeConstraints& constraints, const flat::TypeTemplate* layout, std::unique_ptr<Type>* out_type, LayoutInvocation* out_params) const override; }; struct VectorBaseType { // "vector based" types share common code for determining the size and nullability. // This method provides the resolved size and nullability, so that specific implementations // only need to worry about setting the element type on out_args. // We can't abstract away only the element type resolution process, because not // all vector based type templates return a VectorType (the exception being StringTypeTemplate). static bool ResolveSizeAndNullability(const LibraryMediator& lib, const TypeConstraints& constraints, const TypeTemplate* layout, LayoutInvocation* out_params); const static Size kMaxSize; }; struct VectorType final : public Type, public VectorBaseType { VectorType(const Name& name, const Type* element_type) : Type(name, Kind::kVector, types::Nullability::kNonnullable), element_type(element_type), element_count(&kMaxSize) {} VectorType(const Name& name, const Type* element_type, const Size* element_count, types::Nullability nullability) : Type(name, Kind::kVector, nullability), element_type(element_type), element_count(element_count) {} const Type* element_type; const Size* element_count; std::any AcceptAny(VisitorAny* visitor) const override; Comparison Compare(const Type& other) const override { const auto& o = static_cast<const VectorType&>(other); return Type::Compare(o) .Compare(element_count->value, o.element_count->value) .Compare(*element_type, *o.element_type); } bool ApplySomeLayoutParametersAndConstraints(const flat::LibraryMediator& lib, const CreateInvocation& create_invocation, const flat::TypeTemplate* layout, std::unique_ptr<Type>* out_type, LayoutInvocation* out_params) const override; bool ApplyConstraints(const flat::LibraryMediator& lib, const TypeConstraints& constraints, const flat::TypeTemplate* layout, std::unique_ptr<Type>* out_type, LayoutInvocation* out_params) const override; }; struct StringType final : public Type, public VectorBaseType { explicit StringType(const Name& name) : Type(name, Kind::kString, types::Nullability::kNonnullable), max_size(&kMaxSize) {} StringType(const Name& name, const Size* max_size, types::Nullability nullability) : Type(name, Kind::kString, nullability), max_size(max_size) {} const Size* max_size; std::any AcceptAny(VisitorAny* visitor) const override; Comparison Compare(const Type& other) const override { const auto& o = static_cast<const StringType&>(other); return Type::Compare(o).Compare(max_size->value, o.max_size->value); } bool ApplySomeLayoutParametersAndConstraints(const flat::LibraryMediator& lib, const CreateInvocation& create_invocation, const flat::TypeTemplate* layout, std::unique_ptr<Type>* out_type, LayoutInvocation* out_params) const override; bool ApplyConstraints(const flat::LibraryMediator& lib, const TypeConstraints& constraints, const flat::TypeTemplate* layout, std::unique_ptr<Type>* out_type, LayoutInvocation* out_params) const override; }; struct HandleType final : public Type { HandleType(const Name& name, Resource* resource_decl) : Type(name, Kind::kHandle, types::Nullability::kNonnullable), resource_decl(resource_decl), // TODO(fxbug.dev/64629): When we are ready to create handle types, we // should have an object type (and/or subtype) determined and not require // these hardcoded defaults. // We need to allow setting a default obj_type in resource_definition // declarations rather than hard-coding. obj_type(static_cast<uint32_t>(types::HandleSubtype::kHandle)), subtype(types::HandleSubtype::kHandle), rights(&kSameRights) {} HandleType(const Name& name, Resource* resource_decl, uint32_t obj_type, types::HandleSubtype subtype, const HandleRights* rights, types::Nullability nullability) : Type(name, Kind::kHandle, nullability), resource_decl(resource_decl), obj_type(obj_type), subtype(subtype), rights(rights) {} Resource* resource_decl; const uint32_t obj_type; const types::HandleSubtype subtype; const HandleRights* rights; std::any AcceptAny(VisitorAny* visitor) const override; Comparison Compare(const Type& other) const override { const auto& other_handle_type = *static_cast<const HandleType*>(&other); auto rights_val = static_cast<const flat::NumericConstantValue<types::RightsWrappedType>*>(rights); auto other_rights_val = static_cast<const flat::NumericConstantValue<types::RightsWrappedType>*>( other_handle_type.rights); return Type::Compare(other_handle_type) .Compare(subtype, other_handle_type.subtype) .Compare(*rights_val, *other_rights_val); } bool ApplySomeLayoutParametersAndConstraints(const flat::LibraryMediator& lib, const CreateInvocation& create_invocation, const flat::TypeTemplate* layout, std::unique_ptr<Type>* out_type, LayoutInvocation* out_params) const override; bool ApplyConstraints(const flat::LibraryMediator& lib, const TypeConstraints& constraints, const flat::TypeTemplate* layout, std::unique_ptr<Type>* out_type, LayoutInvocation* out_params) const override; const static HandleRights kSameRights; }; struct PrimitiveType final : public Type { explicit PrimitiveType(const Name& name, types::PrimitiveSubtype subtype) : Type(name, Kind::kPrimitive, types::Nullability::kNonnullable), subtype(subtype) {} types::PrimitiveSubtype subtype; std::any AcceptAny(VisitorAny* visitor) const override; Comparison Compare(const Type& other) const override { const auto& o = static_cast<const PrimitiveType&>(other); return Type::Compare(o).Compare(subtype, o.subtype); } bool ApplySomeLayoutParametersAndConstraints(const flat::LibraryMediator& lib, const CreateInvocation& create_invocation, const flat::TypeTemplate* layout, std::unique_ptr<Type>* out_type, LayoutInvocation* out_params) const override; bool ApplyConstraints(const flat::LibraryMediator& lib, const TypeConstraints& constraints, const flat::TypeTemplate* layout, std::unique_ptr<Type>* out_type, LayoutInvocation* out_params) const override; private: static uint32_t SubtypeSize(types::PrimitiveSubtype subtype); }; struct IdentifierType final : public Type { IdentifierType(const Name& name, const TypeDecl* type_decl) : IdentifierType(name, type_decl, types::Nullability::kNonnullable) {} IdentifierType(const Name& name, const TypeDecl* type_decl, types::Nullability nullability) : Type(name, Kind::kIdentifier, nullability), type_decl(type_decl) {} const TypeDecl* type_decl; std::any AcceptAny(VisitorAny* visitor) const override; Comparison Compare(const Type& other) const override { const auto& o = static_cast<const IdentifierType&>(other); return Type::Compare(o).Compare(name, o.name); } bool ApplySomeLayoutParametersAndConstraints(const flat::LibraryMediator& lib, const CreateInvocation& create_invocation, const flat::TypeTemplate* layout, std::unique_ptr<Type>* out_type, LayoutInvocation* out_params) const override; bool ApplyConstraints(const flat::LibraryMediator& lib, const TypeConstraints& constraints, const flat::TypeTemplate* layout, std::unique_ptr<Type>* out_type, LayoutInvocation* out_params) const override; }; // TODO(fxbug.dev/70247): Delete this // TODO(fxbug.dev/43803) Add required and optional rights. struct RequestHandleType final : public Type { RequestHandleType(const Name& name, const IdentifierType* protocol_type) : RequestHandleType(name, protocol_type, types::Nullability::kNonnullable) {} RequestHandleType(const Name& name, const IdentifierType* protocol_type, types::Nullability nullability) : Type(name, Kind::kRequestHandle, nullability), protocol_type(protocol_type) {} const IdentifierType* protocol_type; std::any AcceptAny(VisitorAny* visitor) const override; Comparison Compare(const Type& other) const override { const auto& o = static_cast<const RequestHandleType&>(other); return Type::Compare(o).Compare(*protocol_type, *o.protocol_type); } bool ApplySomeLayoutParametersAndConstraints(const flat::LibraryMediator& lib, const CreateInvocation& create_invocation, const flat::TypeTemplate* layout, std::unique_ptr<Type>* out_type, LayoutInvocation* out_params) const override; bool ApplyConstraints(const flat::LibraryMediator& lib, const TypeConstraints& constraints, const flat::TypeTemplate* layout, std::unique_ptr<Type>* out_type, LayoutInvocation* out_params) const override; }; enum class TransportSide { kClient, kServer, }; struct TransportSideType final : public Type { TransportSideType(const Name& name, TransportSide end) : TransportSideType(name, nullptr, types::Nullability::kNonnullable, end) {} TransportSideType(const Name& name, const Decl* protocol_decl, types::Nullability nullability, TransportSide end) : Type(name, Kind::kTransportSide, nullability), protocol_decl(protocol_decl), end(end) {} const Decl* protocol_decl; const TransportSide end; std::any AcceptAny(VisitorAny* visitor) const override; Comparison Compare(const Type& other) const override { const auto& o = static_cast<const TransportSideType&>(other); return Type::Compare(o) .Compare(name, o.name) .Compare(end, o.end) .Compare(protocol_decl, o.protocol_decl); } bool ApplySomeLayoutParametersAndConstraints(const flat::LibraryMediator& lib, const CreateInvocation& create_invocation, const flat::TypeTemplate* layout, std::unique_ptr<Type>* out_type, LayoutInvocation* out_params) const override; bool ApplyConstraints(const flat::LibraryMediator& lib, const TypeConstraints& constraints, const flat::TypeTemplate* layout, std::unique_ptr<Type>* out_type, LayoutInvocation* out_params) const override; }; struct BoxType final : public Type { BoxType(const Name& name, const Type* boxed_type) : Type(name, Kind::kBox, types::Nullability::kNullable), boxed_type(boxed_type) {} const Type* boxed_type; std::any AcceptAny(VisitorAny* visitor) const override; Comparison Compare(const Type& other) const override { const auto& o = static_cast<const BoxType&>(other); return Type::Compare(o).Compare(name, o.name).Compare(boxed_type, o.boxed_type); } bool ApplySomeLayoutParametersAndConstraints(const flat::LibraryMediator& lib, const CreateInvocation& create_invocation, const flat::TypeTemplate* layout, std::unique_ptr<Type>* out_type, LayoutInvocation* out_params) const override; bool ApplyConstraints(const flat::LibraryMediator& lib, const TypeConstraints& constraints, const flat::TypeTemplate* layout, std::unique_ptr<Type>* out_type, LayoutInvocation* out_params) const override; }; } // namespace flat } // namespace fidl #endif // TOOLS_FIDL_FIDLC_INCLUDE_FIDL_FLAT_TYPES_H_
43.875895
98
0.645126
[ "object", "vector" ]
d2f76bf5a7f5b0e3a49f92a27abe2e6b1ec4a978
1,118
h
C
Documentation/Examples/Solvers/ODE/StaticODESolver-LorenzExample.h
grinisrit/tnl-dev
4403b2dca895e2c32636395d6f1c1210c7afcefd
[ "MIT" ]
null
null
null
Documentation/Examples/Solvers/ODE/StaticODESolver-LorenzExample.h
grinisrit/tnl-dev
4403b2dca895e2c32636395d6f1c1210c7afcefd
[ "MIT" ]
null
null
null
Documentation/Examples/Solvers/ODE/StaticODESolver-LorenzExample.h
grinisrit/tnl-dev
4403b2dca895e2c32636395d6f1c1210c7afcefd
[ "MIT" ]
null
null
null
#include <iostream> #include <TNL/Containers/StaticVector.h> #include <TNL/Solvers/ODE/StaticEuler.h> using Real = double; int main( int argc, char* argv[] ) { using Vector = TNL::Containers::StaticVector< 3, Real >; using ODESolver = TNL::Solvers::ODE::StaticEuler< Vector >; const Real final_t = 25.0; const Real tau = 0.001; const Real output_time_step = 0.01; const Real sigma = 10.0; const Real rho = 28.0; const Real beta = 8.0 / 3.0; ODESolver solver; solver.setTau( tau ); solver.setTime( 0.0 ); Vector u( 1.0, 2.0, 3.0 ); while( solver.getTime() < final_t ) { solver.setStopTime( TNL::min( solver.getTime() + output_time_step, final_t ) ); auto f = [=] ( const Real& t, const Real& tau, const Vector& u, Vector& fu ) { const Real& x = u[ 0 ]; const Real& y = u[ 1 ]; const Real& z = u[ 2 ]; fu[ 0 ] = sigma * (y - x ); fu[ 1 ] = rho * x - y - x * z; fu[ 2 ] = -beta * z + x * y; }; solver.solve( u, f ); std::cout << u[ 0 ] << " " << u[ 1 ] << " " << u[ 2 ] << std::endl; } }
30.216216
85
0.538462
[ "vector" ]
d2f79270983db2faab4eb44e1bc171f5b9bbc0c2
3,626
h
C
dev/cmake-3.5.1/Source/CPack/IFW/cmCPackIFWPackage.h
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
4
2016-03-30T14:31:52.000Z
2019-02-02T05:01:32.000Z
dev/cmake-3.5.1/Source/CPack/IFW/cmCPackIFWPackage.h
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
null
null
null
dev/cmake-3.5.1/Source/CPack/IFW/cmCPackIFWPackage.h
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
1
2020-11-04T04:56:50.000Z
2020-11-04T04:56:50.000Z
/*============================================================================ CMake - Cross Platform Makefile Generator Copyright 2000-2009 Kitware, Inc., Insight Software Consortium Distributed under the OSI-approved BSD License (the "License"); see accompanying file Copyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more information. ============================================================================*/ #ifndef cmCPackIFWPackage_h #define cmCPackIFWPackage_h #include <cmStandardIncludes.h> #include <cmGeneratedFileStream.h> class cmCPackComponent; class cmCPackComponentGroup; class cmCPackIFWInstaller; class cmCPackIFWGenerator; /** \class cmCPackIFWPackage * \brief A single component to be installed by CPack IFW generator */ class cmCPackIFWPackage { public: // Types enum CompareTypes { CompareNone = 0x0, CompareEqual = 0x1, CompareLess = 0x2, CompareLessOrEqual = 0x3, CompareGreater = 0x4, CompareGreaterOrEqual = 0x5 }; struct CompareStruct { CompareStruct(); unsigned int Type; std::string Value; }; struct DependenceStruct { DependenceStruct(); DependenceStruct(const std::string &dependence); std::string Name; CompareStruct Compare; std::string NameWithCompare() const; bool operator < (const DependenceStruct &other) const { return Name < other.Name; } }; public: // [Con|De]structor /** * Construct package */ cmCPackIFWPackage(); public: // Configuration /// Human-readable name of the component std::string DisplayName; /// Human-readable description of the component std::string Description; /// Version number of the component std::string Version; /// Date when this component version was released std::string ReleaseDate; /// Domain-like identification for this component std::string Name; /// File name of a script being loaded std::string Script; /// List of license agreements to be accepted by the installing user std::vector<std::string> Licenses; /// Priority of the component in the tree std::string SortingPriority; /// Set to true to preselect the component in the installer std::string Default; /// Set to true to hide the component from the installer std::string Virtual; /// Determines that the package must always be installed std::string ForcedInstallation; public: // Internal implementation const char* GetOption(const std::string& op) const; bool IsOn(const std::string& op) const; bool IsVersionLess(const char *version); bool IsVersionGreater(const char *version); bool IsVersionEqual(const char *version); std::string GetComponentName(cmCPackComponent *component); void DefaultConfiguration(); int ConfigureFromOptions(); int ConfigureFromComponent(cmCPackComponent *component); int ConfigureFromGroup(cmCPackComponentGroup *group); int ConfigureFromGroup(const std::string &groupName); void GeneratePackageFile(); // Pointer to generator cmCPackIFWGenerator* Generator; // Pointer to installer cmCPackIFWInstaller* Installer; // Collection of dependencies std::set<cmCPackIFWPackage*> Dependencies; // Collection of unresolved dependencies std::set<DependenceStruct*> AlienDependencies; // Patch to package directory std::string Directory; protected: void WriteGeneratedByToStrim(cmGeneratedFileStream& xout); }; #endif // cmCPackIFWPackage_h
25.535211
78
0.699393
[ "vector" ]
d2f7b243f75b1cfb55ae259b8bdd8886f83bf377
7,250
h
C
net/tapi/rtc/phoenix/src/axctl/objectsafeimpl.h
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
net/tapi/rtc/phoenix/src/axctl/objectsafeimpl.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
net/tapi/rtc/phoenix/src/axctl/objectsafeimpl.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#ifndef _OBJECT_SAFE_IMPL_H_ #define _OBJECT_SAFE_IMPL_H_ #include <atlcom.h> #include <atlwin.h> #include <atlctl.h> /*++ Copyright (c) 1999 Microsoft Corporation Module Name: ObjectSafeImpl.h Abstract: base class for object safety. basic implementation for IObjectSafety derive your control from this class if the control is safe for scripting on all the interfaces it exposes if you want to delegate IObjectSafety requests to the IObjectSafety interface of the aggrefate that supports the interface requested, have your derived class implement QIOnAggregate() --*/ class __declspec(novtable) CObjectSafeImpl : public IObjectSafety { public: CObjectSafeImpl() :m_dwSafety(0) {} // // we support INTERFACESAFE_FOR_UNTRUSTED_CALLER and INTERFACESAFE_FOR_UNTRUSTED_DATA // enum { SUPPORTED_SAFETY_OPTIONS = INTERFACESAFE_FOR_UNTRUSTED_CALLER | INTERFACESAFE_FOR_UNTRUSTED_DATA }; STDMETHOD(SetInterfaceSafetyOptions)(REFIID riid, DWORD dwOptionSetMask, DWORD dwEnabledOptions) { IUnknown *pNonDelegatingUnknown = NULL; // // any options requested that we do not support? // if ( (~SUPPORTED_SAFETY_OPTIONS & dwOptionSetMask) != 0 ) { return E_FAIL; } // // Is the interface exposed by one of the aggregated objects? // HRESULT hr = QIOnAggregates(riid, &pNonDelegatingUnknown); if (SUCCEEDED(hr)) { // // get IObjectSafety on non delegating unknown of the aggregated object // IObjectSafety *pAggrObjectSafety = NULL; hr = pNonDelegatingUnknown->QueryInterface(IID_IObjectSafety, (void**)&pAggrObjectSafety); pNonDelegatingUnknown->Release(); pNonDelegatingUnknown = NULL; if (SUCCEEDED(hr)) { // // the aggregate exposes IObjectSafety. use it to set the new // safety options // hr = pAggrObjectSafety->SetInterfaceSafetyOptions(riid, dwOptionSetMask, dwEnabledOptions); pAggrObjectSafety->Release(); pAggrObjectSafety = NULL; } } else { // // the interface requested is not requested by the object's // aggregates. see if the interface is supported at all // hr = InterfaceSupported(riid); if (SUCCEEDED(hr)) { // // the object supports the interface. Set safety options. // s_CritSection.Lock(); // // set the bits specified by the mask to the values specified by the values // m_dwSafety = (dwEnabledOptions & dwOptionSetMask) | (m_dwSafety & ~dwOptionSetMask); s_CritSection.Unlock(); } } return hr; } STDMETHOD(GetInterfaceSafetyOptions)(REFIID riid, DWORD *pdwSupportedOptions, DWORD *pdwEnabledOptions) { // // check caller's pointers // if ( IsBadWritePtr(pdwSupportedOptions, sizeof(DWORD)) || IsBadWritePtr(pdwEnabledOptions, sizeof(DWORD)) ) { return E_POINTER; } // // if we fail, at least return something meaningful. // *pdwSupportedOptions = 0; *pdwEnabledOptions = 0; IUnknown *pNonDelegatingUnknown = NULL; // // Is the interface exposed by one of the aggregated objects? // HRESULT hr = QIOnAggregates(riid, &pNonDelegatingUnknown); if (SUCCEEDED(hr)) { // // get IObjectSafety on non delegating unknown of the aggregated object // IObjectSafety *pAggrObjectSafety = NULL; hr = pNonDelegatingUnknown->QueryInterface(IID_IObjectSafety, (void**)&pAggrObjectSafety); pNonDelegatingUnknown->Release(); pNonDelegatingUnknown = NULL; if (SUCCEEDED(hr)) { // // the aggregate exposes IObjectSafety. use it to get the new // safety options // hr = pAggrObjectSafety->GetInterfaceSafetyOptions(riid, pdwSupportedOptions, pdwEnabledOptions); pAggrObjectSafety->Release(); pAggrObjectSafety = NULL; } } else { // // the interface requested is not requested by the object's // aggregates. see if the interface is supported at all // hr = InterfaceSupported(riid); if (SUCCEEDED(hr)) { // // the object supports the interface. get options // *pdwSupportedOptions = SUPPORTED_SAFETY_OPTIONS; s_CritSection.Lock(); *pdwEnabledOptions = m_dwSafety; s_CritSection.Unlock(); } } return hr; } private: DWORD m_dwSafety; // // thread safety // // this interface is not likely to be a performance bottleneck, // at the same time, having one critical section per object // is wasteful. so have a static critical section // static CComAutoCriticalSection s_CritSection; protected: // // return S_OK if the interface requested is exposed // by the object // HRESULT InterfaceSupported(REFIID riid) { void *pVoid = NULL; HRESULT hr = E_FAIL; // // does the object support requested interface // hr = QueryInterface(riid, &pVoid); if (SUCCEEDED(hr)) { // // don't need the interface itself, just wanted to see if // it is supported // ((IUnknown*)pVoid)->Release(); } return hr; } // // Implement in the derived class if you have any aggregates // // returns the non delegating IUnknown of the first (in the order of COMMAP) // aggregate that supports the iid requested // virtual HRESULT QIOnAggregates(REFIID riid, IUnknown **ppNonDelegatingUnknown) { return E_NOINTERFACE; } }; #endif // _OBJECT_SAFE_IMPL_H_
23.927393
108
0.509655
[ "object" ]
d2fa01d7304d1b892bf9447f29b1a2581039585f
6,277
h
C
src/chrono/motion_functions/ChFunction_Sequence.h
yangfengzzz/chrono
6abb679feef0e64ae1863268052624c581f876a8
[ "BSD-3-Clause" ]
null
null
null
src/chrono/motion_functions/ChFunction_Sequence.h
yangfengzzz/chrono
6abb679feef0e64ae1863268052624c581f876a8
[ "BSD-3-Clause" ]
null
null
null
src/chrono/motion_functions/ChFunction_Sequence.h
yangfengzzz/chrono
6abb679feef0e64ae1863268052624c581f876a8
[ "BSD-3-Clause" ]
null
null
null
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Alessandro Tasora, Radu Serban // ============================================================================= #ifndef CHFUNCT_SEQUENCE_H #define CHFUNCT_SEQUENCE_H #include "chrono/motion_functions/ChFunction_Base.h" #include <list> namespace chrono { /// @addtogroup chrono_functions /// @{ /// Node for the list of functions in a ChFunction_Sequence object. class ChApi ChFseqNode { public: std::shared_ptr<ChFunction> fx; double duration; double weight; double t_start; double t_end; double Iy; double Iydt; double Iydtdt; bool y_cont; bool ydt_cont; bool ydtdt_cont; void SetDuration(double mdur); void SetTend(double mt_end) { t_end = mt_end; if (t_end < t_start) t_end = t_start; duration = t_end - t_start; } ChFseqNode(); ChFseqNode(std::shared_ptr<ChFunction> myfx, double mdur); ChFseqNode(const ChFseqNode &other); ~ChFseqNode() {} /// Method to allow serialization of transient data to archives. void ArchiveOUT(ChArchiveOut &marchive); /// Method to allow de-serialization of transient data from archives. void ArchiveIN(ChArchiveIn &marchive); }; CH_CLASS_VERSION(ChFseqNode, 0) /// Sequence function: /// `y = sequence_of_functions(f1(y), f2(y), f3(y))` /// All other function types can be inserted into this. /// This function is very important because very complex motion /// laws can be created by sequencing many basic ChFunctions. class ChApi ChFunction_Sequence : public ChFunction { private: std::list<ChFseqNode> functions; ///< the list of sub functions double start; ///< start time for sequence public: ChFunction_Sequence() : start(0) {} ChFunction_Sequence(const ChFunction_Sequence &other); ~ChFunction_Sequence() {} /// "Virtual" copy constructor (covariant return type). virtual ChFunction_Sequence *Clone() const override { return new ChFunction_Sequence(*this); } virtual FunctionType Get_Type() const override { return FUNCT_SEQUENCE; } virtual double Get_y(double x) const override; virtual double Get_y_dx(double x) const override; virtual double Get_y_dxdx(double x) const override; /// The sequence of functions starts at this x value. void Set_start(double m_start) { start = m_start; } double Get_start() const { return start; } /// Access the list of the sub-functions. std::list<ChFseqNode> &Get_list() { return functions; } /// Scans all the seq.of functions and setup the timings and continuity /// offsets, to satisfy all constraints. /// This must be called whenever a new function is inserted, or its /// timing and continuity constraints are changed. void Setup(); /// Insert function after the fx with defined "position" index in list. /// - If index is higher than available objects, it simply goes to the end. /// - If index = 0 insert at the beginning, /// - If index = -1 insert at the end. /// Inserted functions will be deleted automatically when this object will be deleted. /// The fx segment has its own 'weight': use 1.0 for default, or different weights /// if you want that Get_weight() will give different results depending on the "x" parameter. /// Set c0=true if you want to force C0 continuity with previous function (an offset /// will be implicitly added to the function, as y=f(x)+Offset). Same for C1 and C2 continuity, /// using c1 and c2 flags. bool InsertFunct(std::shared_ptr<ChFunction> myfx, ///< the function to insert double duration, ///< duration of the time segment for this function double weight = 1, ///< optional weight scalar bool c0 = false, ///< impose continuity to previous f() by offsetting/slanting bool c1 = false, ///< impose continuity to previous f() by offsetting/slanting bool c2 = false, ///< impose continuity to previous f() by offsetting/slanting int position = -1 ///< position index, 0,1,2,3.. (if -1 insert at the end) ); /// Remove and deletes function with defined "position", and returns true. /// - If position = 0, removes always head (beginning), /// - If position = -1 removes tail (end). /// - If position > max number of current nodes, removes tail anyway, but returns false. bool KillFunct(int position); /// Returns the ChFunction with given "position". /// - If position = 0, returns always head (beginning), /// - If position = -1 returns tail (end). /// - If position > max number of current nodes, returns tail fx anyway. std::shared_ptr<ChFunction> GetNthFunction(int position); /// As above, but returns the function node (containing function pointer, /// function duration, continuity flags with previous node, etc.) ChFseqNode *GetNthNode(int position); /// As above, but returning duration. (return value is reference, so it /// can be also changed later, but remember Setup() for the /// ChFunction_Sequence after you modified this return value by reference ***TO DO***). /// If no function, returns 0. double GetNthDuration(int position); virtual double Get_weight(double x) const override; virtual void Estimate_x_range(double &xmin, double &xmax) const override; virtual int HandleNumber() const override; virtual bool HandleAccess(int handle_id, double mx, double my, bool set_mode) override; /// Method to allow serialization of transient data to archives. virtual void ArchiveOUT(ChArchiveOut &marchive) override; /// Method to allow de-serialization of transient data from archives. virtual void ArchiveIN(ChArchiveIn &marchive) override; }; /// @} chrono_functions } // end namespace chrono #endif
39.23125
114
0.667835
[ "object" ]
d2fbd0482a8eb41db4c73df07c61c3c2cc68d535
4,874
h
C
mcrouter/routes/MissFailoverRoute.h
hurricane1026/mcrouter
5f1c1ca2b9c5f61753f853b34104338e04dd9d50
[ "MIT" ]
null
null
null
mcrouter/routes/MissFailoverRoute.h
hurricane1026/mcrouter
5f1c1ca2b9c5f61753f853b34104338e04dd9d50
[ "MIT" ]
null
null
null
mcrouter/routes/MissFailoverRoute.h
hurricane1026/mcrouter
5f1c1ca2b9c5f61753f853b34104338e04dd9d50
[ "MIT" ]
null
null
null
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the LICENSE * file in the root directory of this source tree. */ #pragma once #include <memory> #include <string> #include <vector> #include <folly/dynamic.h> #include "mcrouter/McrouterFiberContext.h" #include "mcrouter/lib/McResUtil.h" #include "mcrouter/lib/Reply.h" #include "mcrouter/lib/RouteHandleTraverser.h" #include "mcrouter/lib/carbon/RoutingGroups.h" #include "mcrouter/lib/config/RouteHandleBuilder.h" #include "mcrouter/lib/config/RouteHandleFactory.h" #include "mcrouter/lib/routes/NullRoute.h" namespace facebook { namespace memcache { namespace mcrouter { /** * For get-like requests, sends the same request sequentially * to each destination in the list in order until the first hit reply. * If all replies result in errors/misses, returns the reply from the * last destination in the list. */ template <class RouterInfo> class MissFailoverRoute { private: using RouteHandleIf = typename RouterInfo::RouteHandleIf; public: explicit MissFailoverRoute( std::vector<std::shared_ptr<RouteHandleIf>> targets, bool returnBestOnError = false) : targets_(std::move(targets)), returnBestOnError_(returnBestOnError) { assert(targets_.size() > 1); } static std::string routeName() { return "miss-failover"; } template <class Request> void traverse( const Request& req, const RouteHandleTraverser<RouteHandleIf>& t) const { t(targets_, req); } template <class Request> ReplyT<Request> route(const Request& req, carbon::GetLikeT<Request> = 0) const { return routeImpl(req); } template <class Request> ReplyT<Request> route(const Request& req, carbon::DeleteLikeT<Request> = 0) const { return routeImpl(req); } template <class Request> ReplyT<Request> route( const Request& req, carbon::OtherThanT<Request, carbon::GetLike<>, carbon::DeleteLike<>> = 0) const { return targets_[0]->route(req); } private: const std::vector<std::shared_ptr<RouteHandleIf>> targets_; const bool returnBestOnError_; bool shouldFailover(const mc_res_t replyResult) const { return !isHitResult(replyResult) && (replyResult != mc_res_ok); } template <class Request> ReplyT<Request> routeImpl(const Request& req) const { auto reply = targets_[0]->route(req); if (!shouldFailover(reply.result())) { return reply; } // Failover return fiber_local<RouterInfo>::runWithLocals( [ this, &req, bestReply = std::move(reply) ]() mutable { fiber_local<RouterInfo>::addRequestClass(RequestClass::kFailover); for (size_t i = 1; i < targets_.size(); ++i) { auto failoverReply = targets_[i]->route(req); if (!shouldFailover(failoverReply.result())) { return failoverReply; } if (returnBestOnError_) { // Prefer returning a miss from a healthy host rather than // an error from the last broken host. if (!worseThan(failoverReply.result(), bestReply.result())) { // This reply is "better" than we already have. bestReply = std::move(failoverReply); } } else { // Return reply from the last host, no matter if it's broken. bestReply = std::move(failoverReply); } } return bestReply; }); } }; namespace detail { template <class RouterInfo> typename RouterInfo::RouteHandlePtr makeMissFailoverRoute( std::vector<typename RouterInfo::RouteHandlePtr> targets, bool returnBestOnError) { if (targets.empty()) { return createNullRoute<typename RouterInfo::RouteHandleIf>(); } if (targets.size() == 1) { return std::move(targets[0]); } return makeRouteHandleWithInfo<RouterInfo, MissFailoverRoute>( std::move(targets), returnBestOnError); } } // detail template <class RouterInfo> typename RouterInfo::RouteHandlePtr makeMissFailoverRoute( RouteHandleFactory<typename RouterInfo::RouteHandleIf>& factory, const folly::dynamic& json) { std::vector<typename RouterInfo::RouteHandlePtr> children; bool returnBestOnError = false; if (json.isObject()) { if (auto jChildren = json.get_ptr("children")) { children = factory.createList(*jChildren); } if (auto jReturnBest = json.get_ptr("return_best_on_error")) { checkLogic( jReturnBest->isBool(), "ModifyKeyRoute: return_best_on_error is not a bool"); returnBestOnError = jReturnBest->asBool(); } } else { children = factory.createList(json); } return detail::makeMissFailoverRoute<RouterInfo>( std::move(children), returnBestOnError); } } // mcrouter } // memcache } // facebook
29.361446
77
0.671728
[ "vector" ]
d2fe46f578cfd32a1e73cb3c5c118a13d0e2e1a7
6,341
h
C
crawl-ref/source/terrain.h
dplusplus/dcss-0.21-ja
51656602d6353e73464eca1639f22ee42903dfa4
[ "CC0-1.0" ]
1
2021-12-24T02:07:54.000Z
2021-12-24T02:07:54.000Z
crawl-ref/source/terrain.h
dplusplus/dcss-0.21-ja
51656602d6353e73464eca1639f22ee42903dfa4
[ "CC0-1.0" ]
null
null
null
crawl-ref/source/terrain.h
dplusplus/dcss-0.21-ja
51656602d6353e73464eca1639f22ee42903dfa4
[ "CC0-1.0" ]
null
null
null
/** * @file * @brief Terrain related functions. **/ #pragma once #include <memory> #include "command-type.h" #include "enum.h" #include "god-type.h" #include "terrain-change-type.h" class actor; struct coord_def; typedef FixedArray<bool, GXM, GYM> map_mask_boolean; // Precomputes slime wall neighbours for all squares on the map. Handy if // you need to make a lot of slime wall checks (such as for travel). class unwind_slime_wall_precomputer { public: unwind_slime_wall_precomputer(bool docompute = true); ~unwind_slime_wall_precomputer(); private: bool did_compute_mask; }; actor* actor_at(const coord_def& c); bool cell_is_solid(const coord_def &c); bool feat_is_malign_gateway_suitable(dungeon_feature_type feat); bool feat_is_wall(dungeon_feature_type feat); bool feat_is_opaque(dungeon_feature_type feat); bool feat_is_solid(dungeon_feature_type feat); bool feat_has_solid_floor(dungeon_feature_type feat); bool feat_has_dry_floor(dungeon_feature_type feat); bool feat_is_door(dungeon_feature_type feat); bool feat_is_closed_door(dungeon_feature_type feat); bool feat_is_sealed(dungeon_feature_type feat); bool feat_is_statuelike(dungeon_feature_type feat); bool feat_is_permarock(dungeon_feature_type feat); bool feat_is_endless(dungeon_feature_type feat); bool feat_can_wall_jump_against(dungeon_feature_type feat); bool feat_is_diggable(dungeon_feature_type feat); bool feat_is_stone_stair_down(dungeon_feature_type feat); bool feat_is_stone_stair_up(dungeon_feature_type feat); bool feat_is_stone_stair(dungeon_feature_type feat); bool feat_is_staircase(dungeon_feature_type feat); bool feat_is_escape_hatch(dungeon_feature_type feat); bool feat_is_trap(dungeon_feature_type feat, bool undiscovered_too = false); command_type feat_stair_direction(dungeon_feature_type feat); bool feat_is_portal(dungeon_feature_type feat); bool feat_is_tree(dungeon_feature_type feat); bool feat_is_metal(dungeon_feature_type feat); bool feat_is_stair(dungeon_feature_type feat); bool feat_is_travelable_stair(dungeon_feature_type feat); bool feat_is_gate(dungeon_feature_type feat); string feat_preposition(dungeon_feature_type feat, bool active = false, const actor* who = nullptr); string stair_climb_verb(dungeon_feature_type feat); bool feat_is_water(dungeon_feature_type feat); bool feat_is_watery(dungeon_feature_type feat); bool feat_is_lava(dungeon_feature_type feat); god_type feat_altar_god(dungeon_feature_type feat); dungeon_feature_type altar_for_god(god_type god); bool feat_is_altar(dungeon_feature_type feat); bool feat_is_player_altar(dungeon_feature_type grid); bool feat_is_branch_entrance(dungeon_feature_type feat); bool feat_is_branch_exit(dungeon_feature_type feat); bool feat_is_portal_entrance(dungeon_feature_type feat); bool feat_is_portal_exit(dungeon_feature_type feat); bool feat_is_bidirectional_portal(dungeon_feature_type feat); bool feat_is_fountain(dungeon_feature_type feat); bool feat_is_reachable_past(dungeon_feature_type feat); bool feat_is_critical(dungeon_feature_type feat); bool feat_is_valid_border(dungeon_feature_type feat); bool feat_is_mimicable(dungeon_feature_type feat, bool strict = true); bool feat_is_shaftable(dungeon_feature_type feat); int count_neighbours_with_func(const coord_def& c, bool (*checker)(dungeon_feature_type)); void find_connected_identical(const coord_def& d, set<coord_def>& out); coord_def get_random_stair(); bool slime_wall_neighbour(const coord_def& c); int count_adjacent_slime_walls(const coord_def &pos); void slime_wall_damage(actor* act, int delay); void get_door_description(int door_size, const char** adjective, const char** noun); void feat_splash_noise(dungeon_feature_type feat); bool feat_destroys_items(dungeon_feature_type feat); bool feat_eliminates_items(dungeon_feature_type feat); // Terrain changed under 'pos', perform necessary effects. void dungeon_terrain_changed(const coord_def &pos, dungeon_feature_type feat = DNGN_UNSEEN, bool preserve_features = false, bool preserve_items = false, bool temporary = false, bool wizmode = false); // Moves everything on the level at src to dst. void dgn_move_entities_at(coord_def src, coord_def dst, bool move_player, bool move_monster, bool move_items); bool swap_features(const coord_def &pos1, const coord_def &pos2, bool swap_everything = false, bool announce = true); bool slide_feature_over(const coord_def &src, coord_def preferred_dest = coord_def(-1, -1), bool announce = false); void fall_into_a_pool(dungeon_feature_type terrain); void init_feat_desc_cache(); dungeon_feature_type feat_by_desc(string desc); const char* feat_type_name(dungeon_feature_type feat); dungeon_feature_type dungeon_feature_by_name(const string &name); vector<string> dungeon_feature_matches(const string &name); const char *dungeon_feature_name(dungeon_feature_type rfeat); void destroy_wall(const coord_def& p); void set_terrain_changed(const coord_def c); bool cell_is_clingable(const coord_def pos); bool cell_can_cling_to(const coord_def& from, const coord_def to); bool is_boring_terrain(dungeon_feature_type feat); dungeon_feature_type orig_terrain(coord_def pos); void temp_change_terrain(coord_def pos, dungeon_feature_type newfeat, int dur, terrain_change_type type = TERRAIN_CHANGE_GENERIC, const monster* mon = nullptr); bool revert_terrain_change(coord_def pos, terrain_change_type ctype); bool is_temp_terrain(coord_def pos); bool plant_forbidden_at(const coord_def &p, bool connectivity_only = false); vector<coord_def> get_push_spaces(const coord_def& pos, bool push_actor, const vector<coord_def>* excluded); bool has_push_spaces(const coord_def& pos, bool push_actor, const vector<coord_def>* excluded); bool push_items_from(const coord_def& pos, const vector<coord_def>* excluded); coord_def push_actor_from(const coord_def& pos, const vector<coord_def>* excluded, bool random);
39.880503
96
0.774168
[ "vector" ]
9604c421dcb1d288590a789ef660291b9b88be2e
5,109
h
C
physx/include/PxFoundation.h
Toolchefs/PhysX
bf983b19f763698e41e10766482679c6e2278400
[ "BSD-3-Clause" ]
2,372
2018-12-20T18:01:39.000Z
2022-03-31T09:58:37.000Z
physx/include/PxFoundation.h
Toolchefs/PhysX
bf983b19f763698e41e10766482679c6e2278400
[ "BSD-3-Clause" ]
534
2018-12-20T20:04:42.000Z
2022-03-31T19:00:50.000Z
physx/include/PxFoundation.h
Toolchefs/PhysX
bf983b19f763698e41e10766482679c6e2278400
[ "BSD-3-Clause" ]
694
2018-12-20T18:32:36.000Z
2022-03-16T03:45:42.000Z
// // 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 NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''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. // // Copyright (c) 2008-2021 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PX_FOUNDATION_PX_FOUNDATION_H #define PX_FOUNDATION_PX_FOUNDATION_H /** \addtogroup foundation @{ */ #include "foundation/Px.h" #include "foundation/PxErrors.h" #include "foundation/PxFoundationConfig.h" #if !PX_DOXYGEN namespace physx { #endif /** \brief Foundation SDK singleton class. You need to have an instance of this class to instance the higher level SDKs. */ class PX_FOUNDATION_API PxFoundation { public: /** \brief Destroys the instance it is called on. The operation will fail, if there are still modules referencing the foundation object. Release all dependent modules prior to calling this method. @see PxCreateFoundation() */ virtual void release() = 0; /** retrieves error callback */ virtual PxErrorCallback& getErrorCallback() = 0; /** Sets mask of errors to report. */ virtual void setErrorLevel(PxErrorCode::Enum mask = PxErrorCode::eMASK_ALL) = 0; /** Retrieves mask of errors to be reported. */ virtual PxErrorCode::Enum getErrorLevel() const = 0; /** Retrieves the allocator this object was created with. */ virtual PxAllocatorCallback& getAllocatorCallback() = 0; /** Retrieves if allocation names are being passed to allocator callback. */ virtual bool getReportAllocationNames() const = 0; /** Set if allocation names are being passed to allocator callback. \details Enabled by default in debug and checked build, disabled by default in profile and release build. */ virtual void setReportAllocationNames(bool value) = 0; protected: virtual ~PxFoundation() { } }; #if !PX_DOXYGEN } // namespace physx #endif /** \brief Creates an instance of the foundation class The foundation class is needed to initialize higher level SDKs. There may be only one instance per process. Calling this method after an instance has been created already will result in an error message and NULL will be returned. \param version Version number we are expecting (should be #PX_PHYSICS_VERSION) \param allocator User supplied interface for allocating memory(see #PxAllocatorCallback) \param errorCallback User supplied interface for reporting errors and displaying messages(see #PxErrorCallback) \return Foundation instance on success, NULL if operation failed @see PxFoundation */ PX_C_EXPORT PX_FOUNDATION_API physx::PxFoundation* PX_CALL_CONV PxCreateFoundation(physx::PxU32 version, physx::PxAllocatorCallback& allocator, physx::PxErrorCallback& errorCallback); /** \brief Retrieves the Foundation SDK after it has been created. \note The behavior of this method is undefined if the foundation instance has not been created already. @see PxCreateFoundation() */ #if PX_CLANG #if PX_LINUX #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreturn-type-c-linkage" #endif // PX_LINUX #endif // PX_CLANG PX_C_EXPORT PX_FOUNDATION_API physx::PxFoundation& PX_CALL_CONV PxGetFoundation(); #if PX_CLANG #if PX_LINUX #pragma clang diagnostic pop #endif // PX_LINUX #endif // PX_CLANG namespace physx { class PxProfilerCallback; } /** \brief Get the callback that will be used for all profiling. */ PX_C_EXPORT PX_FOUNDATION_API physx::PxProfilerCallback* PX_CALL_CONV PxGetProfilerCallback(); /** \brief Set the callback that will be used for all profiling. */ PX_C_EXPORT PX_FOUNDATION_API void PX_CALL_CONV PxSetProfilerCallback(physx::PxProfilerCallback* profiler); /** @} */ #endif // PX_FOUNDATION_PX_FOUNDATION_H
31.93125
119
0.773537
[ "object" ]
960919679fb4c3cb2f9acbc5462a01070fc6cb06
340
h
C
ReeeEngine/src/ReeeEngine/Rendering/Renderables/Mesh.h
Lewisscrivens/ReeeEngine
abb31ef7e1adb553fafe02c4f9bd60ceb520acbf
[ "MIT" ]
null
null
null
ReeeEngine/src/ReeeEngine/Rendering/Renderables/Mesh.h
Lewisscrivens/ReeeEngine
abb31ef7e1adb553fafe02c4f9bd60ceb520acbf
[ "MIT" ]
null
null
null
ReeeEngine/src/ReeeEngine/Rendering/Renderables/Mesh.h
Lewisscrivens/ReeeEngine
abb31ef7e1adb553fafe02c4f9bd60ceb520acbf
[ "MIT" ]
null
null
null
#pragma once #include "Renderable.h" namespace ReeeEngine { /* A triangulated mesh that is loaded using the assimp loading library. */ class Mesh : public Renderable<Mesh> { public: /* Mesh constructor from a given file. */ Mesh(Graphics& graphics, const std::string& filePath, float importScale = 1.0f, bool lit = false); }; }
21.25
100
0.708824
[ "mesh" ]
960bd28252ce442d19578bd31a3f36c1556ef95e
7,283
h
C
third_party/mesa/src/chromium_gensrc/mesa/program/program_parse.tab.h
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
third_party/mesa/src/chromium_gensrc/mesa/program/program_parse.tab.h
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
third_party/mesa/src/chromium_gensrc/mesa/program/program_parse.tab.h
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
/* A Bison parser, made by GNU Bison 3.0.4. */ /* Bison interface for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2015 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ #ifndef YY__MESA_PROGRAM_PROGRAM_PROGRAM_PARSE_TAB_H_INCLUDED # define YY__MESA_PROGRAM_PROGRAM_PROGRAM_PARSE_TAB_H_INCLUDED /* Debug traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif #if YYDEBUG extern int _mesa_program_debug; #endif /* Token type. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE enum yytokentype { ARBvp_10 = 258, ARBfp_10 = 259, ADDRESS = 260, ALIAS = 261, ATTRIB = 262, OPTION = 263, OUTPUT = 264, PARAM = 265, TEMP = 266, END = 267, BIN_OP = 268, BINSC_OP = 269, SAMPLE_OP = 270, SCALAR_OP = 271, TRI_OP = 272, VECTOR_OP = 273, ARL = 274, KIL = 275, SWZ = 276, TXD_OP = 277, INTEGER = 278, REAL = 279, AMBIENT = 280, ATTENUATION = 281, BACK = 282, CLIP = 283, COLOR = 284, DEPTH = 285, DIFFUSE = 286, DIRECTION = 287, EMISSION = 288, ENV = 289, EYE = 290, FOG = 291, FOGCOORD = 292, FRAGMENT = 293, FRONT = 294, HALF = 295, INVERSE = 296, INVTRANS = 297, LIGHT = 298, LIGHTMODEL = 299, LIGHTPROD = 300, LOCAL = 301, MATERIAL = 302, MAT_PROGRAM = 303, MATRIX = 304, MATRIXINDEX = 305, MODELVIEW = 306, MVP = 307, NORMAL = 308, OBJECT = 309, PALETTE = 310, PARAMS = 311, PLANE = 312, POINT_TOK = 313, POINTSIZE = 314, POSITION = 315, PRIMARY = 316, PROGRAM = 317, PROJECTION = 318, RANGE = 319, RESULT = 320, ROW = 321, SCENECOLOR = 322, SECONDARY = 323, SHININESS = 324, SIZE_TOK = 325, SPECULAR = 326, SPOT = 327, STATE = 328, TEXCOORD = 329, TEXENV = 330, TEXGEN = 331, TEXGEN_Q = 332, TEXGEN_R = 333, TEXGEN_S = 334, TEXGEN_T = 335, TEXTURE = 336, TRANSPOSE = 337, TEXTURE_UNIT = 338, TEX_1D = 339, TEX_2D = 340, TEX_3D = 341, TEX_CUBE = 342, TEX_RECT = 343, TEX_SHADOW1D = 344, TEX_SHADOW2D = 345, TEX_SHADOWRECT = 346, TEX_ARRAY1D = 347, TEX_ARRAY2D = 348, TEX_ARRAYSHADOW1D = 349, TEX_ARRAYSHADOW2D = 350, VERTEX = 351, VTXATTRIB = 352, WEIGHT = 353, IDENTIFIER = 354, USED_IDENTIFIER = 355, MASK4 = 356, MASK3 = 357, MASK2 = 358, MASK1 = 359, SWIZZLE = 360, DOT_DOT = 361, DOT = 362 }; #endif /* Tokens. */ #define ARBvp_10 258 #define ARBfp_10 259 #define ADDRESS 260 #define ALIAS 261 #define ATTRIB 262 #define OPTION 263 #define OUTPUT 264 #define PARAM 265 #define TEMP 266 #define END 267 #define BIN_OP 268 #define BINSC_OP 269 #define SAMPLE_OP 270 #define SCALAR_OP 271 #define TRI_OP 272 #define VECTOR_OP 273 #define ARL 274 #define KIL 275 #define SWZ 276 #define TXD_OP 277 #define INTEGER 278 #define REAL 279 #define AMBIENT 280 #define ATTENUATION 281 #define BACK 282 #define CLIP 283 #define COLOR 284 #define DEPTH 285 #define DIFFUSE 286 #define DIRECTION 287 #define EMISSION 288 #define ENV 289 #define EYE 290 #define FOG 291 #define FOGCOORD 292 #define FRAGMENT 293 #define FRONT 294 #define HALF 295 #define INVERSE 296 #define INVTRANS 297 #define LIGHT 298 #define LIGHTMODEL 299 #define LIGHTPROD 300 #define LOCAL 301 #define MATERIAL 302 #define MAT_PROGRAM 303 #define MATRIX 304 #define MATRIXINDEX 305 #define MODELVIEW 306 #define MVP 307 #define NORMAL 308 #define OBJECT 309 #define PALETTE 310 #define PARAMS 311 #define PLANE 312 #define POINT_TOK 313 #define POINTSIZE 314 #define POSITION 315 #define PRIMARY 316 #define PROGRAM 317 #define PROJECTION 318 #define RANGE 319 #define RESULT 320 #define ROW 321 #define SCENECOLOR 322 #define SECONDARY 323 #define SHININESS 324 #define SIZE_TOK 325 #define SPECULAR 326 #define SPOT 327 #define STATE 328 #define TEXCOORD 329 #define TEXENV 330 #define TEXGEN 331 #define TEXGEN_Q 332 #define TEXGEN_R 333 #define TEXGEN_S 334 #define TEXGEN_T 335 #define TEXTURE 336 #define TRANSPOSE 337 #define TEXTURE_UNIT 338 #define TEX_1D 339 #define TEX_2D 340 #define TEX_3D 341 #define TEX_CUBE 342 #define TEX_RECT 343 #define TEX_SHADOW1D 344 #define TEX_SHADOW2D 345 #define TEX_SHADOWRECT 346 #define TEX_ARRAY1D 347 #define TEX_ARRAY2D 348 #define TEX_ARRAYSHADOW1D 349 #define TEX_ARRAYSHADOW2D 350 #define VERTEX 351 #define VTXATTRIB 352 #define WEIGHT 353 #define IDENTIFIER 354 #define USED_IDENTIFIER 355 #define MASK4 356 #define MASK3 357 #define MASK2 358 #define MASK1 359 #define SWIZZLE 360 #define DOT_DOT 361 #define DOT 362 /* Value type. */ #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED union YYSTYPE { #line 126 "program/program_parse.y" /* yacc.c:1909 */ struct asm_instruction *inst; struct asm_symbol *sym; struct asm_symbol temp_sym; struct asm_swizzle_mask swiz_mask; struct asm_src_register src_reg; struct prog_dst_register dst_reg; struct prog_instruction temp_inst; char *string; unsigned result; unsigned attrib; int integer; float real; gl_state_index state[STATE_LENGTH]; int negate; struct asm_vector vector; gl_inst_opcode opcode; struct { unsigned swz; unsigned rgba_valid:1; unsigned xyzw_valid:1; unsigned negate:1; } ext_swizzle; #line 294 "program/program_parse.tab.h" /* yacc.c:1909 */ }; typedef union YYSTYPE YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif /* Location type. */ #if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED typedef struct YYLTYPE YYLTYPE; struct YYLTYPE { int first_line; int first_column; int last_line; int last_column; }; # define YYLTYPE_IS_DECLARED 1 # define YYLTYPE_IS_TRIVIAL 1 #endif int _mesa_program_parse (struct asm_parser_state *state); #endif /* !YY__MESA_PROGRAM_PROGRAM_PROGRAM_PARSE_TAB_H_INCLUDED */
22.759375
76
0.703419
[ "object", "vector" ]
c554232e4d2efdec817ca8bd747d8993de1f748a
7,351
h
C
include/extensions/dmxext.h
sourcecode-reloaded/Xming
b9f2e99d00f9445a29803d622d24b5314ee35991
[ "X11", "MIT" ]
4
2020-08-21T04:21:14.000Z
2022-01-15T11:26:11.000Z
include/extensions/dmxext.h
sourcecode-reloaded/Xming
b9f2e99d00f9445a29803d622d24b5314ee35991
[ "X11", "MIT" ]
1
2020-02-23T19:22:52.000Z
2020-02-23T19:22:52.000Z
include/extensions/dmxext.h
talregev/Xming
e7a997e3c6441c572df6953468fd8e88ca9e07e7
[ "X11", "MIT" ]
3
2020-12-18T06:33:36.000Z
2022-02-22T16:25:50.000Z
/* $XFree86$ */ /* * Copyright 2002-2004 Red Hat Inc., Durham, North Carolina. * * 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 on the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NON-INFRINGEMENT. IN NO EVENT SHALL RED HAT AND/OR THEIR SUPPLIERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /* * Authors: * Rickard E. (Rik) Faith <faith@redhat.com> * */ /** \file * This file describes the interface to the client-side libdmx.a * library. All DMX-aware client-side applications should include this * file. */ #ifndef _DMXEXT_H_ #define _DMXEXT_H_ /* These values must be larger than LastExtensionError. The values in dmxext.h and dmxproto.h *MUST* match. */ #define DmxBadXinerama 1001 #define DmxBadValue 1002 #define DmxBadReply 1003 #define DMXScreenWindowWidth (1L<<0) #define DMXScreenWindowHeight (1L<<1) #define DMXScreenWindowXoffset (1L<<2) #define DMXScreenWindowYoffset (1L<<3) #define DMXRootWindowWidth (1L<<4) #define DMXRootWindowHeight (1L<<5) #define DMXRootWindowXoffset (1L<<6) #define DMXRootWindowYoffset (1L<<7) #define DMXRootWindowXorigin (1L<<8) #define DMXRootWindowYorigin (1L<<9) #define DMXDesktopWidth (1L<<0) #define DMXDesktopHeight (1L<<1) #define DMXDesktopShiftX (1L<<2) #define DMXDesktopShiftY (1L<<3) #define DMXInputType (1L<<0) #define DMXInputPhysicalScreen (1L<<1) #define DMXInputSendsCore (1L<<2) #ifndef _DMX_SERVER_ /** Client-library screen information structure, returned by * #DMXGetScreenAttributes. */ typedef struct { char *displayName; int logicalScreen; unsigned int screenWindowWidth; /* displayName's coordinate system */ unsigned int screenWindowHeight; /* displayName's coordinate system */ int screenWindowXoffset; /* displayName's coordinate system */ int screenWindowYoffset; /* displayName's coordinate system */ unsigned int rootWindowWidth; /* screenWindow's coordinate system */ unsigned int rootWindowHeight; /* screenWindow's coordinate system */ int rootWindowXoffset; /* screenWindow's coordinate system */ int rootWindowYoffset; /* screenWindow's coordinate system */ int rootWindowXorigin; /* global coordinate system */ int rootWindowYorigin; /* global coordinate system */ } DMXScreenAttributes; /** Client-library window information structure, returned by * #DMXGetWindowAttributes. */ typedef struct { int screen; Window window; XRectangle pos, vis; } DMXWindowAttributes; /** Client-library desktop information structure, returned by * #DMXGetDesktopAttributes. */ typedef struct { unsigned int width; /* global coordinate system */ unsigned int height; /* global coordinate system */ int shiftX; /* global coordinate system */ int shiftY; /* global coordinate system */ } DMXDesktopAttributes; /** Enumeration for the #inputType field in the #DMXInputAttributes * structure. */ typedef enum { DMXLocalInputType, DMXConsoleInputType, DMXBackendInputType } DMXInputEnum; /** Client-library input information structure, returned by * #DMXGetInputAttributes. */ typedef struct { DMXInputEnum inputType; int physicalScreen; int physicalId; Bool isCore; Bool sendsCore; const char *name; Bool detached; } DMXInputAttributes; _XFUNCPROTOBEGIN extern Bool DMXQueryExtension(Display *dpy, int *event_basep, int *error_basep); extern Bool DMXQueryVersion(Display *dpy, int *major_version, int *minor_version, int *patch_version); extern Bool DMXSync(Display *dpy); extern Bool DMXForceWindowCreation(Display *dpy, Window window); extern Bool DMXGetScreenCount(Display *dpy, int *screen_count); extern Bool DMXGetScreenAttributes(Display *dpy, int screen, DMXScreenAttributes *attr); extern int DMXChangeScreensAttributes(Display *dpy, int screen_count, int *screens, int mask_count, unsigned int *masks, DMXScreenAttributes *attr, /* vector */ int *error_screen); extern Bool DMXAddScreen(Display *dpy, const char *displayName, unsigned int mask, DMXScreenAttributes *attr, int *screen); extern Bool DMXRemoveScreen(Display *dpy, int screen); /* Call DMXGetScreenWindowCount and allocate info to that size. Pass * the size in available_count. This call can generate a large amount * of wire traffic and should not be used called with available_count=0 * just to determine the screen_count value -- use DMXGetScreenCount * instead. NOTE: Also see DMX protocol specification (DMXSpec.txt) for * usage of DMXSync to flush pending commands. */ extern Bool DMXGetWindowAttributes(Display *dpy, Window window, int *screen_count, int available_count, DMXWindowAttributes *attr); extern Bool DMXGetDesktopAttributes(Display *dpy, DMXDesktopAttributes *attr); extern int DMXChangeDesktopAttributes(Display *dpy, unsigned int mask, DMXDesktopAttributes *attr); extern Bool DMXGetInputCount(Display *dpy, int *input_count); extern Bool DMXGetInputAttributes(Display *dpy, int id, DMXInputAttributes *attr); extern Bool DMXAddInput(Display *dpy, unsigned int mask, DMXInputAttributes *attr, int *id); extern Bool DMXRemoveInput(Display *dpy, int id); /* These are helper functions that call DMXAddInput. */ extern Bool DMXAddBackendInput(Display *dpy, int screen, int sendsCore, int *newId); extern Bool DMXAddConsoleInput(Display *dpy, const char *name, int sendsCore, int *newId); _XFUNCPROTOEND #endif #endif
38.486911
78
0.649163
[ "vector" ]
c5572af1258e84803e40324cdb99e262c4387d96
3,084
h
C
source/MaterialXRuntime/RtNameResolver.h
muenstc/MaterialX
b8365086a738fddae683065d78f65410aacd0dc4
[ "BSD-3-Clause" ]
101
2017-08-08T12:08:01.000Z
2022-03-17T06:37:58.000Z
source/MaterialXRuntime/RtNameResolver.h
testpassword/MaterialX
7c69782196b11fa43c67aee0707801983bb81e6c
[ "BSD-3-Clause" ]
1,002
2018-01-09T10:33:07.000Z
2022-03-31T18:35:04.000Z
source/MaterialXRuntime/RtNameResolver.h
testpassword/MaterialX
7c69782196b11fa43c67aee0707801983bb81e6c
[ "BSD-3-Clause" ]
24
2018-01-05T20:16:36.000Z
2022-02-03T15:40:14.000Z
// // TM & (c) 2020 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd. // All rights reserved. See LICENSE.txt for license. // #ifndef MATERIALX_RTNAMERESOLVER_H #define MATERIALX_RTNAMERESOLVER_H #include <MaterialXRuntime/RtString.h> #include <MaterialXCore/Element.h> #include <memory> /// @file /// TODO: Docs namespace MaterialX { class PvtNameResolverRegistry; /// Shared pointer to an RtNameResolverRegistry using RtNameResolverRegistryPtr = std::shared_ptr<class RtNameResolverRegistry>; /// Function for resolving a given identifier of a given type typedef RtString (*RtNameResolverFunction)(const RtString& str, const RtString& type); /// @class RtNameResolverInfo /// /// \brief A structure containing information for custom name resolving /// to MaterialX or from MaterialX. /// /// In the structure it is possible to specify a function to call to perform /// identifier changes. Additionally it is possible to supply a set of identifier /// replacements. This is for both to and from MaterialX resolution. /// struct RtNameResolverInfo { /// Element type enumeration enum ElementType { FILENAME_TYPE, /// Filename element type GEOMNAME_TYPE /// Geometry element type }; RtNameResolverInfo() = default; RtString identifier {""}; /// Unique identifier for this information ElementType elementType; /// Type of element this resolver applies to RtNameResolverFunction toFunction; /// Resolver function to resolve to MaterialX. Can be null. RtNameResolverFunction fromFunction; /// Resolver function to resolve from MaterialX. Can be null. RtStringMap<RtString> toSubstitutions; /// Custom token substitutions to MaterialX. May be empty. RtStringMap<RtString> fromSubstitutions; /// Custom token substitutions from MaterialX. May be empty. }; /// @class RtNameResolverRegistry class RtNameResolverRegistry { public: /// Constructor static RtNameResolverRegistryPtr createNew(); /// \brief Registers a pair of string resolvers for resolving scene identifiers to/from MaterialX /// \param nameResolverContext Name resolution information void registerNameResolvers(RtNameResolverInfo& info); /// \brief Deregisters a named pair of string resolvers /// \param name The name given to the pair of identifiers to deregister void deregisterNameResolvers(const RtString& name); /// \brief Resolves the provided string. Any registered custom resolvers are applied to determine /// the final resolved value. The resolvers are applied in the order that they are registered. /// /// \param valueToResolve The value to resolve /// \param elementType The type of element to resolve /// \param toMaterialX Whether to convert to/from MaterialX RtString resolveIdentifier(const RtString& valueToResolve, const RtNameResolverInfo::ElementType elementType, bool toMaterialX = true) const; private: RtNameResolverRegistry(); friend class PvtNameResolverRegistry; std::unique_ptr<PvtNameResolverRegistry> _nameResolverRegistry; }; } #endif
35.045455
145
0.755188
[ "geometry" ]
c55ee7587b0840680c4315521580aef7bee05cf5
986
h
C
Game/ui/menuroot.h
mjaneczek/OpenGothic
383d8921e35d8e3b7479f6770fc07f73867b3bfd
[ "MIT" ]
null
null
null
Game/ui/menuroot.h
mjaneczek/OpenGothic
383d8921e35d8e3b7479f6770fc07f73867b3bfd
[ "MIT" ]
null
null
null
Game/ui/menuroot.h
mjaneczek/OpenGothic
383d8921e35d8e3b7479f6770fc07f73867b3bfd
[ "MIT" ]
null
null
null
#pragma once #include <Tempest/Widget> #include <daedalus/DaedalusVM.h> class Gothic; class GameMenu; class Npc; class MenuRoot : public Tempest::Widget { public: MenuRoot(Gothic& gothic); ~MenuRoot() override; void setMenu(const char* menu); void setMenu(GameMenu* w); void pushMenu(GameMenu* w); void popMenu(); void closeAll(); bool isActive() const; void setPlayer(const Npc& pl); void mouseWheelEvent(Tempest::MouseEvent& event) override; void keyDownEvent (Tempest::KeyEvent& event) override; void keyUpEvent (Tempest::KeyEvent& event) override; protected: void mouseDownEvent (Tempest::MouseEvent& event) override; void mouseUpEvent (Tempest::MouseEvent& event) override; private: Gothic& gothic; std::unique_ptr<Daedalus::DaedalusVM> vm; GameMenu* current=nullptr; std::vector<std::unique_ptr<GameMenu>> menuStack; };
26.648649
62
0.650101
[ "vector" ]
c5646481f6055686f14bd4cfa5770e8966a0537f
8,933
h
C
flatbuffers/cpp/index_generated.h
joseprupi/quantragrpc
48192a1d490596115252c2ad33e2dee4e2b215b5
[ "BSD-3-Clause" ]
null
null
null
flatbuffers/cpp/index_generated.h
joseprupi/quantragrpc
48192a1d490596115252c2ad33e2dee4e2b215b5
[ "BSD-3-Clause" ]
null
null
null
flatbuffers/cpp/index_generated.h
joseprupi/quantragrpc
48192a1d490596115252c2ad33e2dee4e2b215b5
[ "BSD-3-Clause" ]
null
null
null
// automatically generated by the FlatBuffers compiler, do not modify #ifndef FLATBUFFERS_GENERATED_INDEX_QUANTRA_H_ #define FLATBUFFERS_GENERATED_INDEX_QUANTRA_H_ #include "flatbuffers/flatbuffers.h" #include "enums_generated.h" namespace quantra { struct Fixing; struct FixingBuilder; struct Index; struct IndexBuilder; struct Fixing FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { typedef FixingBuilder Builder; enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { VT_DATE = 4, VT_RATE = 6 }; const flatbuffers::String *date() const { return GetPointer<const flatbuffers::String *>(VT_DATE); } float rate() const { return GetField<float>(VT_RATE, 0.0f); } bool Verify(flatbuffers::Verifier &verifier) const { return VerifyTableStart(verifier) && VerifyOffset(verifier, VT_DATE) && verifier.VerifyString(date()) && VerifyField<float>(verifier, VT_RATE) && verifier.EndTable(); } }; struct FixingBuilder { typedef Fixing Table; flatbuffers::FlatBufferBuilder &fbb_; flatbuffers::uoffset_t start_; void add_date(flatbuffers::Offset<flatbuffers::String> date) { fbb_.AddOffset(Fixing::VT_DATE, date); } void add_rate(float rate) { fbb_.AddElement<float>(Fixing::VT_RATE, rate, 0.0f); } explicit FixingBuilder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); } flatbuffers::Offset<Fixing> Finish() { const auto end = fbb_.EndTable(start_); auto o = flatbuffers::Offset<Fixing>(end); return o; } }; inline flatbuffers::Offset<Fixing> CreateFixing( flatbuffers::FlatBufferBuilder &_fbb, flatbuffers::Offset<flatbuffers::String> date = 0, float rate = 0.0f) { FixingBuilder builder_(_fbb); builder_.add_rate(rate); builder_.add_date(date); return builder_.Finish(); } inline flatbuffers::Offset<Fixing> CreateFixingDirect( flatbuffers::FlatBufferBuilder &_fbb, const char *date = nullptr, float rate = 0.0f) { auto date__ = date ? _fbb.CreateString(date) : 0; return quantra::CreateFixing( _fbb, date__, rate); } struct Index FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { typedef IndexBuilder Builder; enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { VT_PERIOD_NUMBER = 4, VT_PERIOD_TIME_UNIT = 6, VT_SETTLEMENT_DAYS = 8, VT_CALENDAR = 10, VT_BUSINESS_DAY_CONVENTION = 12, VT_END_OF_MONTH = 14, VT_DAY_COUNTER = 16, VT_FIXINGS = 18 }; int32_t period_number() const { return GetField<int32_t>(VT_PERIOD_NUMBER, 0); } quantra::enums::TimeUnit period_time_unit() const { return static_cast<quantra::enums::TimeUnit>(GetField<int8_t>(VT_PERIOD_TIME_UNIT, 0)); } int32_t settlement_days() const { return GetField<int32_t>(VT_SETTLEMENT_DAYS, 0); } quantra::enums::Calendar calendar() const { return static_cast<quantra::enums::Calendar>(GetField<int8_t>(VT_CALENDAR, 0)); } quantra::enums::BusinessDayConvention business_day_convention() const { return static_cast<quantra::enums::BusinessDayConvention>(GetField<int8_t>(VT_BUSINESS_DAY_CONVENTION, 0)); } bool end_of_month() const { return GetField<uint8_t>(VT_END_OF_MONTH, 0) != 0; } quantra::enums::DayCounter day_counter() const { return static_cast<quantra::enums::DayCounter>(GetField<int8_t>(VT_DAY_COUNTER, 0)); } const flatbuffers::Vector<flatbuffers::Offset<quantra::Fixing>> *fixings() const { return GetPointer<const flatbuffers::Vector<flatbuffers::Offset<quantra::Fixing>> *>(VT_FIXINGS); } bool Verify(flatbuffers::Verifier &verifier) const { return VerifyTableStart(verifier) && VerifyField<int32_t>(verifier, VT_PERIOD_NUMBER) && VerifyField<int8_t>(verifier, VT_PERIOD_TIME_UNIT) && VerifyField<int32_t>(verifier, VT_SETTLEMENT_DAYS) && VerifyField<int8_t>(verifier, VT_CALENDAR) && VerifyField<int8_t>(verifier, VT_BUSINESS_DAY_CONVENTION) && VerifyField<uint8_t>(verifier, VT_END_OF_MONTH) && VerifyField<int8_t>(verifier, VT_DAY_COUNTER) && VerifyOffset(verifier, VT_FIXINGS) && verifier.VerifyVector(fixings()) && verifier.VerifyVectorOfTables(fixings()) && verifier.EndTable(); } }; struct IndexBuilder { typedef Index Table; flatbuffers::FlatBufferBuilder &fbb_; flatbuffers::uoffset_t start_; void add_period_number(int32_t period_number) { fbb_.AddElement<int32_t>(Index::VT_PERIOD_NUMBER, period_number, 0); } void add_period_time_unit(quantra::enums::TimeUnit period_time_unit) { fbb_.AddElement<int8_t>(Index::VT_PERIOD_TIME_UNIT, static_cast<int8_t>(period_time_unit), 0); } void add_settlement_days(int32_t settlement_days) { fbb_.AddElement<int32_t>(Index::VT_SETTLEMENT_DAYS, settlement_days, 0); } void add_calendar(quantra::enums::Calendar calendar) { fbb_.AddElement<int8_t>(Index::VT_CALENDAR, static_cast<int8_t>(calendar), 0); } void add_business_day_convention(quantra::enums::BusinessDayConvention business_day_convention) { fbb_.AddElement<int8_t>(Index::VT_BUSINESS_DAY_CONVENTION, static_cast<int8_t>(business_day_convention), 0); } void add_end_of_month(bool end_of_month) { fbb_.AddElement<uint8_t>(Index::VT_END_OF_MONTH, static_cast<uint8_t>(end_of_month), 0); } void add_day_counter(quantra::enums::DayCounter day_counter) { fbb_.AddElement<int8_t>(Index::VT_DAY_COUNTER, static_cast<int8_t>(day_counter), 0); } void add_fixings(flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<quantra::Fixing>>> fixings) { fbb_.AddOffset(Index::VT_FIXINGS, fixings); } explicit IndexBuilder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); } flatbuffers::Offset<Index> Finish() { const auto end = fbb_.EndTable(start_); auto o = flatbuffers::Offset<Index>(end); return o; } }; inline flatbuffers::Offset<Index> CreateIndex( flatbuffers::FlatBufferBuilder &_fbb, int32_t period_number = 0, quantra::enums::TimeUnit period_time_unit = quantra::enums::TimeUnit_Days, int32_t settlement_days = 0, quantra::enums::Calendar calendar = quantra::enums::Calendar_Argentina, quantra::enums::BusinessDayConvention business_day_convention = quantra::enums::BusinessDayConvention_Following, bool end_of_month = false, quantra::enums::DayCounter day_counter = quantra::enums::DayCounter_Actual360, flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<quantra::Fixing>>> fixings = 0) { IndexBuilder builder_(_fbb); builder_.add_fixings(fixings); builder_.add_settlement_days(settlement_days); builder_.add_period_number(period_number); builder_.add_day_counter(day_counter); builder_.add_end_of_month(end_of_month); builder_.add_business_day_convention(business_day_convention); builder_.add_calendar(calendar); builder_.add_period_time_unit(period_time_unit); return builder_.Finish(); } inline flatbuffers::Offset<Index> CreateIndexDirect( flatbuffers::FlatBufferBuilder &_fbb, int32_t period_number = 0, quantra::enums::TimeUnit period_time_unit = quantra::enums::TimeUnit_Days, int32_t settlement_days = 0, quantra::enums::Calendar calendar = quantra::enums::Calendar_Argentina, quantra::enums::BusinessDayConvention business_day_convention = quantra::enums::BusinessDayConvention_Following, bool end_of_month = false, quantra::enums::DayCounter day_counter = quantra::enums::DayCounter_Actual360, const std::vector<flatbuffers::Offset<quantra::Fixing>> *fixings = nullptr) { auto fixings__ = fixings ? _fbb.CreateVector<flatbuffers::Offset<quantra::Fixing>>(*fixings) : 0; return quantra::CreateIndex( _fbb, period_number, period_time_unit, settlement_days, calendar, business_day_convention, end_of_month, day_counter, fixings__); } inline const quantra::Index *GetIndex(const void *buf) { return flatbuffers::GetRoot<quantra::Index>(buf); } inline const quantra::Index *GetSizePrefixedIndex(const void *buf) { return flatbuffers::GetSizePrefixedRoot<quantra::Index>(buf); } inline bool VerifyIndexBuffer( flatbuffers::Verifier &verifier) { return verifier.VerifyBuffer<quantra::Index>(nullptr); } inline bool VerifySizePrefixedIndexBuffer( flatbuffers::Verifier &verifier) { return verifier.VerifySizePrefixedBuffer<quantra::Index>(nullptr); } inline void FinishIndexBuffer( flatbuffers::FlatBufferBuilder &fbb, flatbuffers::Offset<quantra::Index> root) { fbb.Finish(root); } inline void FinishSizePrefixedIndexBuffer( flatbuffers::FlatBufferBuilder &fbb, flatbuffers::Offset<quantra::Index> root) { fbb.FinishSizePrefixed(root); } } // namespace quantra #endif // FLATBUFFERS_GENERATED_INDEX_QUANTRA_H_
35.589641
116
0.735251
[ "vector" ]
c56509841063644985b0641da7b94361306e9528
3,508
h
C
build/fuchsia/pkg/lib/vfs/cpp/pseudo_dir.h
chinmaygarde/buildroot
6b69caa4c7a04b6e81709bedd52297f29c2b1a14
[ "BSD-3-Clause" ]
1
2020-12-04T02:06:21.000Z
2020-12-04T02:06:21.000Z
build/fuchsia/pkg/lib/vfs/cpp/pseudo_dir.h
mdempsky/flutter_buildroot
765b0ea58a095374a73943ad78471b915c2d63e1
[ "BSD-3-Clause" ]
null
null
null
build/fuchsia/pkg/lib/vfs/cpp/pseudo_dir.h
mdempsky/flutter_buildroot
765b0ea58a095374a73943ad78471b915c2d63e1
[ "BSD-3-Clause" ]
1
2019-08-26T02:16:11.000Z
2019-08-26T02:16:11.000Z
// Copyright 2019 The Fuchsia 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_VFS_CPP_PSEUDO_DIR_H_ #define LIB_VFS_CPP_PSEUDO_DIR_H_ #include <lib/vfs/cpp/directory.h> #include <map> #include <mutex> namespace vfs { // A pseudo-directory is a directory-like object whose entries are constructed // by a program at runtime. The client can lookup, enumerate, and watch(not yet // implemented) these directory entries but it cannot create, remove, or rename // them. // // Instances of this class are thread-safe. class PseudoDir : public Directory { public: // Creates a directory which is initially empty. PseudoDir(); // Destroys the directory and releases the nodes it contains. ~PseudoDir() override; // Adds a directory entry associating the given |name| with |vn|. // It is ok to add the same Node multiple times with different names. // // Returns |ZX_OK| on success. // Returns |ZX_ERR_ALREADY_EXISTS| if there is already a node with the given // name. zx_status_t AddSharedEntry(std::string name, std::shared_ptr<Node> vn); // Adds a directory entry associating the given |name| with |vn|. // // Returns |ZX_OK| on success. // Returns |ZX_ERR_ALREADY_EXISTS| if there is already a node with the given // name. zx_status_t AddEntry(std::string name, std::unique_ptr<Node> vn); // Removes a directory entry with the given |name|. // // Returns |ZX_OK| on success. // Returns |ZX_ERR_NOT_FOUND| if there is no node with the given name. zx_status_t RemoveEntry(const std::string& name); // Removes all directory entries. void RemoveAllEntries(); // Checks if directory is empty. // Be careful while using this function if using this Dir in multiple // threads. bool IsEmpty() const; // |Directory| implementation: zx_status_t Lookup(const std::string& name, Node** out_node) const final; // |Node| implementations: zx_status_t GetAttr( fuchsia::io::NodeAttributes* out_attributes) const override; zx_status_t Readdir(uint64_t offset, void* data, uint64_t len, uint64_t* out_offset, uint64_t* out_actual) override; private: class Entry { public: Entry(uint64_t id, std::string name); virtual ~Entry(); uint64_t id() const { return id_; } const std::string& name() const { return name_; } virtual Node* node() const = 0; private: uint64_t const id_; std::string name_; }; class SharedEntry : public Entry { public: SharedEntry(uint64_t id, std::string name, std::shared_ptr<Node> node); ~SharedEntry() override; Node* node() const override; private: std::shared_ptr<Node> node_; }; class UniqueEntry : public Entry { public: UniqueEntry(uint64_t id, std::string name, std::unique_ptr<Node> node); ~UniqueEntry() override; Node* node() const override; private: std::unique_ptr<Node> node_; }; zx_status_t AddEntry(std::unique_ptr<Entry> entry); static constexpr uint64_t kDotId = 1u; mutable std::mutex mutex_; std::atomic_uint16_t next_node_id_ = {kDotId + 1}; // for enumeration std::map<uint64_t, std::unique_ptr<Entry>> entries_by_id_ __TA_GUARDED(mutex_); // for lookup std::map<std::string, Entry*> entries_by_name_ __TA_GUARDED(mutex_); }; } // namespace vfs #endif // LIB_VFS_CPP_PSEUDO_DIR_H_
27.84127
80
0.689282
[ "object" ]
c56d20a7de1e4d1d37817f3d17305041b5372c37
4,295
h
C
headers/chap01/test_framework.h
ClazyChen/ds-lab
d7ce031bb1e22230be5687ac848e897a6d589ddf
[ "MIT" ]
4
2022-03-12T14:42:21.000Z
2022-03-30T02:09:55.000Z
headers/chap01/test_framework.h
ClazyChen/ds-lab
d7ce031bb1e22230be5687ac848e897a6d589ddf
[ "MIT" ]
null
null
null
headers/chap01/test_framework.h
ClazyChen/ds-lab
d7ce031bb1e22230be5687ac848e897a6d589ddf
[ "MIT" ]
1
2022-03-29T18:17:55.000Z
2022-03-29T18:17:55.000Z
#pragma once // 这个文件提供了一个测试用的框架 // 它用来生成对比测试的一组实例 #include "framework.h" namespace clazy_framework { // 统计执行函数f需要的时间 // 这里采用了chrono库,可以更好的控制时间,达到微秒级 // 当返回的值非常小时,可以认为是没有执行时间,不应该进行比较 // 因为这个时候可能会受到系统的影响 double calculateTime(function<void()> f) { auto start = chrono::high_resolution_clock::now(); f(); auto end = chrono::high_resolution_clock::now(); return chrono::duration_cast<chrono::microseconds>(end - start).count() / 1e6; } // BaseClass:问题的基类(构造函数不需要参数) // DerivedClass:需要对比测试的子类 // 生成一组DerivedClass的实例,用于对比测试 template <typename BaseClass, typename... DerivedClass> requires (is_base_of_v<Object, BaseClass> && (is_base_of_v<BaseClass, DerivedClass> && ...)) class TestFramework : public Object { private: // 删除了拷贝构造函数、移动构造函数以及相应的赋值运算符 TestFramework(const TestFramework<BaseClass, DerivedClass...>&) = delete; TestFramework(TestFramework<BaseClass, DerivedClass...>&&) = delete; TestFramework<BaseClass, DerivedClass...>& operator=(const TestFramework<BaseClass, DerivedClass...>&) = delete; TestFramework<BaseClass, DerivedClass...>& operator=(TestFramework<BaseClass, DerivedClass...>&&) = delete; public: vector<shared_ptr<BaseClass>> instances; private: // 默认的实例类型名输出宽度 constexpr static int defaultWidth = 20; int instanceNameWidth() const { int width = defaultWidth; for (auto& instance : instances) { width = max(width, (int)instance->getTypeName().size()); } return width; } // 输出测试结果 void printResult(function<void(shared_ptr<BaseClass>&)> f) { for (auto& instance : instances) { int width = instanceNameWidth(); cout << "TEST [" << setw(width) << instance->getTypeName() << "] \t"; // 输出实例类型名 double seconds = calculateTime([&] { f(instance); }); cout << " (" << fixed << setprecision(6) << seconds << "s)" << endl; // 输出测试所需时间 } } public: // 在构造函数中,初始化一组实例(至少需要含有1个实例) // 这里采用了不定参数的一个遍历形式 // 通过生成一个伪数组,保证push_back行为是被正确执行的 TestFramework() : instances{make_shared<DerivedClass>()...} { if constexpr (sizeof...(DerivedClass) == 0) { instances.push_back(make_shared<BaseClass>()); } } // 重置所有的实例 void clear() { for (auto& instance : instances) { instance->clear(); } } // 用给定的参数调用所有的实例的某个函数 void invoke(function<void(BaseClass*)> f) { for (auto& instance : instances) { f(instance.get()); } } // 用给定的参数对所有实例进行测试 // 这里存在两种情况: // 1. 各个测试实例运行过程中不会改动参数,如查找 // 此时不需要制作参数的副本,可以直接调用 // 2. 各个测试实例运行过程中会改动参数,如排序 // 此时每次调用实例的时候,需要制作参数的副本 // 这两种情况的区分,通过检查BaseClass的调用方法中,接受的是否是值(或const引用)还是普通引用 // 从另一个维度,也可以分成两种情况 // 1. 实例调用后没有返回值,此时只需要报告所用时间即可 // 2. 实例调用后存在返回值,此时除了报告所用时间,还需要报告返回值 template <typename... Args> void test(const Args&... args) { constexpr bool directInvoke = is_invocable_v<BaseClass, Args...>; constexpr bool referenceInvoke = is_invocable_v<BaseClass, Args&...>; constexpr bool procedureInvoke = is_same_v<void, invoke_result_t<BaseClass, Args&...>>; static_assert(directInvoke || referenceInvoke, "BaseClass must have a valid invoke method"); constexpr bool noCopy = directInvoke; auto invoke = [&](auto& instance) { if constexpr (noCopy) { return instance->apply(args...); } else /* need copy */ { return [&instance](Args... copied){ return instance->apply(copied...); }(args...); } }; auto getResult = [&](auto& instance) { if constexpr (procedureInvoke) { invoke(instance); return 0; } else { return invoke(instance); } }; printResult([&](auto& instance) { auto result = getResult(instance); if constexpr (!procedureInvoke) { cout << "result = " << setw(11) << result << flush; } }); } // 强制执行(传入引用) template <typename... Args> void apply(Args&... args) { printResult([&](auto& instance) { instance->apply(args...); }); } }; }
31.580882
116
0.596973
[ "object", "vector" ]
c56e6ec593657760972638938c25804d974e0408
47,743
c
C
qemu/hw/display/xlnx_dp.c
hyunjoy/scripts
01114d3627730d695b5ebe61093c719744432ffa
[ "Apache-2.0" ]
44
2022-03-16T08:32:31.000Z
2022-03-31T16:02:35.000Z
qemu/hw/display/xlnx_dp.c
hyunjoy/scripts
01114d3627730d695b5ebe61093c719744432ffa
[ "Apache-2.0" ]
1
2022-03-29T02:30:28.000Z
2022-03-30T03:40:46.000Z
qemu/hw/display/xlnx_dp.c
hyunjoy/scripts
01114d3627730d695b5ebe61093c719744432ffa
[ "Apache-2.0" ]
18
2022-03-19T04:41:04.000Z
2022-03-31T03:32:12.000Z
/* * Xilinx Display Port * * Copyright (C) 2015 : GreenSocs Ltd * http://www.greensocs.com/ , email: info@greensocs.com * * Developed by : * Frederic Konrad <fred.konrad@greensocs.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option)any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see <http://www.gnu.org/licenses/>. * */ #include "qemu/osdep.h" #include "qapi/error.h" #include "qemu/error-report.h" #include "qemu/log.h" #include "qemu/module.h" #include "hw/display/xlnx_dp.h" #include "hw/irq.h" #include "migration/vmstate.h" #ifndef DEBUG_DP #define DEBUG_DP 0 #endif #define DPRINTF(fmt, ...) do { \ if (DEBUG_DP) { \ qemu_log("xlnx_dp: " fmt , ## __VA_ARGS__); \ } \ } while (0) /* * Register offset for DP. */ #define DP_LINK_BW_SET (0x0000 >> 2) #define DP_LANE_COUNT_SET (0x0004 >> 2) #define DP_ENHANCED_FRAME_EN (0x0008 >> 2) #define DP_TRAINING_PATTERN_SET (0x000C >> 2) #define DP_LINK_QUAL_PATTERN_SET (0x0010 >> 2) #define DP_SCRAMBLING_DISABLE (0x0014 >> 2) #define DP_DOWNSPREAD_CTRL (0x0018 >> 2) #define DP_SOFTWARE_RESET (0x001C >> 2) #define DP_TRANSMITTER_ENABLE (0x0080 >> 2) #define DP_MAIN_STREAM_ENABLE (0x0084 >> 2) #define DP_FORCE_SCRAMBLER_RESET (0x00C0 >> 2) #define DP_VERSION_REGISTER (0x00F8 >> 2) #define DP_CORE_ID (0x00FC >> 2) #define DP_AUX_COMMAND_REGISTER (0x0100 >> 2) #define AUX_ADDR_ONLY_MASK (0x1000) #define AUX_COMMAND_MASK (0x0F00) #define AUX_COMMAND_SHIFT (8) #define AUX_COMMAND_NBYTES (0x000F) #define DP_AUX_WRITE_FIFO (0x0104 >> 2) #define DP_AUX_ADDRESS (0x0108 >> 2) #define DP_AUX_CLOCK_DIVIDER (0x010C >> 2) #define DP_TX_USER_FIFO_OVERFLOW (0x0110 >> 2) #define DP_INTERRUPT_SIGNAL_STATE (0x0130 >> 2) #define DP_AUX_REPLY_DATA (0x0134 >> 2) #define DP_AUX_REPLY_CODE (0x0138 >> 2) #define DP_AUX_REPLY_COUNT (0x013C >> 2) #define DP_REPLY_DATA_COUNT (0x0148 >> 2) #define DP_REPLY_STATUS (0x014C >> 2) #define DP_HPD_DURATION (0x0150 >> 2) #define DP_MAIN_STREAM_HTOTAL (0x0180 >> 2) #define DP_MAIN_STREAM_VTOTAL (0x0184 >> 2) #define DP_MAIN_STREAM_POLARITY (0x0188 >> 2) #define DP_MAIN_STREAM_HSWIDTH (0x018C >> 2) #define DP_MAIN_STREAM_VSWIDTH (0x0190 >> 2) #define DP_MAIN_STREAM_HRES (0x0194 >> 2) #define DP_MAIN_STREAM_VRES (0x0198 >> 2) #define DP_MAIN_STREAM_HSTART (0x019C >> 2) #define DP_MAIN_STREAM_VSTART (0x01A0 >> 2) #define DP_MAIN_STREAM_MISC0 (0x01A4 >> 2) #define DP_MAIN_STREAM_MISC1 (0x01A8 >> 2) #define DP_MAIN_STREAM_M_VID (0x01AC >> 2) #define DP_MSA_TRANSFER_UNIT_SIZE (0x01B0 >> 2) #define DP_MAIN_STREAM_N_VID (0x01B4 >> 2) #define DP_USER_DATA_COUNT_PER_LANE (0x01BC >> 2) #define DP_MIN_BYTES_PER_TU (0x01C4 >> 2) #define DP_FRAC_BYTES_PER_TU (0x01C8 >> 2) #define DP_INIT_WAIT (0x01CC >> 2) #define DP_PHY_RESET (0x0200 >> 2) #define DP_PHY_VOLTAGE_DIFF_LANE_0 (0x0220 >> 2) #define DP_PHY_VOLTAGE_DIFF_LANE_1 (0x0224 >> 2) #define DP_TRANSMIT_PRBS7 (0x0230 >> 2) #define DP_PHY_CLOCK_SELECT (0x0234 >> 2) #define DP_TX_PHY_POWER_DOWN (0x0238 >> 2) #define DP_PHY_PRECURSOR_LANE_0 (0x023C >> 2) #define DP_PHY_PRECURSOR_LANE_1 (0x0240 >> 2) #define DP_PHY_POSTCURSOR_LANE_0 (0x024C >> 2) #define DP_PHY_POSTCURSOR_LANE_1 (0x0250 >> 2) #define DP_PHY_STATUS (0x0280 >> 2) #define DP_TX_AUDIO_CONTROL (0x0300 >> 2) #define DP_TX_AUD_CTRL (1) #define DP_TX_AUDIO_CHANNELS (0x0304 >> 2) #define DP_TX_AUDIO_INFO_DATA(n) ((0x0308 + 4 * n) >> 2) #define DP_TX_M_AUD (0x0328 >> 2) #define DP_TX_N_AUD (0x032C >> 2) #define DP_TX_AUDIO_EXT_DATA(n) ((0x0330 + 4 * n) >> 2) #define DP_INT_STATUS (0x03A0 >> 2) #define DP_INT_MASK (0x03A4 >> 2) #define DP_INT_EN (0x03A8 >> 2) #define DP_INT_DS (0x03AC >> 2) /* * Registers offset for Audio Video Buffer configuration. */ #define V_BLEND_OFFSET (0xA000) #define V_BLEND_BG_CLR_0 (0x0000 >> 2) #define V_BLEND_BG_CLR_1 (0x0004 >> 2) #define V_BLEND_BG_CLR_2 (0x0008 >> 2) #define V_BLEND_SET_GLOBAL_ALPHA_REG (0x000C >> 2) #define V_BLEND_OUTPUT_VID_FORMAT (0x0014 >> 2) #define V_BLEND_LAYER0_CONTROL (0x0018 >> 2) #define V_BLEND_LAYER1_CONTROL (0x001C >> 2) #define V_BLEND_RGB2YCBCR_COEFF(n) ((0x0020 + 4 * n) >> 2) #define V_BLEND_IN1CSC_COEFF(n) ((0x0044 + 4 * n) >> 2) #define V_BLEND_LUMA_IN1CSC_OFFSET (0x0068 >> 2) #define V_BLEND_CR_IN1CSC_OFFSET (0x006C >> 2) #define V_BLEND_CB_IN1CSC_OFFSET (0x0070 >> 2) #define V_BLEND_LUMA_OUTCSC_OFFSET (0x0074 >> 2) #define V_BLEND_CR_OUTCSC_OFFSET (0x0078 >> 2) #define V_BLEND_CB_OUTCSC_OFFSET (0x007C >> 2) #define V_BLEND_IN2CSC_COEFF(n) ((0x0080 + 4 * n) >> 2) #define V_BLEND_LUMA_IN2CSC_OFFSET (0x00A4 >> 2) #define V_BLEND_CR_IN2CSC_OFFSET (0x00A8 >> 2) #define V_BLEND_CB_IN2CSC_OFFSET (0x00AC >> 2) #define V_BLEND_CHROMA_KEY_ENABLE (0x01D0 >> 2) #define V_BLEND_CHROMA_KEY_COMP1 (0x01D4 >> 2) #define V_BLEND_CHROMA_KEY_COMP2 (0x01D8 >> 2) #define V_BLEND_CHROMA_KEY_COMP3 (0x01DC >> 2) /* * Registers offset for Audio Video Buffer configuration. */ #define AV_BUF_MANAGER_OFFSET (0xB000) #define AV_BUF_FORMAT (0x0000 >> 2) #define AV_BUF_NON_LIVE_LATENCY (0x0008 >> 2) #define AV_CHBUF0 (0x0010 >> 2) #define AV_CHBUF1 (0x0014 >> 2) #define AV_CHBUF2 (0x0018 >> 2) #define AV_CHBUF3 (0x001C >> 2) #define AV_CHBUF4 (0x0020 >> 2) #define AV_CHBUF5 (0x0024 >> 2) #define AV_BUF_STC_CONTROL (0x002C >> 2) #define AV_BUF_STC_INIT_VALUE0 (0x0030 >> 2) #define AV_BUF_STC_INIT_VALUE1 (0x0034 >> 2) #define AV_BUF_STC_ADJ (0x0038 >> 2) #define AV_BUF_STC_VIDEO_VSYNC_TS_REG0 (0x003C >> 2) #define AV_BUF_STC_VIDEO_VSYNC_TS_REG1 (0x0040 >> 2) #define AV_BUF_STC_EXT_VSYNC_TS_REG0 (0x0044 >> 2) #define AV_BUF_STC_EXT_VSYNC_TS_REG1 (0x0048 >> 2) #define AV_BUF_STC_CUSTOM_EVENT_TS_REG0 (0x004C >> 2) #define AV_BUF_STC_CUSTOM_EVENT_TS_REG1 (0x0050 >> 2) #define AV_BUF_STC_CUSTOM_EVENT2_TS_REG0 (0x0054 >> 2) #define AV_BUF_STC_CUSTOM_EVENT2_TS_REG1 (0x0058 >> 2) #define AV_BUF_STC_SNAPSHOT0 (0x0060 >> 2) #define AV_BUF_STC_SNAPSHOT1 (0x0064 >> 2) #define AV_BUF_OUTPUT_AUDIO_VIDEO_SELECT (0x0070 >> 2) #define AV_BUF_HCOUNT_VCOUNT_INT0 (0x0074 >> 2) #define AV_BUF_HCOUNT_VCOUNT_INT1 (0x0078 >> 2) #define AV_BUF_DITHER_CONFIG (0x007C >> 2) #define AV_BUF_DITHER_CONFIG_MAX (0x008C >> 2) #define AV_BUF_DITHER_CONFIG_MIN (0x0090 >> 2) #define AV_BUF_PATTERN_GEN_SELECT (0x0100 >> 2) #define AV_BUF_AUD_VID_CLK_SOURCE (0x0120 >> 2) #define AV_BUF_SRST_REG (0x0124 >> 2) #define AV_BUF_AUDIO_RDY_INTERVAL (0x0128 >> 2) #define AV_BUF_AUDIO_CH_CONFIG (0x012C >> 2) #define AV_BUF_GRAPHICS_COMP_SCALE_FACTOR(n)((0x0200 + 4 * n) >> 2) #define AV_BUF_VIDEO_COMP_SCALE_FACTOR(n) ((0x020C + 4 * n) >> 2) #define AV_BUF_LIVE_VIDEO_COMP_SF(n) ((0x0218 + 4 * n) >> 2) #define AV_BUF_LIVE_VID_CONFIG (0x0224 >> 2) #define AV_BUF_LIVE_GFX_COMP_SF(n) ((0x0228 + 4 * n) >> 2) #define AV_BUF_LIVE_GFX_CONFIG (0x0234 >> 2) #define AUDIO_MIXER_REGISTER_OFFSET (0xC000) #define AUDIO_MIXER_VOLUME_CONTROL (0x0000 >> 2) #define AUDIO_MIXER_META_DATA (0x0004 >> 2) #define AUD_CH_STATUS_REG(n) ((0x0008 + 4 * n) >> 2) #define AUD_CH_A_DATA_REG(n) ((0x0020 + 4 * n) >> 2) #define AUD_CH_B_DATA_REG(n) ((0x0038 + 4 * n) >> 2) #define DP_AUDIO_DMA_CHANNEL(n) (4 + n) #define DP_GRAPHIC_DMA_CHANNEL (3) #define DP_VIDEO_DMA_CHANNEL (0) enum DPGraphicFmt { DP_GRAPHIC_RGBA8888 = 0 << 8, DP_GRAPHIC_ABGR8888 = 1 << 8, DP_GRAPHIC_RGB888 = 2 << 8, DP_GRAPHIC_BGR888 = 3 << 8, DP_GRAPHIC_RGBA5551 = 4 << 8, DP_GRAPHIC_RGBA4444 = 5 << 8, DP_GRAPHIC_RGB565 = 6 << 8, DP_GRAPHIC_8BPP = 7 << 8, DP_GRAPHIC_4BPP = 8 << 8, DP_GRAPHIC_2BPP = 9 << 8, DP_GRAPHIC_1BPP = 10 << 8, DP_GRAPHIC_MASK = 0xF << 8 }; enum DPVideoFmt { DP_NL_VID_CB_Y0_CR_Y1 = 0, DP_NL_VID_CR_Y0_CB_Y1 = 1, DP_NL_VID_Y0_CR_Y1_CB = 2, DP_NL_VID_Y0_CB_Y1_CR = 3, DP_NL_VID_YV16 = 4, DP_NL_VID_YV24 = 5, DP_NL_VID_YV16CL = 6, DP_NL_VID_MONO = 7, DP_NL_VID_YV16CL2 = 8, DP_NL_VID_YUV444 = 9, DP_NL_VID_RGB888 = 10, DP_NL_VID_RGBA8880 = 11, DP_NL_VID_RGB888_10BPC = 12, DP_NL_VID_YUV444_10BPC = 13, DP_NL_VID_YV16CL2_10BPC = 14, DP_NL_VID_YV16CL_10BPC = 15, DP_NL_VID_YV16_10BPC = 16, DP_NL_VID_YV24_10BPC = 17, DP_NL_VID_Y_ONLY_10BPC = 18, DP_NL_VID_YV16_420 = 19, DP_NL_VID_YV16CL_420 = 20, DP_NL_VID_YV16CL2_420 = 21, DP_NL_VID_YV16_420_10BPC = 22, DP_NL_VID_YV16CL_420_10BPC = 23, DP_NL_VID_YV16CL2_420_10BPC = 24, DP_NL_VID_FMT_MASK = 0x1F }; typedef enum DPGraphicFmt DPGraphicFmt; typedef enum DPVideoFmt DPVideoFmt; static const VMStateDescription vmstate_dp = { .name = TYPE_XLNX_DP, .version_id = 1, .fields = (VMStateField[]){ VMSTATE_UINT32_ARRAY(core_registers, XlnxDPState, DP_CORE_REG_ARRAY_SIZE), VMSTATE_UINT32_ARRAY(avbufm_registers, XlnxDPState, DP_AVBUF_REG_ARRAY_SIZE), VMSTATE_UINT32_ARRAY(vblend_registers, XlnxDPState, DP_VBLEND_REG_ARRAY_SIZE), VMSTATE_UINT32_ARRAY(audio_registers, XlnxDPState, DP_AUDIO_REG_ARRAY_SIZE), VMSTATE_END_OF_LIST() } }; static void xlnx_dp_update_irq(XlnxDPState *s); static uint64_t xlnx_dp_audio_read(void *opaque, hwaddr offset, unsigned size) { XlnxDPState *s = XLNX_DP(opaque); offset = offset >> 2; return s->audio_registers[offset]; } static void xlnx_dp_audio_write(void *opaque, hwaddr offset, uint64_t value, unsigned size) { XlnxDPState *s = XLNX_DP(opaque); offset = offset >> 2; switch (offset) { case AUDIO_MIXER_META_DATA: s->audio_registers[offset] = value & 0x00000001; break; default: s->audio_registers[offset] = value; break; } } static const MemoryRegionOps audio_ops = { .read = xlnx_dp_audio_read, .write = xlnx_dp_audio_write, .endianness = DEVICE_NATIVE_ENDIAN, }; static inline uint32_t xlnx_dp_audio_get_volume(XlnxDPState *s, uint8_t channel) { switch (channel) { case 0: return extract32(s->audio_registers[AUDIO_MIXER_VOLUME_CONTROL], 0, 16); case 1: return extract32(s->audio_registers[AUDIO_MIXER_VOLUME_CONTROL], 16, 16); default: return 0; } } static inline void xlnx_dp_audio_activate(XlnxDPState *s) { bool activated = ((s->core_registers[DP_TX_AUDIO_CONTROL] & DP_TX_AUD_CTRL) != 0); AUD_set_active_out(s->amixer_output_stream, activated); xlnx_dpdma_set_host_data_location(s->dpdma, DP_AUDIO_DMA_CHANNEL(0), &s->audio_buffer_0); xlnx_dpdma_set_host_data_location(s->dpdma, DP_AUDIO_DMA_CHANNEL(1), &s->audio_buffer_1); } static inline void xlnx_dp_audio_mix_buffer(XlnxDPState *s) { /* * Audio packets are signed and have this shape: * | 16 | 16 | 16 | 16 | 16 | 16 | 16 | 16 | * | R3 | L3 | R2 | L2 | R1 | L1 | R0 | L0 | * * Output audio is 16bits saturated. */ int i; if ((s->audio_data_available[0]) && (xlnx_dp_audio_get_volume(s, 0))) { for (i = 0; i < s->audio_data_available[0] / 2; i++) { s->temp_buffer[i] = (int64_t)(s->audio_buffer_0[i]) * xlnx_dp_audio_get_volume(s, 0) / 8192; } s->byte_left = s->audio_data_available[0]; } else { memset(s->temp_buffer, 0, s->audio_data_available[1] / 2); } if ((s->audio_data_available[1]) && (xlnx_dp_audio_get_volume(s, 1))) { if ((s->audio_data_available[0] == 0) || (s->audio_data_available[1] == s->audio_data_available[0])) { for (i = 0; i < s->audio_data_available[1] / 2; i++) { s->temp_buffer[i] += (int64_t)(s->audio_buffer_1[i]) * xlnx_dp_audio_get_volume(s, 1) / 8192; } s->byte_left = s->audio_data_available[1]; } } for (i = 0; i < s->byte_left / 2; i++) { s->out_buffer[i] = MAX(-32767, MIN(s->temp_buffer[i], 32767)); } s->data_ptr = 0; } static void xlnx_dp_audio_callback(void *opaque, int avail) { /* * Get some data from the DPDMA and compute these datas. * Then wait for QEMU's audio subsystem to call this callback. */ XlnxDPState *s = XLNX_DP(opaque); size_t written = 0; /* If there are already some data don't get more data. */ if (s->byte_left == 0) { s->audio_data_available[0] = xlnx_dpdma_start_operation(s->dpdma, 4, true); s->audio_data_available[1] = xlnx_dpdma_start_operation(s->dpdma, 5, true); xlnx_dp_audio_mix_buffer(s); } /* Send the buffer through the audio. */ if (s->byte_left <= MAX_QEMU_BUFFER_SIZE) { if (s->byte_left != 0) { written = AUD_write(s->amixer_output_stream, &s->out_buffer[s->data_ptr], s->byte_left); } else { int len_to_copy; /* * There is nothing to play.. We don't have any data! Fill the * buffer with zero's and send it. */ written = 0; while (avail) { len_to_copy = MIN(AUD_CHBUF_MAX_DEPTH, avail); memset(s->out_buffer, 0, len_to_copy); avail -= AUD_write(s->amixer_output_stream, s->out_buffer, len_to_copy); } } } else { written = AUD_write(s->amixer_output_stream, &s->out_buffer[s->data_ptr], MAX_QEMU_BUFFER_SIZE); } s->byte_left -= written; s->data_ptr += written; } /* * AUX channel related function. */ static void xlnx_dp_aux_clear_rx_fifo(XlnxDPState *s) { fifo8_reset(&s->rx_fifo); } static void xlnx_dp_aux_push_rx_fifo(XlnxDPState *s, uint8_t *buf, size_t len) { DPRINTF("Push %u data in rx_fifo\n", (unsigned)len); fifo8_push_all(&s->rx_fifo, buf, len); } static uint8_t xlnx_dp_aux_pop_rx_fifo(XlnxDPState *s) { uint8_t ret; if (fifo8_is_empty(&s->rx_fifo)) { qemu_log_mask(LOG_GUEST_ERROR, "%s: Reading empty RX_FIFO\n", __func__); /* * The datasheet is not clear about the reset value, it seems * to be unspecified. We choose to return '0'. */ ret = 0; } else { ret = fifo8_pop(&s->rx_fifo); DPRINTF("pop 0x%" PRIX8 " from rx_fifo.\n", ret); } return ret; } static void xlnx_dp_aux_clear_tx_fifo(XlnxDPState *s) { fifo8_reset(&s->tx_fifo); } static void xlnx_dp_aux_push_tx_fifo(XlnxDPState *s, uint8_t *buf, size_t len) { DPRINTF("Push %u data in tx_fifo\n", (unsigned)len); fifo8_push_all(&s->tx_fifo, buf, len); } static uint8_t xlnx_dp_aux_pop_tx_fifo(XlnxDPState *s) { uint8_t ret; if (fifo8_is_empty(&s->tx_fifo)) { error_report("%s: TX_FIFO underflow", __func__); abort(); } ret = fifo8_pop(&s->tx_fifo); DPRINTF("pop 0x%2.2X from tx_fifo.\n", ret); return ret; } static uint32_t xlnx_dp_aux_get_address(XlnxDPState *s) { return s->core_registers[DP_AUX_ADDRESS]; } /* * Get command from the register. */ static void xlnx_dp_aux_set_command(XlnxDPState *s, uint32_t value) { bool address_only = (value & AUX_ADDR_ONLY_MASK) != 0; AUXCommand cmd = (value & AUX_COMMAND_MASK) >> AUX_COMMAND_SHIFT; uint8_t nbytes = (value & AUX_COMMAND_NBYTES) + 1; uint8_t buf[16]; int i; /* * When an address_only command is executed nothing happen to the fifo, so * just make nbytes = 0. */ if (address_only) { nbytes = 0; } switch (cmd) { case READ_AUX: case READ_I2C: case READ_I2C_MOT: s->core_registers[DP_AUX_REPLY_CODE] = aux_request(s->aux_bus, cmd, xlnx_dp_aux_get_address(s), nbytes, buf); s->core_registers[DP_REPLY_DATA_COUNT] = nbytes; if (s->core_registers[DP_AUX_REPLY_CODE] == AUX_I2C_ACK) { xlnx_dp_aux_push_rx_fifo(s, buf, nbytes); } break; case WRITE_AUX: case WRITE_I2C: case WRITE_I2C_MOT: for (i = 0; i < nbytes; i++) { buf[i] = xlnx_dp_aux_pop_tx_fifo(s); } s->core_registers[DP_AUX_REPLY_CODE] = aux_request(s->aux_bus, cmd, xlnx_dp_aux_get_address(s), nbytes, buf); xlnx_dp_aux_clear_tx_fifo(s); break; case WRITE_I2C_STATUS: qemu_log_mask(LOG_UNIMP, "xlnx_dp: Write i2c status not implemented\n"); break; default: error_report("%s: invalid command: %u", __func__, cmd); abort(); } s->core_registers[DP_INTERRUPT_SIGNAL_STATE] |= 0x04; } static void xlnx_dp_set_dpdma(const Object *obj, const char *name, Object *val, Error **errp) { XlnxDPState *s = XLNX_DP(obj); if (s->console) { DisplaySurface *surface = qemu_console_surface(s->console); XlnxDPDMAState *dma = XLNX_DPDMA(val); xlnx_dpdma_set_host_data_location(dma, DP_GRAPHIC_DMA_CHANNEL, surface_data(surface)); } } static inline uint8_t xlnx_dp_global_alpha_value(XlnxDPState *s) { return (s->vblend_registers[V_BLEND_SET_GLOBAL_ALPHA_REG] & 0x1FE) >> 1; } static inline bool xlnx_dp_global_alpha_enabled(XlnxDPState *s) { /* * If the alpha is totally opaque (255) we consider the alpha is disabled to * reduce CPU consumption. */ return ((xlnx_dp_global_alpha_value(s) != 0xFF) && ((s->vblend_registers[V_BLEND_SET_GLOBAL_ALPHA_REG] & 0x01) != 0)); } static void xlnx_dp_recreate_surface(XlnxDPState *s) { /* * Two possibilities, if blending is enabled the console displays * bout_plane, if not g_plane is displayed. */ uint16_t width = s->core_registers[DP_MAIN_STREAM_HRES]; uint16_t height = s->core_registers[DP_MAIN_STREAM_VRES]; DisplaySurface *current_console_surface = qemu_console_surface(s->console); if ((width != 0) && (height != 0)) { /* * As dpy_gfx_replace_surface calls qemu_free_displaysurface on the * surface we need to be careful and don't free the surface associated * to the console or double free will happen. */ if (s->bout_plane.surface != current_console_surface) { qemu_free_displaysurface(s->bout_plane.surface); } if (s->v_plane.surface != current_console_surface) { qemu_free_displaysurface(s->v_plane.surface); } if (s->g_plane.surface != current_console_surface) { qemu_free_displaysurface(s->g_plane.surface); } s->g_plane.surface = qemu_create_displaysurface_from(width, height, s->g_plane.format, 0, NULL); s->v_plane.surface = qemu_create_displaysurface_from(width, height, s->v_plane.format, 0, NULL); if (xlnx_dp_global_alpha_enabled(s)) { s->bout_plane.surface = qemu_create_displaysurface_from(width, height, s->g_plane.format, 0, NULL); dpy_gfx_replace_surface(s->console, s->bout_plane.surface); } else { s->bout_plane.surface = NULL; dpy_gfx_replace_surface(s->console, s->g_plane.surface); } xlnx_dpdma_set_host_data_location(s->dpdma, DP_GRAPHIC_DMA_CHANNEL, surface_data(s->g_plane.surface)); xlnx_dpdma_set_host_data_location(s->dpdma, DP_VIDEO_DMA_CHANNEL, surface_data(s->v_plane.surface)); } } /* * Change the graphic format of the surface. */ static void xlnx_dp_change_graphic_fmt(XlnxDPState *s) { switch (s->avbufm_registers[AV_BUF_FORMAT] & DP_GRAPHIC_MASK) { case DP_GRAPHIC_RGBA8888: s->g_plane.format = PIXMAN_r8g8b8a8; break; case DP_GRAPHIC_ABGR8888: s->g_plane.format = PIXMAN_a8b8g8r8; break; case DP_GRAPHIC_RGB565: s->g_plane.format = PIXMAN_r5g6b5; break; case DP_GRAPHIC_RGB888: s->g_plane.format = PIXMAN_r8g8b8; break; case DP_GRAPHIC_BGR888: s->g_plane.format = PIXMAN_b8g8r8; break; default: error_report("%s: unsupported graphic format %u", __func__, s->avbufm_registers[AV_BUF_FORMAT] & DP_GRAPHIC_MASK); abort(); } switch (s->avbufm_registers[AV_BUF_FORMAT] & DP_NL_VID_FMT_MASK) { case 0: s->v_plane.format = PIXMAN_x8b8g8r8; break; case DP_NL_VID_Y0_CB_Y1_CR: s->v_plane.format = PIXMAN_yuy2; break; case DP_NL_VID_RGBA8880: s->v_plane.format = PIXMAN_x8b8g8r8; break; default: error_report("%s: unsupported video format %u", __func__, s->avbufm_registers[AV_BUF_FORMAT] & DP_NL_VID_FMT_MASK); abort(); } xlnx_dp_recreate_surface(s); } static void xlnx_dp_update_irq(XlnxDPState *s) { uint32_t flags; flags = s->core_registers[DP_INT_STATUS] & ~s->core_registers[DP_INT_MASK]; DPRINTF("update IRQ value = %" PRIx32 "\n", flags); qemu_set_irq(s->irq, flags != 0); } static uint64_t xlnx_dp_read(void *opaque, hwaddr offset, unsigned size) { XlnxDPState *s = XLNX_DP(opaque); uint64_t ret = 0; offset = offset >> 2; switch (offset) { case DP_TX_USER_FIFO_OVERFLOW: /* This register is cleared after a read */ ret = s->core_registers[DP_TX_USER_FIFO_OVERFLOW]; s->core_registers[DP_TX_USER_FIFO_OVERFLOW] = 0; break; case DP_AUX_REPLY_DATA: ret = xlnx_dp_aux_pop_rx_fifo(s); break; case DP_INTERRUPT_SIGNAL_STATE: /* * XXX: Not sure it is the right thing to do actually. * The register is not written by the device driver so it's stuck * to 0x04. */ ret = s->core_registers[DP_INTERRUPT_SIGNAL_STATE]; s->core_registers[DP_INTERRUPT_SIGNAL_STATE] &= ~0x04; break; case DP_AUX_WRITE_FIFO: case DP_TX_AUDIO_INFO_DATA(0): case DP_TX_AUDIO_INFO_DATA(1): case DP_TX_AUDIO_INFO_DATA(2): case DP_TX_AUDIO_INFO_DATA(3): case DP_TX_AUDIO_INFO_DATA(4): case DP_TX_AUDIO_INFO_DATA(5): case DP_TX_AUDIO_INFO_DATA(6): case DP_TX_AUDIO_INFO_DATA(7): case DP_TX_AUDIO_EXT_DATA(0): case DP_TX_AUDIO_EXT_DATA(1): case DP_TX_AUDIO_EXT_DATA(2): case DP_TX_AUDIO_EXT_DATA(3): case DP_TX_AUDIO_EXT_DATA(4): case DP_TX_AUDIO_EXT_DATA(5): case DP_TX_AUDIO_EXT_DATA(6): case DP_TX_AUDIO_EXT_DATA(7): case DP_TX_AUDIO_EXT_DATA(8): /* write only registers */ ret = 0; break; default: assert(offset <= (0x3AC >> 2)); ret = s->core_registers[offset]; break; } DPRINTF("core read @%" PRIx64 " = 0x%8.8" PRIX64 "\n", offset << 2, ret); return ret; } static void xlnx_dp_write(void *opaque, hwaddr offset, uint64_t value, unsigned size) { XlnxDPState *s = XLNX_DP(opaque); DPRINTF("core write @%" PRIx64 " = 0x%8.8" PRIX64 "\n", offset, value); offset = offset >> 2; switch (offset) { /* * Only special write case are handled. */ case DP_LINK_BW_SET: s->core_registers[offset] = value & 0x000000FF; break; case DP_LANE_COUNT_SET: case DP_MAIN_STREAM_MISC0: s->core_registers[offset] = value & 0x0000000F; break; case DP_TRAINING_PATTERN_SET: case DP_LINK_QUAL_PATTERN_SET: case DP_MAIN_STREAM_POLARITY: case DP_PHY_VOLTAGE_DIFF_LANE_0: case DP_PHY_VOLTAGE_DIFF_LANE_1: s->core_registers[offset] = value & 0x00000003; break; case DP_ENHANCED_FRAME_EN: case DP_SCRAMBLING_DISABLE: case DP_DOWNSPREAD_CTRL: case DP_MAIN_STREAM_ENABLE: case DP_TRANSMIT_PRBS7: s->core_registers[offset] = value & 0x00000001; break; case DP_PHY_CLOCK_SELECT: s->core_registers[offset] = value & 0x00000007; break; case DP_SOFTWARE_RESET: /* * No need to update this bit as it's read '0'. */ /* * TODO: reset IP. */ break; case DP_TRANSMITTER_ENABLE: s->core_registers[offset] = value & 0x01; break; case DP_FORCE_SCRAMBLER_RESET: /* * No need to update this bit as it's read '0'. */ /* * TODO: force a scrambler reset?? */ break; case DP_AUX_COMMAND_REGISTER: s->core_registers[offset] = value & 0x00001F0F; xlnx_dp_aux_set_command(s, s->core_registers[offset]); break; case DP_MAIN_STREAM_HTOTAL: case DP_MAIN_STREAM_VTOTAL: case DP_MAIN_STREAM_HSTART: case DP_MAIN_STREAM_VSTART: s->core_registers[offset] = value & 0x0000FFFF; break; case DP_MAIN_STREAM_HRES: case DP_MAIN_STREAM_VRES: s->core_registers[offset] = value & 0x0000FFFF; xlnx_dp_recreate_surface(s); break; case DP_MAIN_STREAM_HSWIDTH: case DP_MAIN_STREAM_VSWIDTH: s->core_registers[offset] = value & 0x00007FFF; break; case DP_MAIN_STREAM_MISC1: s->core_registers[offset] = value & 0x00000086; break; case DP_MAIN_STREAM_M_VID: case DP_MAIN_STREAM_N_VID: s->core_registers[offset] = value & 0x00FFFFFF; break; case DP_MSA_TRANSFER_UNIT_SIZE: case DP_MIN_BYTES_PER_TU: case DP_INIT_WAIT: s->core_registers[offset] = value & 0x00000007; break; case DP_USER_DATA_COUNT_PER_LANE: s->core_registers[offset] = value & 0x0003FFFF; break; case DP_FRAC_BYTES_PER_TU: s->core_registers[offset] = value & 0x000003FF; break; case DP_PHY_RESET: s->core_registers[offset] = value & 0x00010003; /* * TODO: Reset something? */ break; case DP_TX_PHY_POWER_DOWN: s->core_registers[offset] = value & 0x0000000F; /* * TODO: Power down things? */ break; case DP_AUX_WRITE_FIFO: { uint8_t c = value; xlnx_dp_aux_push_tx_fifo(s, &c, 1); break; } case DP_AUX_CLOCK_DIVIDER: break; case DP_AUX_REPLY_COUNT: /* * Writing to this register clear the counter. */ s->core_registers[offset] = 0x00000000; break; case DP_AUX_ADDRESS: s->core_registers[offset] = value & 0x000FFFFF; break; case DP_VERSION_REGISTER: case DP_CORE_ID: case DP_TX_USER_FIFO_OVERFLOW: case DP_AUX_REPLY_DATA: case DP_AUX_REPLY_CODE: case DP_REPLY_DATA_COUNT: case DP_REPLY_STATUS: case DP_HPD_DURATION: /* * Write to read only location.. */ break; case DP_TX_AUDIO_CONTROL: s->core_registers[offset] = value & 0x00000001; xlnx_dp_audio_activate(s); break; case DP_TX_AUDIO_CHANNELS: s->core_registers[offset] = value & 0x00000007; xlnx_dp_audio_activate(s); break; case DP_INT_STATUS: s->core_registers[DP_INT_STATUS] &= ~value; xlnx_dp_update_irq(s); break; case DP_INT_EN: s->core_registers[DP_INT_MASK] &= ~value; xlnx_dp_update_irq(s); break; case DP_INT_DS: s->core_registers[DP_INT_MASK] |= ~value; xlnx_dp_update_irq(s); break; default: assert(offset <= (0x504C >> 2)); s->core_registers[offset] = value; break; } } static const MemoryRegionOps dp_ops = { .read = xlnx_dp_read, .write = xlnx_dp_write, .endianness = DEVICE_NATIVE_ENDIAN, .valid = { .min_access_size = 4, .max_access_size = 4, }, .impl = { .min_access_size = 4, .max_access_size = 4, }, }; /* * This is to handle Read/Write to the Video Blender. */ static void xlnx_dp_vblend_write(void *opaque, hwaddr offset, uint64_t value, unsigned size) { XlnxDPState *s = XLNX_DP(opaque); bool alpha_was_enabled; DPRINTF("vblend: write @0x%" HWADDR_PRIX " = 0x%" PRIX32 "\n", offset, (uint32_t)value); offset = offset >> 2; switch (offset) { case V_BLEND_BG_CLR_0: case V_BLEND_BG_CLR_1: case V_BLEND_BG_CLR_2: s->vblend_registers[offset] = value & 0x00000FFF; break; case V_BLEND_SET_GLOBAL_ALPHA_REG: /* * A write to this register can enable or disable blending. Thus we need * to recreate the surfaces. */ alpha_was_enabled = xlnx_dp_global_alpha_enabled(s); s->vblend_registers[offset] = value & 0x000001FF; if (xlnx_dp_global_alpha_enabled(s) != alpha_was_enabled) { xlnx_dp_recreate_surface(s); } break; case V_BLEND_OUTPUT_VID_FORMAT: s->vblend_registers[offset] = value & 0x00000017; break; case V_BLEND_LAYER0_CONTROL: case V_BLEND_LAYER1_CONTROL: s->vblend_registers[offset] = value & 0x00000103; break; case V_BLEND_RGB2YCBCR_COEFF(0): case V_BLEND_RGB2YCBCR_COEFF(1): case V_BLEND_RGB2YCBCR_COEFF(2): case V_BLEND_RGB2YCBCR_COEFF(3): case V_BLEND_RGB2YCBCR_COEFF(4): case V_BLEND_RGB2YCBCR_COEFF(5): case V_BLEND_RGB2YCBCR_COEFF(6): case V_BLEND_RGB2YCBCR_COEFF(7): case V_BLEND_RGB2YCBCR_COEFF(8): case V_BLEND_IN1CSC_COEFF(0): case V_BLEND_IN1CSC_COEFF(1): case V_BLEND_IN1CSC_COEFF(2): case V_BLEND_IN1CSC_COEFF(3): case V_BLEND_IN1CSC_COEFF(4): case V_BLEND_IN1CSC_COEFF(5): case V_BLEND_IN1CSC_COEFF(6): case V_BLEND_IN1CSC_COEFF(7): case V_BLEND_IN1CSC_COEFF(8): case V_BLEND_IN2CSC_COEFF(0): case V_BLEND_IN2CSC_COEFF(1): case V_BLEND_IN2CSC_COEFF(2): case V_BLEND_IN2CSC_COEFF(3): case V_BLEND_IN2CSC_COEFF(4): case V_BLEND_IN2CSC_COEFF(5): case V_BLEND_IN2CSC_COEFF(6): case V_BLEND_IN2CSC_COEFF(7): case V_BLEND_IN2CSC_COEFF(8): s->vblend_registers[offset] = value & 0x0000FFFF; break; case V_BLEND_LUMA_IN1CSC_OFFSET: case V_BLEND_CR_IN1CSC_OFFSET: case V_BLEND_CB_IN1CSC_OFFSET: case V_BLEND_LUMA_IN2CSC_OFFSET: case V_BLEND_CR_IN2CSC_OFFSET: case V_BLEND_CB_IN2CSC_OFFSET: case V_BLEND_LUMA_OUTCSC_OFFSET: case V_BLEND_CR_OUTCSC_OFFSET: case V_BLEND_CB_OUTCSC_OFFSET: s->vblend_registers[offset] = value & 0x3FFF7FFF; break; case V_BLEND_CHROMA_KEY_ENABLE: s->vblend_registers[offset] = value & 0x00000003; break; case V_BLEND_CHROMA_KEY_COMP1: case V_BLEND_CHROMA_KEY_COMP2: case V_BLEND_CHROMA_KEY_COMP3: s->vblend_registers[offset] = value & 0x0FFF0FFF; break; default: s->vblend_registers[offset] = value; break; } } static uint64_t xlnx_dp_vblend_read(void *opaque, hwaddr offset, unsigned size) { XlnxDPState *s = XLNX_DP(opaque); DPRINTF("vblend: read @0x%" HWADDR_PRIX " = 0x%" PRIX32 "\n", offset, s->vblend_registers[offset >> 2]); return s->vblend_registers[offset >> 2]; } static const MemoryRegionOps vblend_ops = { .read = xlnx_dp_vblend_read, .write = xlnx_dp_vblend_write, .endianness = DEVICE_NATIVE_ENDIAN, .valid = { .min_access_size = 4, .max_access_size = 4, }, .impl = { .min_access_size = 4, .max_access_size = 4, }, }; /* * This is to handle Read/Write to the Audio Video buffer manager. */ static void xlnx_dp_avbufm_write(void *opaque, hwaddr offset, uint64_t value, unsigned size) { XlnxDPState *s = XLNX_DP(opaque); DPRINTF("avbufm: write @0x%" HWADDR_PRIX " = 0x%" PRIX32 "\n", offset, (uint32_t)value); offset = offset >> 2; switch (offset) { case AV_BUF_FORMAT: s->avbufm_registers[offset] = value & 0x00000FFF; xlnx_dp_change_graphic_fmt(s); break; case AV_CHBUF0: case AV_CHBUF1: case AV_CHBUF2: case AV_CHBUF3: case AV_CHBUF4: case AV_CHBUF5: s->avbufm_registers[offset] = value & 0x0000007F; break; case AV_BUF_OUTPUT_AUDIO_VIDEO_SELECT: s->avbufm_registers[offset] = value & 0x0000007F; break; case AV_BUF_DITHER_CONFIG: s->avbufm_registers[offset] = value & 0x000007FF; break; case AV_BUF_DITHER_CONFIG_MAX: case AV_BUF_DITHER_CONFIG_MIN: s->avbufm_registers[offset] = value & 0x00000FFF; break; case AV_BUF_PATTERN_GEN_SELECT: s->avbufm_registers[offset] = value & 0xFFFFFF03; break; case AV_BUF_AUD_VID_CLK_SOURCE: s->avbufm_registers[offset] = value & 0x00000007; break; case AV_BUF_SRST_REG: s->avbufm_registers[offset] = value & 0x00000002; break; case AV_BUF_AUDIO_CH_CONFIG: s->avbufm_registers[offset] = value & 0x00000003; break; case AV_BUF_GRAPHICS_COMP_SCALE_FACTOR(0): case AV_BUF_GRAPHICS_COMP_SCALE_FACTOR(1): case AV_BUF_GRAPHICS_COMP_SCALE_FACTOR(2): case AV_BUF_VIDEO_COMP_SCALE_FACTOR(0): case AV_BUF_VIDEO_COMP_SCALE_FACTOR(1): case AV_BUF_VIDEO_COMP_SCALE_FACTOR(2): s->avbufm_registers[offset] = value & 0x0000FFFF; break; case AV_BUF_LIVE_VIDEO_COMP_SF(0): case AV_BUF_LIVE_VIDEO_COMP_SF(1): case AV_BUF_LIVE_VIDEO_COMP_SF(2): case AV_BUF_LIVE_VID_CONFIG: case AV_BUF_LIVE_GFX_COMP_SF(0): case AV_BUF_LIVE_GFX_COMP_SF(1): case AV_BUF_LIVE_GFX_COMP_SF(2): case AV_BUF_LIVE_GFX_CONFIG: case AV_BUF_NON_LIVE_LATENCY: case AV_BUF_STC_CONTROL: case AV_BUF_STC_INIT_VALUE0: case AV_BUF_STC_INIT_VALUE1: case AV_BUF_STC_ADJ: case AV_BUF_STC_VIDEO_VSYNC_TS_REG0: case AV_BUF_STC_VIDEO_VSYNC_TS_REG1: case AV_BUF_STC_EXT_VSYNC_TS_REG0: case AV_BUF_STC_EXT_VSYNC_TS_REG1: case AV_BUF_STC_CUSTOM_EVENT_TS_REG0: case AV_BUF_STC_CUSTOM_EVENT_TS_REG1: case AV_BUF_STC_CUSTOM_EVENT2_TS_REG0: case AV_BUF_STC_CUSTOM_EVENT2_TS_REG1: case AV_BUF_STC_SNAPSHOT0: case AV_BUF_STC_SNAPSHOT1: case AV_BUF_HCOUNT_VCOUNT_INT0: case AV_BUF_HCOUNT_VCOUNT_INT1: qemu_log_mask(LOG_UNIMP, "avbufm: unimplemented register 0x%04" PRIx64 "\n", offset << 2); break; default: s->avbufm_registers[offset] = value; break; } } static uint64_t xlnx_dp_avbufm_read(void *opaque, hwaddr offset, unsigned size) { XlnxDPState *s = XLNX_DP(opaque); offset = offset >> 2; return s->avbufm_registers[offset]; } static const MemoryRegionOps avbufm_ops = { .read = xlnx_dp_avbufm_read, .write = xlnx_dp_avbufm_write, .endianness = DEVICE_NATIVE_ENDIAN, .valid = { .min_access_size = 4, .max_access_size = 4, }, .impl = { .min_access_size = 4, .max_access_size = 4, }, }; /* * This is a global alpha blending using pixman. * Both graphic and video planes are multiplied with the global alpha * coefficient and added. */ static inline void xlnx_dp_blend_surface(XlnxDPState *s) { pixman_fixed_t alpha1[] = { pixman_double_to_fixed(1), pixman_double_to_fixed(1), pixman_double_to_fixed(1.0) }; pixman_fixed_t alpha2[] = { pixman_double_to_fixed(1), pixman_double_to_fixed(1), pixman_double_to_fixed(1.0) }; if ((surface_width(s->g_plane.surface) != surface_width(s->v_plane.surface)) || (surface_height(s->g_plane.surface) != surface_height(s->v_plane.surface))) { return; } alpha1[2] = pixman_double_to_fixed((double)(xlnx_dp_global_alpha_value(s)) / 256.0); alpha2[2] = pixman_double_to_fixed((255.0 - (double)xlnx_dp_global_alpha_value(s)) / 256.0); pixman_image_set_filter(s->g_plane.surface->image, PIXMAN_FILTER_CONVOLUTION, alpha1, 3); pixman_image_composite(PIXMAN_OP_SRC, s->g_plane.surface->image, 0, s->bout_plane.surface->image, 0, 0, 0, 0, 0, 0, surface_width(s->g_plane.surface), surface_height(s->g_plane.surface)); pixman_image_set_filter(s->v_plane.surface->image, PIXMAN_FILTER_CONVOLUTION, alpha2, 3); pixman_image_composite(PIXMAN_OP_ADD, s->v_plane.surface->image, 0, s->bout_plane.surface->image, 0, 0, 0, 0, 0, 0, surface_width(s->g_plane.surface), surface_height(s->g_plane.surface)); } static void xlnx_dp_update_display(void *opaque) { XlnxDPState *s = XLNX_DP(opaque); if ((s->core_registers[DP_TRANSMITTER_ENABLE] & 0x01) == 0) { return; } s->core_registers[DP_INT_STATUS] |= (1 << 13); xlnx_dp_update_irq(s); xlnx_dpdma_trigger_vsync_irq(s->dpdma); /* * Trigger the DMA channel. */ if (!xlnx_dpdma_start_operation(s->dpdma, 3, false)) { /* * An error occurred don't do anything with the data.. * Trigger an underflow interrupt. */ s->core_registers[DP_INT_STATUS] |= (1 << 21); xlnx_dp_update_irq(s); return; } if (xlnx_dp_global_alpha_enabled(s)) { if (!xlnx_dpdma_start_operation(s->dpdma, 0, false)) { s->core_registers[DP_INT_STATUS] |= (1 << 21); xlnx_dp_update_irq(s); return; } xlnx_dp_blend_surface(s); } /* * XXX: We might want to update only what changed. */ dpy_gfx_update_full(s->console); } static const GraphicHwOps xlnx_dp_gfx_ops = { .gfx_update = xlnx_dp_update_display, }; static void xlnx_dp_init(Object *obj) { SysBusDevice *sbd = SYS_BUS_DEVICE(obj); XlnxDPState *s = XLNX_DP(obj); memory_region_init(&s->container, obj, TYPE_XLNX_DP, 0xC050); memory_region_init_io(&s->core_iomem, obj, &dp_ops, s, TYPE_XLNX_DP ".core", 0x3AF); memory_region_add_subregion(&s->container, 0x0000, &s->core_iomem); memory_region_init_io(&s->vblend_iomem, obj, &vblend_ops, s, TYPE_XLNX_DP ".v_blend", 0x1DF); memory_region_add_subregion(&s->container, 0xA000, &s->vblend_iomem); memory_region_init_io(&s->avbufm_iomem, obj, &avbufm_ops, s, TYPE_XLNX_DP ".av_buffer_manager", 0x238); memory_region_add_subregion(&s->container, 0xB000, &s->avbufm_iomem); memory_region_init_io(&s->audio_iomem, obj, &audio_ops, s, TYPE_XLNX_DP ".audio", sizeof(s->audio_registers)); memory_region_add_subregion(&s->container, 0xC000, &s->audio_iomem); sysbus_init_mmio(sbd, &s->container); sysbus_init_irq(sbd, &s->irq); object_property_add_link(obj, "dpdma", TYPE_XLNX_DPDMA, (Object **) &s->dpdma, xlnx_dp_set_dpdma, OBJ_PROP_LINK_STRONG); /* * Initialize AUX Bus. */ s->aux_bus = aux_bus_init(DEVICE(obj), "aux"); /* * Initialize DPCD and EDID.. */ s->dpcd = DPCD(qdev_new("dpcd")); object_property_add_child(OBJECT(s), "dpcd", OBJECT(s->dpcd)); s->edid = I2CDDC(qdev_new("i2c-ddc")); i2c_set_slave_address(I2C_SLAVE(s->edid), 0x50); object_property_add_child(OBJECT(s), "edid", OBJECT(s->edid)); fifo8_create(&s->rx_fifo, 16); fifo8_create(&s->tx_fifo, 16); } static void xlnx_dp_realize(DeviceState *dev, Error **errp) { XlnxDPState *s = XLNX_DP(dev); DisplaySurface *surface; struct audsettings as; aux_bus_realize(s->aux_bus); qdev_realize(DEVICE(s->dpcd), BUS(s->aux_bus), &error_fatal); aux_map_slave(AUX_SLAVE(s->dpcd), 0x0000); qdev_realize_and_unref(DEVICE(s->edid), BUS(aux_get_i2c_bus(s->aux_bus)), &error_fatal); s->console = graphic_console_init(dev, 0, &xlnx_dp_gfx_ops, s); surface = qemu_console_surface(s->console); xlnx_dpdma_set_host_data_location(s->dpdma, DP_GRAPHIC_DMA_CHANNEL, surface_data(surface)); as.freq = 44100; as.nchannels = 2; as.fmt = AUDIO_FORMAT_S16; as.endianness = 0; AUD_register_card("xlnx_dp.audio", &s->aud_card); s->amixer_output_stream = AUD_open_out(&s->aud_card, s->amixer_output_stream, "xlnx_dp.audio.out", s, xlnx_dp_audio_callback, &as); AUD_set_volume_out(s->amixer_output_stream, 0, 255, 255); xlnx_dp_audio_activate(s); } static void xlnx_dp_reset(DeviceState *dev) { XlnxDPState *s = XLNX_DP(dev); memset(s->core_registers, 0, sizeof(s->core_registers)); s->core_registers[DP_VERSION_REGISTER] = 0x04010000; s->core_registers[DP_CORE_ID] = 0x01020000; s->core_registers[DP_REPLY_STATUS] = 0x00000010; s->core_registers[DP_MSA_TRANSFER_UNIT_SIZE] = 0x00000040; s->core_registers[DP_INIT_WAIT] = 0x00000020; s->core_registers[DP_PHY_RESET] = 0x00010003; s->core_registers[DP_INT_MASK] = 0xFFFFF03F; s->core_registers[DP_PHY_STATUS] = 0x00000043; s->core_registers[DP_INTERRUPT_SIGNAL_STATE] = 0x00000001; s->vblend_registers[V_BLEND_RGB2YCBCR_COEFF(0)] = 0x00001000; s->vblend_registers[V_BLEND_RGB2YCBCR_COEFF(4)] = 0x00001000; s->vblend_registers[V_BLEND_RGB2YCBCR_COEFF(8)] = 0x00001000; s->vblend_registers[V_BLEND_IN1CSC_COEFF(0)] = 0x00001000; s->vblend_registers[V_BLEND_IN1CSC_COEFF(4)] = 0x00001000; s->vblend_registers[V_BLEND_IN1CSC_COEFF(8)] = 0x00001000; s->vblend_registers[V_BLEND_IN2CSC_COEFF(0)] = 0x00001000; s->vblend_registers[V_BLEND_IN2CSC_COEFF(4)] = 0x00001000; s->vblend_registers[V_BLEND_IN2CSC_COEFF(8)] = 0x00001000; s->avbufm_registers[AV_BUF_NON_LIVE_LATENCY] = 0x00000180; s->avbufm_registers[AV_BUF_OUTPUT_AUDIO_VIDEO_SELECT] = 0x00000008; s->avbufm_registers[AV_BUF_DITHER_CONFIG_MAX] = 0x00000FFF; s->avbufm_registers[AV_BUF_GRAPHICS_COMP_SCALE_FACTOR(0)] = 0x00010101; s->avbufm_registers[AV_BUF_GRAPHICS_COMP_SCALE_FACTOR(1)] = 0x00010101; s->avbufm_registers[AV_BUF_GRAPHICS_COMP_SCALE_FACTOR(2)] = 0x00010101; s->avbufm_registers[AV_BUF_VIDEO_COMP_SCALE_FACTOR(0)] = 0x00010101; s->avbufm_registers[AV_BUF_VIDEO_COMP_SCALE_FACTOR(1)] = 0x00010101; s->avbufm_registers[AV_BUF_VIDEO_COMP_SCALE_FACTOR(2)] = 0x00010101; s->avbufm_registers[AV_BUF_LIVE_VIDEO_COMP_SF(0)] = 0x00010101; s->avbufm_registers[AV_BUF_LIVE_VIDEO_COMP_SF(1)] = 0x00010101; s->avbufm_registers[AV_BUF_LIVE_VIDEO_COMP_SF(2)] = 0x00010101; s->avbufm_registers[AV_BUF_LIVE_GFX_COMP_SF(0)] = 0x00010101; s->avbufm_registers[AV_BUF_LIVE_GFX_COMP_SF(1)] = 0x00010101; s->avbufm_registers[AV_BUF_LIVE_GFX_COMP_SF(2)] = 0x00010101; memset(s->audio_registers, 0, sizeof(s->audio_registers)); s->byte_left = 0; xlnx_dp_aux_clear_rx_fifo(s); xlnx_dp_change_graphic_fmt(s); xlnx_dp_update_irq(s); } static void xlnx_dp_class_init(ObjectClass *oc, void *data) { DeviceClass *dc = DEVICE_CLASS(oc); dc->realize = xlnx_dp_realize; dc->vmsd = &vmstate_dp; dc->reset = xlnx_dp_reset; } static const TypeInfo xlnx_dp_info = { .name = TYPE_XLNX_DP, .parent = TYPE_SYS_BUS_DEVICE, .instance_size = sizeof(XlnxDPState), .instance_init = xlnx_dp_init, .class_init = xlnx_dp_class_init, }; static void xlnx_dp_register_types(void) { type_register_static(&xlnx_dp_info); } type_init(xlnx_dp_register_types)
34.823487
80
0.610603
[ "object", "shape" ]
c5703840f297d17bdee53755c28052c788c9e009
6,347
h
C
include/yaz/icu_I18N.h
dcrossleyau/yaz
af3a02922bd2d0a7c080942cbe7f55a7710dd27e
[ "BSD-3-Clause" ]
35
2016-01-12T00:21:19.000Z
2022-02-21T12:12:11.000Z
include/yaz/icu_I18N.h
dcrossleyau/yaz
af3a02922bd2d0a7c080942cbe7f55a7710dd27e
[ "BSD-3-Clause" ]
33
2016-01-27T16:44:32.000Z
2022-01-17T16:14:11.000Z
include/yaz/icu_I18N.h
dcrossleyau/yaz
af3a02922bd2d0a7c080942cbe7f55a7710dd27e
[ "BSD-3-Clause" ]
18
2016-01-27T15:48:13.000Z
2021-05-17T20:29:22.000Z
/* This file is part of the YAZ toolkit. * Copyright (C) Index Data. * 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 Index Data nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND 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 \brief Internal header for ICU utilities These functions, while non-static, are considered unstable and internal and may be renamed for each YAZ release. */ #ifndef ICU_I18NL_H #define ICU_I18NL_H #include <yaz/yconfig.h> #include <unicode/utypes.h> /* Basic ICU data types */ #include <unicode/uchar.h> /* char names */ #include <unicode/ucol.h> #include <unicode/ubrk.h> #include <yaz/icu.h> /* declared structs and functions */ int icu_check_status(UErrorCode status); struct icu_buf_utf16 { UChar * utf16; int32_t utf16_len; int32_t utf16_cap; }; struct icu_buf_utf16 * icu_buf_utf16_create(size_t capacity); struct icu_buf_utf16 * icu_buf_utf16_clear(struct icu_buf_utf16 * buf16); struct icu_buf_utf16 * icu_buf_utf16_resize(struct icu_buf_utf16 * buf16, size_t capacity); struct icu_buf_utf16 *icu_buf_utf16_copy(struct icu_buf_utf16 * dest16, const struct icu_buf_utf16 * src16); struct icu_buf_utf16 *icu_buf_utf16_append(struct icu_buf_utf16 *dest16, const struct icu_buf_utf16 * src16); void icu_buf_utf16_log(const char *lead, struct icu_buf_utf16 *src16); void icu_buf_utf16_destroy(struct icu_buf_utf16 * buf16); struct icu_buf_utf8; struct icu_buf_utf8 { uint8_t * utf8; int32_t utf8_len; int32_t utf8_cap; }; struct icu_buf_utf8 * icu_buf_utf8_create(size_t capacity); struct icu_buf_utf8 * icu_buf_utf8_clear(struct icu_buf_utf8 * buf8); struct icu_buf_utf8 * icu_buf_utf8_resize(struct icu_buf_utf8 * buf8, size_t capacity); void icu_buf_utf8_destroy(struct icu_buf_utf8 * buf8); UErrorCode icu_utf16_from_utf8_cstr(struct icu_buf_utf16 * dest16, const char * src8cstr, UErrorCode * status); const char *icu_buf_utf8_to_cstr(struct icu_buf_utf8 *src8); UErrorCode icu_utf16_to_utf8(struct icu_buf_utf8 *dest8, const struct icu_buf_utf16 *src16, UErrorCode * status); struct icu_casemap; struct icu_casemap *icu_casemap_create(char action, UErrorCode *status); struct icu_casemap *icu_casemap_clone(struct icu_casemap *old); void icu_casemap_destroy(struct icu_casemap *casemap); int icu_casemap_casemap(struct icu_casemap *casemap, struct icu_buf_utf16 *dest16, struct icu_buf_utf16 *src16, UErrorCode *status, const char *locale); int icu_utf16_casemap(struct icu_buf_utf16 *dest16, struct icu_buf_utf16 *src16, const char *locale, char action, UErrorCode *status); void icu_sortkey8_from_utf16(UCollator *coll, struct icu_buf_utf8 *dest8, struct icu_buf_utf16 *src16, UErrorCode *status); struct icu_tokenizer; struct icu_tokenizer * icu_tokenizer_create(const char *locale, char action, UErrorCode *status); struct icu_tokenizer *icu_tokenizer_clone(struct icu_tokenizer *old); void icu_tokenizer_destroy(struct icu_tokenizer *tokenizer); int icu_tokenizer_attach(struct icu_tokenizer *tokenizer, struct icu_buf_utf16 *src16, UErrorCode *status); int32_t icu_tokenizer_next_token(struct icu_tokenizer *tokenizer, struct icu_buf_utf16 *tkn16, UErrorCode *status, size_t *start, size_t *len); int32_t icu_tokenizer_token_count(struct icu_tokenizer * tokenizer); struct icu_transform; struct icu_transform * icu_transform_create(const char *id, char action, const char *rules, UErrorCode *status); struct icu_transform *icu_transform_clone(struct icu_transform *old); void icu_transform_destroy(struct icu_transform * transform); int icu_transform_trans(struct icu_transform *transform, struct icu_buf_utf16 *dest16, const struct icu_buf_utf16 *src16, UErrorCode *status); struct icu_chain_step; int icu_chain_token_number(yaz_icu_chain_t chain); yaz_icu_chain_t icu_chain_create(const char *locale, int sort, UErrorCode *status); #endif /* ICU_I18NL_H */ /* * Local variables: * c-basic-offset: 4 * c-file-style: "Stroustrup" * indent-tabs-mode: nil * End: * vim: shiftwidth=4 tabstop=8 expandtab */
35.657303
79
0.669135
[ "transform" ]
c57269df94fb138d7e9c7c1b5db9781b31fddd0d
2,382
h
C
syntaxnet/syntaxnet/document_format.h
robrkerr/tensorflow-models
3656a07e89be134c2bc333c60a6c709e475024a6
[ "Apache-2.0" ]
13
2018-06-22T10:42:39.000Z
2022-01-26T11:44:12.000Z
syntaxnet/syntaxnet/document_format.h
robrkerr/tensorflow-models
3656a07e89be134c2bc333c60a6c709e475024a6
[ "Apache-2.0" ]
7
2019-12-31T03:47:50.000Z
2022-02-10T00:38:51.000Z
syntaxnet/syntaxnet/document_format.h
robrkerr/tensorflow-models
3656a07e89be134c2bc333c60a6c709e475024a6
[ "Apache-2.0" ]
36
2017-03-15T18:18:41.000Z
2022-03-04T04:48:37.000Z
/* Copyright 2016 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // An interface for document formats. #ifndef SYNTAXNET_DOCUMENT_FORMAT_H__ #define SYNTAXNET_DOCUMENT_FORMAT_H__ #include <string> #include <vector> #include "syntaxnet/utils.h" #include "syntaxnet/registry.h" #include "syntaxnet/sentence.pb.h" #include "syntaxnet/task_context.h" #include "tensorflow/core/lib/io/buffered_inputstream.h" namespace syntaxnet { // A document format component converts a key/value pair from a record to one or // more documents. The record format is used for selecting the document format // component. A document format component can be registered with the // REGISTER_SYNTAXNET_DOCUMENT_FORMAT macro. class DocumentFormat : public RegisterableClass<DocumentFormat> { public: DocumentFormat() {} virtual ~DocumentFormat() {} virtual void Setup(TaskContext *context) {} // Reads a record from the given input buffer with format specific logic. // Returns false if no record could be read because we reached end of file. virtual bool ReadRecord(tensorflow::io::BufferedInputStream *buffer, string *record) = 0; // Converts a key/value pair to one or more documents. virtual void ConvertFromString(const string &key, const string &value, std::vector<Sentence *> *documents) = 0; // Converts a document to a key/value pair. virtual void ConvertToString(const Sentence &document, string *key, string *value) = 0; private: TF_DISALLOW_COPY_AND_ASSIGN(DocumentFormat); }; #define REGISTER_SYNTAXNET_DOCUMENT_FORMAT(type, component) \ REGISTER_SYNTAXNET_CLASS_COMPONENT(DocumentFormat, type, component) } // namespace syntaxnet #endif // SYNTAXNET_DOCUMENT_FORMAT_H__
36.090909
80
0.724601
[ "vector" ]
c574b1e0446d9b27a128c312172cf360d24da864
379
h
C
tests/nonsmoke/functional/CompileTests/Cxx11_tests/test2018_17.h
ouankou/rose
76f2a004bd6d8036bc24be2c566a14e33ba4f825
[ "BSD-3-Clause" ]
488
2015-01-09T08:54:48.000Z
2022-03-30T07:15:46.000Z
tests/nonsmoke/functional/CompileTests/Cxx11_tests/test2018_17.h
WildeGeist/rose
17db6454e8baba0014e30a8ec23df1a11ac55a0c
[ "BSD-3-Clause" ]
174
2015-01-28T18:41:32.000Z
2022-03-31T16:51:05.000Z
tests/nonsmoke/functional/CompileTests/Cxx11_tests/test2018_17.h
WildeGeist/rose
17db6454e8baba0014e30a8ec23df1a11ac55a0c
[ "BSD-3-Clause" ]
146
2015-04-27T02:48:34.000Z
2022-03-04T07:32:53.000Z
// #include "algorithm" // namespace XXX // { template<typename _CharT> struct char_traits { }; template<> struct char_traits<unsigned int> { typedef unsigned int int_type; }; template<typename _Tp > class vector { }; // } vector<char_traits<unsigned int>::int_type> local2; // Put this into a header file if required. // vector<unsigned> method1();
14.037037
51
0.670185
[ "vector" ]
c574ecd9e739878b3cd0ed28485bf4adf1432638
106,639
c
C
source/main.c
HarshitJoshi9152/EP01_SandSim
a4b7a27f594899f01f95af89a907b3d50270652d
[ "BSD-3-Clause" ]
322
2020-04-28T20:07:41.000Z
2022-03-29T15:17:42.000Z
source/main.c
HarshitJoshi9152/EP01_SandSim
a4b7a27f594899f01f95af89a907b3d50270652d
[ "BSD-3-Clause" ]
2
2021-04-11T08:26:50.000Z
2021-12-30T16:12:04.000Z
source/main.c
HarshitJoshi9152/EP01_SandSim
a4b7a27f594899f01f95af89a907b3d50270652d
[ "BSD-3-Clause" ]
40
2020-05-23T08:50:46.000Z
2022-03-16T05:13:32.000Z
#define GS_IMPL #include <gs/gs.h> #define GS_IMMEDIATE_DRAW_IMPL #include <gs/util/gs_idraw.h> #include "render_pass/blur_pass.h" #include "render_pass/bright_filter_pass.h" #include "render_pass/composite_pass.h" #include "font/font.h" #include "font/font_data.c" gs_global const s32 g_window_width = 800; gs_global const s32 g_window_height = 600; gs_global const s32 g_texture_width = 1258 >> 1; gs_global const s32 g_texture_height = 848 >> 1; // 32 bit color structure typedef struct color_t { u8 r; u8 g; u8 b; u8 a; } color_t; typedef struct particle_t { u8 id; f32 life_time; gs_vec2 velocity; color_t color; b32 has_been_updated_this_frame; } particle_t; // Should have a hash map of glyph character to glyph metric // Globals gs_global gs_command_buffer_t g_cb = {0}; gs_global gs_immediate_draw_t g_gsi = {0}; gs_global gs_handle(gs_graphics_vertex_buffer_t) g_vbo = {0}; gs_global gs_handle(gs_graphics_index_buffer_t) g_ibo = {0}; gs_global gs_handle(gs_graphics_shader_t) g_shader = {0}; gs_global gs_handle(gs_graphics_uniform_t) u_tex = {0}; gs_global gs_handle(gs_graphics_uniform_t) u_flip_y = {0}; gs_global gs_handle(gs_graphics_texture_t) g_tex = {0}; gs_global gs_handle(gs_graphics_texture_t) g_tex_ui = {0}; gs_global gs_handle(gs_graphics_texture_t) g_rt = {0}; gs_global gs_handle(gs_graphics_framebuffer_t) g_fb = {0}; gs_global gs_handle(gs_graphics_render_pass_t) g_rp = {0}; gs_global gs_handle(gs_graphics_pipeline_t) g_pip = {0}; gs_global blur_pass_t g_blur_pass = {0}; gs_global bright_filter_pass_t g_bright_pass = {0}; gs_global composite_pass_t g_composite_pass = {0}; gs_global font_t g_font = {0}; // For now, all particle information will simply be a value to determine its material id #define mat_id_empty (u8)0 #define mat_id_sand (u8)1 #define mat_id_water (u8)2 #define mat_id_salt (u8)3 #define mat_id_wood (u8)4 #define mat_id_fire (u8)5 #define mat_id_smoke (u8)6 #define mat_id_ember (u8)7 #define mat_id_steam (u8)8 #define mat_id_gunpowder (u8)9 #define mat_id_oil (u8)10 #define mat_id_lava (u8)11 #define mat_id_stone (u8)12 #define mat_id_acid (u8)13 // Colors #define mat_col_empty (color_t){0, 0, 0, 0} #define mat_col_sand (color_t){150, 100, 50, 255} #define mat_col_salt (color_t){200, 180, 190, 255} #define mat_col_water (color_t){20, 100, 170, 200} #define mat_col_stone (color_t){120, 110, 120, 255} #define mat_col_wood (color_t){60, 40, 20, 255} #define mat_col_fire (color_t){150, 20, 0, 255} #define mat_col_smoke (color_t){50, 50, 50, 255} #define mat_col_ember (color_t){200, 120, 20, 255} #define mat_col_steam (color_t){220, 220, 250, 255} #define mat_col_gunpowder (color_t){60, 60, 60, 255} #define mat_col_oil (color_t){80, 70, 60, 255} #define mat_col_lava (color_t){200, 50, 0, 255} #define mat_col_acid (color_t){90, 200, 60, 255} typedef enum material_selection { mat_sel_sand = 0x00, mat_sel_water, mat_sel_salt, mat_sel_wood, mat_sel_fire, mat_sel_smoke, mat_sel_steam, mat_sel_gunpowder, mat_sel_oil, mat_sel_lava, mat_sel_stone, mat_sel_acid } material_selection; // Material selection for "painting" / default to sand gs_global material_selection g_material_selection = mat_sel_sand; // World update processing structure gs_global u8* g_world_process_update_structure = {0}; // Every particle has id associated with it? Jeezuz... // World particle data structure gs_global particle_t* g_world_particle_data = {0}; // Texture buffers gs_global color_t* g_texture_buffer = {0}; // UI texture buffer gs_global color_t* g_ui_buffer = {0}; // Frame counter gs_global u32 g_frame_counter = 0; // World physics settings gs_global f32 gravity = 10.f; gs_global f32 g_selection_radius = 10.f; gs_global b32 g_show_material_selection_panel = true; gs_global b32 g_run_simulation = true; gs_global b32 g_show_frame_count = true; gs_global b32 g_use_post_processing = true; // Shaders #if (defined GS_PLATFORM_WEB || defined GS_PLATFORM_ANDROID) #define GL_VERSION_STR "#version 300 es\n" #else #define GL_VERSION_STR "#version 330 core\n" #endif const char* v_src = GL_VERSION_STR "precision mediump float;\n" "layout (location = 0) in vec2 a_pos;\n" "layout (location = 1) in vec2 a_texCoord;\n" "uniform int u_flip_y;" "out vec2 texCoord;\n" "void main()\n" "{\n" " gl_Position = vec4(a_pos, 0.0, 1.0);\n" " texCoord = vec2(a_texCoord.x, bool(u_flip_y) ? 1.0 - a_texCoord.y : a_texCoord.y);\n" "}"; const char* f_src = GL_VERSION_STR "precision mediump float;\n" "out vec4 frag_color;\n" "in vec2 texCoord;\n" "uniform sampler2D u_tex;\n" "void main()\n" "{\n" " frag_color = texture(u_tex, texCoord);\n" "}"; // Forward Decls. void app_init(); void app_update(); void app_shutdown(); particle_t particle_empty(); particle_t particle_sand(); particle_t particle_water(); particle_t particle_salt(); particle_t particle_wood(); particle_t particle_fire(); particle_t particle_lava(); particle_t particle_smoke(); particle_t particle_ember(); particle_t particle_steam(); particle_t particle_gunpowder(); particle_t particle_oil(); particle_t particle_stone(); particle_t particle_acid(); void update_input(gs_command_buffer_t* cb); b32 update_ui(gs_command_buffer_t* cb); // Particle updates void update_particle_sim(gs_command_buffer_t* cb); void update_sand(u32 x, u32 y); void update_water(u32 x, u32 y); void update_salt(u32 x, u32 y); void update_fire(u32 x, u32 y); void update_smoke(u32 x, u32 y); void update_ember(u32 x, u32 y); void update_steam(u32 x, u32 y); void update_gunpowder(u32 x, u32 y); void update_oil(u32 x, u32 y); void update_lava(u32 x, u32 y); void update_acid(u32 x, u32 y); void update_default(u32 x, u32 y); // Utilities for writing data into color buffer void write_data(u32 idx, particle_t); // Rendering void render_scene(); // Font methods void construct_font_data(); font_glyph_t get_glyph(font_t* f, char c); gs_vec2 calculate_mouse_position() { gs_vec2 ws = gs_platform_window_sizev(gs_platform_main_window()); gs_vec2 pmp = gs_platform_mouse_positionv(); // Need to place mouse into frame f32 x_scale = pmp.x / (f32)ws.x; f32 y_scale = pmp.y / (f32)ws.y; return (gs_vec2){x_scale * (f32)g_texture_width, y_scale * (f32)g_texture_height}; } s32 random_val(s32 lower, s32 upper) { if (upper < lower) { s32 tmp = lower; lower = upper; upper = tmp; } return (rand() % (upper - lower + 1) + lower); } s32 compute_idx(s32 x, s32 y) { return (y * g_texture_width + x); } b32 in_bounds(s32 x, s32 y) { if (x < 0 || x > (g_texture_width - 1) || y < 0 || y > (g_texture_height - 1)) return false; return true; } b32 is_empty(s32 x, s32 y) { return (in_bounds(x, y) && g_world_particle_data[compute_idx(x, y)].id == mat_id_empty); } particle_t get_particle_at(s32 x, s32 y) { return g_world_particle_data[compute_idx(x, y)]; } b32 completely_surrounded(s32 x, s32 y) { // Top if (in_bounds(x, y - 1) && !is_empty(x, y - 1)) { return false; } // Bottom if (in_bounds(x, y + 1) && !is_empty(x, y + 1)) { return false; } // Left if (in_bounds(x - 1, y) && !is_empty(x - 1, y)) { return false; } // Right if (in_bounds(x + 1, y) && !is_empty(x + 1, y)) { return false; } // Top Left if (in_bounds(x - 1, y - 1) && !is_empty(x - 1, y - 1)) { return false; } // Top Right if (in_bounds(x + 1, y - 1) && !is_empty(x + 1, y - 1)) { return false; } // Bottom Left if (in_bounds(x - 1, y + 1) && !is_empty(x - 1, y + 1)) { return false; } // Bottom Right if (in_bounds(x + 1, y + 1) && !is_empty(x + 1, y + 1)) { return false; } return true; } b32 is_in_liquid(s32 x, s32 y, s32* lx, s32* ly) { if (in_bounds(x, y) && (get_particle_at(x, y).id == mat_id_water || get_particle_at(x, y).id == mat_id_oil)) { *lx = x; *ly = y; return true; } if (in_bounds(x, y - 1) && (get_particle_at(x, y - 1).id == mat_id_water || get_particle_at(x, y - 1).id == mat_id_oil)) { *lx = x; *ly = y - 1; return true; } if (in_bounds(x, y + 1) && (get_particle_at(x, y + 1).id == mat_id_water || get_particle_at(x, y + 1).id == mat_id_oil)) { *lx = x; *ly = y + 1; return true; } if (in_bounds(x - 1, y) && (get_particle_at(x - 1, y).id == mat_id_water || get_particle_at(x - 1, y).id == mat_id_oil)) { *lx = x - 1; *ly = y; return true; } if (in_bounds(x - 1, y - 1) && (get_particle_at(x - 1, y - 1).id == mat_id_water || get_particle_at(x - 1, y - 1).id == mat_id_oil)) { *lx = x - 1; *ly = y - 1; return true; } if (in_bounds(x - 1, y + 1) && (get_particle_at(x - 1, y + 1).id == mat_id_water || get_particle_at(x - 1, y + 1).id == mat_id_oil)) { *lx = x - 1; *ly = y + 1; return true; } if (in_bounds(x + 1, y) && (get_particle_at(x + 1, y).id == mat_id_water || get_particle_at(x + 1, y).id == mat_id_oil)) { *lx = x + 1; *ly = y; return true; } if (in_bounds(x + 1, y - 1) && (get_particle_at(x + 1, y - 1).id == mat_id_water || get_particle_at(x + 1, y - 1).id == mat_id_oil)) { *lx = x + 1; *ly = y - 1; return true; } if (in_bounds(x + 1, y + 1) && (get_particle_at(x + 1, y + 1).id == mat_id_water || get_particle_at(x + 1, y + 1).id == mat_id_oil)) { *lx = x + 1; *ly = y + 1; return true; } return false; } b32 is_in_water(s32 x, s32 y, s32* lx, s32* ly) { if (in_bounds(x, y) && (get_particle_at(x, y).id == mat_id_water)) { *lx = x; *ly = y; return true; } if (in_bounds(x, y - 1) && (get_particle_at(x, y - 1).id == mat_id_water)) { *lx = x; *ly = y - 1; return true; } if (in_bounds(x, y + 1) && (get_particle_at(x, y + 1).id == mat_id_water)) { *lx = x; *ly = y + 1; return true; } if (in_bounds(x - 1, y) && (get_particle_at(x - 1, y).id == mat_id_water)) { *lx = x - 1; *ly = y; return true; } if (in_bounds(x - 1, y - 1) && (get_particle_at(x - 1, y - 1).id == mat_id_water)) { *lx = x - 1; *ly = y - 1; return true; } if (in_bounds(x - 1, y + 1) && (get_particle_at(x - 1, y + 1).id == mat_id_water)) { *lx = x - 1; *ly = y + 1; return true; } if (in_bounds(x + 1, y) && (get_particle_at(x + 1, y).id == mat_id_water)) { *lx = x + 1; *ly = y; return true; } if (in_bounds(x + 1, y - 1) && (get_particle_at(x + 1, y - 1).id == mat_id_water)) { *lx = x + 1; *ly = y - 1; return true; } if (in_bounds(x + 1, y + 1) && (get_particle_at(x + 1, y + 1).id == mat_id_water)) { *lx = x + 1; *ly = y + 1; return true; } return false; } gs_app_desc_t gs_main(int32_t argc, char** argv) { gs_app_desc_t app = {0}; app.window_title = "SandSim"; app.window_width = g_window_width; app.window_height = g_window_height; app.init = app_init; app.update = app_update; app.shutdown = app_shutdown; app.frame_rate = 60; app.enable_vsync = false; return app; } typedef struct hsv_t { f32 h; f32 s; f32 v; } hsv_t; // From on: https://gist.github.com/fairlight1337/4935ae72bcbcc1ba5c72 hsv_t rgb_to_hsv(color_t c) { gs_vec3 cv = (gs_vec3){(f32)c.r / 255.f, (f32)c.g / 255.f, (f32)c.b / 255.f}; f32 fR = cv.x, fG = cv.y, fB = cv.z; f32 fCMax = gs_max(gs_max(fR, fG), fB); f32 fCMin = gs_min(gs_min(fR, fG), fB); f32 fDelta = fCMax - fCMin; hsv_t hsv; if(fDelta > 0) { if(fCMax == fR) { hsv.h = 60 * (fmod(((fG - fB) / fDelta), 6)); } else if(fCMax == fG) { hsv.h = 60 * (((fB - fR) / fDelta) + 2); } else if(fCMax == fB) { hsv.h = 60 * (((fR - fG) / fDelta) + 4); } if(fCMax > 0) { hsv.s = fDelta / fCMax; } else { hsv.s = 0; } hsv.v = fCMax; } else { hsv.h = 0; hsv.s = 0; hsv.v = fCMax; } if(hsv.h < 0) { hsv.h = 360 + hsv.h; } return hsv; } // Implemented from: https://stackoverflow.com/questions/27374550/how-to-compare-color-object-and-get-closest-color-in-an-color // distance between two hues: f32 hue_dist(f32 h1, f32 h2) { f32 d = fabsf(h1 - h2); return d > 180.f ? 360.f - d : d; } // color brightness as perceived: f32 brightness(color_t c) { return ((f32)c.r * 0.299f + (f32)c.g * 0.587f + (f32)c.b *0.114f) / 256.f; } f32 color_num(color_t c) { const f32 bright_factor = 100.0f; const f32 sat_factor = 0.1f; hsv_t hsv = rgb_to_hsv(c); return hsv.s * sat_factor + brightness(c) * bright_factor; } #define __check_hsv(c0, c1, p_func)\ do {\ hsv_t hsv0 = rgb_to_hsv(c0);\ hsv_t hsv1 = rgb_to_hsv(c1);\ f32 d = abs(color_num(c0) - color_num(c1)) + hue_dist(hsv0.h, hsv1.h);\ if (d < min_dist) {\ min_dist = d;\ p = p_func();\ }\ } while (0) #define __check_dist_euclidean(c0, c1, p_func)\ do {\ gs_vec4 c0_vec = (gs_vec4){(f32)c0.r, c0.g, c0.b, 255.f};\ gs_vec4 c1_vec = (gs_vec4){(f32)c1.r, c1.g, c1.b, 255.f};\ f32 d = gs_vec4_dist(c0_vec, c1_vec);\ if (d < min_dist) {\ min_dist = d;\ p = p_func();\ }\ } while (0) #define __check_dist(c0, c1, p_func)\ do\ {\ f32 rd = (f32)c0.r - (f32)c1.r;\ f32 gd = (f32)c0.g - (f32)c1.g;\ f32 bd = (f32)c0.b - (f32)c1.b;\ f32 sd = rd * rd + gd * gd + bd * bd;\ f32 d = pow(rd * 0.299, 2) + pow(gd * 0.587, 2) + pow(bd * 0.114, 2);\ if (d < min_dist) {\ min_dist = d;\ p = p_func();\ }\ } while (0) particle_t get_closest_particle_from_color(color_t c) { particle_t p = particle_empty(); f32 min_dist = FLT_MAX; gs_vec4 c_vec = (gs_vec4){(f32)c.r, (f32)c.g, (f32)c.b, (f32)c.a}; u8 id = mat_id_empty; __check_dist_euclidean(c, mat_col_sand, particle_sand); __check_dist_euclidean(c, mat_col_water, particle_water); __check_dist_euclidean(c, mat_col_salt, particle_salt); __check_dist_euclidean(c, mat_col_wood, particle_wood); __check_dist_euclidean(c, mat_col_fire, particle_fire); __check_dist_euclidean(c, mat_col_smoke, particle_smoke); __check_dist_euclidean(c, mat_col_steam, particle_steam); __check_dist_euclidean(c, mat_col_gunpowder, particle_gunpowder); __check_dist_euclidean(c, mat_col_oil, particle_oil); __check_dist_euclidean(c, mat_col_lava, particle_lava); __check_dist_euclidean(c, mat_col_stone, particle_stone); __check_dist_euclidean(c, mat_col_acid, particle_acid); return p; } void drop_file_callback(void* platform_window, s32 count, const char** file_paths) { if (count < 1) return; // Just do first one for now... if (count > 1) count = 1; // We'll place at the mouse position as well, for shiggles gs_vec2 mp = calculate_mouse_position(); for (s32 i = 0; i < count; ++i) { // Need to verify this IS an image first. char temp_file_extension_buffer[16] = {0}; gs_util_get_file_extension(temp_file_extension_buffer, sizeof(temp_file_extension_buffer), file_paths[0]); if (gs_string_compare_equal(temp_file_extension_buffer, "png") || gs_string_compare_equal(temp_file_extension_buffer, "jpg") || gs_string_compare_equal(temp_file_extension_buffer, "jpeg") || gs_string_compare_equal(temp_file_extension_buffer, "bmp")) { // Load texture into memory s32 _w, _h, _n; void* texture_data = NULL; // Force texture data to 3 components gs_util_load_texture_data_from_file(file_paths[i], &_w, &_h, &_n, &texture_data, false); _n = 3; // Not sure what the format should be, so this is ...blah. Need to find a way to determine this beforehand. u8* data = (u8*)texture_data; s32 sx = (g_texture_width - _w) / 2; s32 sy = (g_texture_height - _h) / 2; // Now we need to process the data and place it into our particle/color buffers for (u32 h = 0; h < _h; ++h) { for (u32 w = 0; w < _w; ++w) { color_t c = { data[(h * _w + w) * _n + 0], data[(h * _w + w) * _n + 1], data[(h * _w + w) * _n + 2], 255 }; // Get color of this pixel in the image particle_t p = get_closest_particle_from_color(c); // Let's place this thing in the center instead... if (in_bounds(sx + w, sy + h)) { u32 idx = compute_idx(sx + w, sy + h); write_data(idx, p); } } } // Free texture data gs_free(texture_data); } } } // Here, we'll initialize all of our application data, which in this case is our graphics resources void app_init() { // Construct command buffer (the command buffer is used to allow for immediate drawing at any point in our program) g_cb = gs_command_buffer_new(); // Create shader g_shader = gs_graphics_shader_create ( &(gs_graphics_shader_desc_t) { .sources = (gs_graphics_shader_source_desc_t[]) { {.type = GS_GRAPHICS_SHADER_STAGE_VERTEX, .source = v_src}, {.type = GS_GRAPHICS_SHADER_STAGE_FRAGMENT, .source = f_src} }, .size = 2 * sizeof(gs_graphics_shader_source_desc_t), .name = "g_shader" } ); // Construct uniforms for shader u_tex = gs_graphics_uniform_create ( &(gs_graphics_uniform_desc_t) { .name = "u_tex", .layout = &(gs_graphics_uniform_layout_desc_t){.type = GS_GRAPHICS_UNIFORM_SAMPLER2D} } ); u_flip_y = gs_graphics_uniform_create ( &(gs_graphics_uniform_desc_t) { .name = "u_flip_y", .layout = &(gs_graphics_uniform_layout_desc_t){.type = GS_GRAPHICS_UNIFORM_INT} } ); // Vertex data for triangle f32 v_data[] = { // Positions UVs -1.0f, -1.0f, 0.0f, 0.0f, // Top Left 1.0f, -1.0f, 1.0f, 0.0f, // Top Right -1.0f, 1.0f, 0.0f, 1.0f, // Bottom Left 1.0f, 1.0f, 1.0f, 1.0f // Bottom Right }; u32 i_data[] = { 0, 2, 3, 3, 1, 0 }; // Construct vertex buffer g_vbo = gs_graphics_vertex_buffer_create( &(gs_graphics_vertex_buffer_desc_t) { .data = v_data, .size = sizeof(v_data) } ); // Construct index buffer g_ibo = gs_graphics_index_buffer_create( &(gs_graphics_index_buffer_desc_t) { .data = i_data, .size = sizeof(i_data) } ); // Construct world data (for now, it'll just be the size of the screen) g_world_particle_data = gs_malloc(g_texture_width * g_texture_height * sizeof(particle_t)); // Construct texture buffer data g_texture_buffer = gs_malloc(g_texture_width * g_texture_height * sizeof(color_t)); g_ui_buffer = gs_malloc(g_texture_width * g_texture_height * sizeof(color_t)); // Set buffers to 0 memset(g_texture_buffer, 0, g_texture_width * g_texture_height * sizeof(color_t)); memset(g_world_particle_data, 0, g_texture_width * g_texture_height); memset(g_ui_buffer, 0, g_texture_width * g_texture_height); // Construct texture resource from GPU gs_graphics_texture_desc_t t_desc = gs_default_val(); t_desc.format = GS_GRAPHICS_TEXTURE_FORMAT_RGBA8; t_desc.mag_filter = GS_GRAPHICS_TEXTURE_FILTER_NEAREST; t_desc.min_filter = GS_GRAPHICS_TEXTURE_FILTER_NEAREST; t_desc.num_mips = 0; t_desc.width = g_texture_width; t_desc.height = g_texture_height; t_desc.data = g_texture_buffer; g_tex = gs_graphics_texture_create(&t_desc); // Construct texture resource from GPU t_desc.data = g_ui_buffer; g_tex_ui = gs_graphics_texture_create(&t_desc); // Construct target for offscreen rendering t_desc.data = NULL; g_rt = gs_graphics_texture_create(&t_desc); // Construct frame buffer g_fb = gs_graphics_framebuffer_create(NULL); // Construct render pass g_rp = gs_graphics_render_pass_create( &(gs_graphics_render_pass_desc_t){ .fbo = g_fb, // Frame buffer to bind for render pass .color = &g_rt, // Color buffer array to bind to frame buffer .color_size = sizeof(g_rt) // Size of color attachment array in bytes } ); // Pipeline g_pip = gs_graphics_pipeline_create( &(gs_graphics_pipeline_desc_t) { .raster = { .shader = g_shader }, .blend = { .func = GS_GRAPHICS_BLEND_EQUATION_ADD, .src = GS_GRAPHICS_BLEND_MODE_SRC_ALPHA, .dst = GS_GRAPHICS_BLEND_MODE_ONE_MINUS_SRC_ALPHA }, .layout = { .attrs = (gs_graphics_vertex_attribute_desc_t[]){ {.format = GS_GRAPHICS_VERTEX_ATTRIBUTE_FLOAT2, .name = "a_position"}, // Named attribute required for lower GL versions / ES2 / ES3 {.format = GS_GRAPHICS_VERTEX_ATTRIBUTE_FLOAT2, .name = "a_texCoord"} // Named attribute required for lower GL versions / ES2 / ES3 }, .size = 2 * sizeof(gs_graphics_vertex_attribute_desc_t) } } ); // Initialize render passes g_blur_pass = blur_pass_ctor(g_fb); g_bright_pass = bright_filter_pass_ctor(g_fb); g_composite_pass = composite_pass_ctor(g_fb); // Load UI font texture data from file construct_font_data(); // Set up callback for dropping them files, yo. // platform->set_dropped_files_callback(platform->main_window(), &drop_file_callback); } void app_update() { // If we press the escape key, exit the application if (gs_platform_key_pressed(GS_KEYCODE_ESC)) { gs_engine_quit(); } // Why not print this elsewhere, yo? gs_timed_action(60, { gs_println("frame: %.5f ms", gs_engine_subsystem(platform)->time.frame); }); // All application updates b32 ui_interaction = update_ui(&g_cb); if (!ui_interaction) { update_input(&g_cb); } if (g_run_simulation) { update_particle_sim(&g_cb); } /*=============== // Render scene ================*/ render_scene(&g_cb); // Update frame counter g_frame_counter = (g_frame_counter + 1) % UINT32_MAX; } void app_shutdown() { gs_println("Goodbye, Gunslinger."); } void construct_font_data() { g_font.data = g_font_data; g_font.width = 90; g_font.height = 42; g_font.num_comps = 3; // Set up metrics g_font.glyph_advance = 1; // Construct glyph information const s32 glyph_width = 5, glyph_height = 7; for (u32 r = 0; r < 6; ++r) { for (u32 c = 0; c < 18; ++c) { u32 idx = r * 18 + c; g_font.glyphs[idx] = (font_glyph_t){c * 5, r * 7, 5, 7}; } } } font_glyph_t get_glyph(font_t* f, char c) { switch (c) { case ' ': return g_font.glyphs[0]; case '!': return g_font.glyphs[1]; case '"': return g_font.glyphs[2]; case '#': return g_font.glyphs[3]; case '$': return g_font.glyphs[4]; case '%': return g_font.glyphs[5]; case '&': return g_font.glyphs[6]; case '\'': return g_font.glyphs[7]; case '(': return g_font.glyphs[8]; case ')': return g_font.glyphs[9]; case '*': return g_font.glyphs[10]; case '+': return g_font.glyphs[11]; case ',': return g_font.glyphs[12]; case '-': return g_font.glyphs[13]; case '.': return g_font.glyphs[14]; case '/': return g_font.glyphs[15]; case '0': return g_font.glyphs[16]; case '1': return g_font.glyphs[17]; case '2': return g_font.glyphs[18]; case '3': return g_font.glyphs[19]; case '4': return g_font.glyphs[20]; case '5': return g_font.glyphs[21]; case '6': return g_font.glyphs[22]; case '7': return g_font.glyphs[23]; case '8': return g_font.glyphs[24]; case '9': return g_font.glyphs[25]; case ':': return g_font.glyphs[26]; case ';': return g_font.glyphs[27]; case '<': return g_font.glyphs[28]; case '=': return g_font.glyphs[29]; case '>': return g_font.glyphs[30]; case '?': return g_font.glyphs[31]; case '@': return g_font.glyphs[32]; case 'A': return g_font.glyphs[33]; case 'B': return g_font.glyphs[34]; case 'C': return g_font.glyphs[35]; case 'D': return g_font.glyphs[36]; case 'E': return g_font.glyphs[37]; case 'F': return g_font.glyphs[38]; case 'G': return g_font.glyphs[39]; case 'H': return g_font.glyphs[40]; case 'I': return g_font.glyphs[41]; case 'J': return g_font.glyphs[42]; case 'K': return g_font.glyphs[43]; case 'L': return g_font.glyphs[44]; case 'M': return g_font.glyphs[45]; case 'N': return g_font.glyphs[46]; case 'O': return g_font.glyphs[47]; case 'P': return g_font.glyphs[48]; case 'Q': return g_font.glyphs[49]; case 'R': return g_font.glyphs[50]; case 'S': return g_font.glyphs[51]; case 'T': return g_font.glyphs[52]; case 'U': return g_font.glyphs[53]; case 'V': return g_font.glyphs[54]; case 'W': return g_font.glyphs[55]; case 'X': return g_font.glyphs[56]; case 'Y': return g_font.glyphs[57]; case 'Z': return g_font.glyphs[58]; case '[': return g_font.glyphs[59]; case '\\': return g_font.glyphs[60]; case ']': return g_font.glyphs[61]; case '^': return g_font.glyphs[62]; case '_': return g_font.glyphs[63]; case '`': return g_font.glyphs[64]; case 'a': return g_font.glyphs[65]; case 'b': return g_font.glyphs[66]; case 'c': return g_font.glyphs[67]; case 'd': return g_font.glyphs[68]; case 'e': return g_font.glyphs[69]; case 'f': return g_font.glyphs[70]; case 'g': return g_font.glyphs[71]; case 'h': return g_font.glyphs[72]; case 'i': return g_font.glyphs[73]; case 'j': return g_font.glyphs[74]; case 'k': return g_font.glyphs[75]; case 'l': return g_font.glyphs[76]; case 'm': return g_font.glyphs[77]; case 'n': return g_font.glyphs[78]; case 'o': return g_font.glyphs[79]; case 'p': return g_font.glyphs[80]; case 'q': return g_font.glyphs[81]; case 'r': return g_font.glyphs[82]; case 's': return g_font.glyphs[83]; case 't': return g_font.glyphs[84]; case 'u': return g_font.glyphs[85]; case 'v': return g_font.glyphs[86]; case 'w': return g_font.glyphs[87]; case 'x': return g_font.glyphs[88]; case 'y': return g_font.glyphs[89]; case 'z': return g_font.glyphs[90]; case '{': return g_font.glyphs[91]; case '|': return g_font.glyphs[92]; case '}': return g_font.glyphs[93]; case '~': return g_font.glyphs[94]; // For anything not supported, just return empty space default: { return (font_glyph_t){0}; } break; } } void putpixel(int x, int y) { if (in_bounds(x, y)) { g_ui_buffer[compute_idx(x, y)] = (color_t){255, 255, 255, 255}; } } // Function to put pixels // at subsequence points void drawCircle(int xc, int yc, int x, int y) { putpixel(xc+x, yc+y); putpixel(xc-x, yc+y); putpixel(xc+x, yc-y); putpixel(xc-x, yc-y); putpixel(xc+y, yc+x); putpixel(xc-y, yc+x); putpixel(xc+y, yc-x); putpixel(xc-y, yc-x); } // Function for circle-generation // using Bresenham's algorithm void circleBres(int xc, int yc, int r) { int x = 0, y = r; int d = 3 - 2 * r; drawCircle(xc, yc, x, y); while (y >= x) { // For each pixel we will // draw all eight pixels x++; // Check for decision parameter // and correspondingly // update d, x, y if (d > 0) { y--; d = d + 4 * (x - y) + 10; } else d = d + 4 * x + 6; drawCircle(xc, yc, x, y); } } void update_input(gs_command_buffer_t* cb) { if (gs_platform_key_pressed(GS_KEYCODE_I)) { g_show_material_selection_panel = !g_show_material_selection_panel; } if (gs_platform_key_pressed(GS_KEYCODE_F)) { g_show_frame_count = !g_show_frame_count; } if (gs_platform_key_pressed(GS_KEYCODE_B)) { g_use_post_processing = !g_use_post_processing; } f32 wx = 0, wy = 0; gs_platform_mouse_wheel(&wx, &wy); if (gs_platform_key_pressed(GS_KEYCODE_LEFT_BRACKET) || wy < 0.f) { g_selection_radius = gs_clamp(g_selection_radius - 1.f, 1.f, 100.f); } if (gs_platform_key_pressed(GS_KEYCODE_RIGHT_BRACKET) || wy > 0.f) { g_selection_radius = gs_clamp(g_selection_radius + 1.f, 1.f, 100.f); } if (gs_platform_key_pressed(GS_KEYCODE_P)) { g_run_simulation = !g_run_simulation; } // Clear data if (gs_platform_key_pressed(GS_KEYCODE_C)) { memset(g_texture_buffer, 0, sizeof(color_t) * g_texture_width * g_texture_height); memset(g_world_particle_data, 0, sizeof(particle_t) * g_texture_width * g_texture_height); } // Mouse input for testing if (gs_platform_mouse_down(GS_MOUSE_LBUTTON)) { gs_vec2 mp = calculate_mouse_position(); f32 mp_x = gs_clamp(mp.x, 0.f, (f32)g_texture_width - 1.f); f32 mp_y = gs_clamp(mp.y, 0.f, (f32)g_texture_height - 1.f); u32 max_idx = (g_texture_width * g_texture_height) - 1; s32 r_amt = random_val(1, 10000); float _R = g_selection_radius; // Spawn in a circle around the mouse for (u32 i = 0; i < r_amt; ++i) { f32 ran = (f32)random_val(0, 100) / 100.f; f32 r = _R * sqrt(ran); f32 theta = (f32)random_val(0, 100)/100.f * 2.f * GS_PI; f32 rx = cos((f32)theta) * r; f32 ry = sin((f32)theta) * r; s32 mpx = (s32)gs_clamp(mp_x + (f32)rx, 0.f, (f32)g_texture_width - 1.f); s32 mpy = (s32)gs_clamp(mp_y + (f32)ry, 0.f, (f32)g_texture_height - 1.f); s32 idx = mpy * (s32)g_texture_width + mpx; idx = gs_clamp(idx, 0, max_idx); if (is_empty(mpx, mpy)) { particle_t p = {0}; switch (g_material_selection) { case mat_sel_sand: p = particle_sand(); break;; case mat_sel_water: p = particle_water(); break;; case mat_sel_salt: p = particle_salt(); break;; case mat_sel_wood: p = particle_wood(); break;; case mat_sel_fire: p = particle_fire(); break; case mat_sel_smoke: p = particle_smoke(); break; case mat_sel_steam: p = particle_steam(); break; case mat_sel_gunpowder: p = particle_gunpowder(); break; case mat_sel_oil: p = particle_oil(); break; case mat_sel_lava: p = particle_lava(); break; case mat_sel_stone: p = particle_stone(); break; case mat_sel_acid: p = particle_acid(); break; } p.velocity = (gs_vec2){random_val(-1, 1), random_val(-2, 5)}; write_data(idx, p); } } } // Solid Erase if (gs_platform_mouse_down(GS_MOUSE_RBUTTON)) { gs_vec2 mp = calculate_mouse_position(); f32 mp_x = gs_clamp(mp.x, 0.f, (f32)g_texture_width - 1.f); f32 mp_y = gs_clamp(mp.y, 0.f, (f32)g_texture_height - 1.f); u32 max_idx = (g_texture_width * g_texture_height) - 1; const f32 _R = g_selection_radius; // Erase in a circle pattern for (s32 i = -_R ; i < _R; ++i) { for (s32 j = -_R ; j < _R; ++j) { s32 rx = ((s32)mp_x + j); s32 ry = ((s32)mp_y + i); gs_vec2 r = (gs_vec2){rx, ry}; if (in_bounds(rx, ry) && gs_vec2_dist(mp, r) <= _R) { write_data(compute_idx(rx, ry), particle_empty()); } } } } // Need to detect if mouse has entered the screen with payload... } void update_particle_sim(gs_command_buffer_t* cb) { // Update frame counter (loop back to 0 if we roll past u32 max) b32 frame_counter_even = ((g_frame_counter % 2) == 0); s32 ran = frame_counter_even ? 0 : 1; const f32 dt = gs_platform_delta_time(); // Rip through read data and update write buffer // Note(John): We update "bottom up", since all the data is edited "in place". Double buffering all data would fix this // issue, however it requires double all of the data. for (u32 y = g_texture_height - 1; y > 0; --y) { for (u32 x = ran ? 0 : g_texture_width - 1; ran ? x < g_texture_width : x > 0; ran ? ++x : --x) { // Current particle idx u32 read_idx = compute_idx(x, y); // Get material of particle at point u8 mat_id = get_particle_at(x, y).id; // Update particle's lifetime (I guess just use frames)? Or should I have sublife? g_world_particle_data[read_idx].life_time += 1.f * dt; switch (mat_id) { case mat_id_sand: update_sand(x, y); break; case mat_id_water: update_water(x, y); break; case mat_id_salt: update_salt(x, y); break; case mat_id_fire: update_fire(x, y); break; case mat_id_smoke: update_smoke(x, y); break; case mat_id_ember: update_ember(x, y); break; case mat_id_steam: update_steam(x, y); break; case mat_id_gunpowder: update_gunpowder(x, y); break; case mat_id_oil: update_oil(x, y); break; case mat_id_lava: update_lava(x, y); break; case mat_id_acid: update_acid(x, y); break; // Do nothing for empty or default case default: case mat_id_empty: { // update_default(w, h, i); } break; } } } // Can remove this loop later on by keeping update structure and setting that for the particle as it moves, // then at the end of frame just memsetting the entire structure to 0. for (u32 y = g_texture_height - 1; y > 0; --y) { for (u32 x = ran ? 0 : g_texture_width - 1; ran ? x < g_texture_width : x > 0; ran ? ++x : --x) { // Set particle's update to false for next frame g_world_particle_data[compute_idx(x, y)].has_been_updated_this_frame = false; } } } void draw_glyph_at(font_t* f, color_t* buffer, s32 x, s32 y, char c, color_t col) { u8* font_data = (u8*)f->data; font_glyph_t g = get_glyph(f, c); // How to accurately place? I have width and height of glyph in texture, but need to convert this to RGBA data for ui buffer for (s32 h = 0; h < g.height; ++h) { for (s32 w = 0; w < g.width; ++w) { s32 _w = w + g.x; s32 _h = h + g.y; u8 a = font_data[(_h * f->width + _w) * f->num_comps + 0] == 0 ? 0 : 255; color_t c = { font_data[(_h * f->width + _w) * f->num_comps + 0], font_data[(_h * f->width + _w) * f->num_comps + 1], font_data[(_h * f->width + _w) * f->num_comps + 2], a }; if (in_bounds(x + w, y + h) && a) { buffer[compute_idx(x + w, y + h)] = col; } } } } void draw_string_at(font_t* f, color_t* buffer, s32 x, s32 y, const char* str, usize len, color_t col) { u8* font_data = (u8*)f->data; for (u32 i = 0; i < len; ++i) { font_glyph_t g = get_glyph(f, str[i]); draw_glyph_at(f, buffer, x, y, str[i], col); x += g.width + f->glyph_advance; // Move by glyph width + advance } } b32 in_rect (gs_vec2 p, gs_vec2 ro, gs_vec2 rd) { if (p.x < ro.x || p.x > ro.x + rd.x || p.y < ro.y || p.y > ro.y + rd.y) return false; return true; } b32 gui_rect(color_t* buffer, s32 _x, s32 _y, s32 _w, s32 _h, color_t c) { gs_vec2 mp = calculate_mouse_position(); for (u32 h = 0; h < _h; ++ h) { for (u32 w = 0; w < _w; ++w) { if (in_bounds(_x + w, _y + h)) { buffer[compute_idx(_x + w, _y + h)] = c; } } } b32 clicked = gs_platform_mouse_pressed(GS_MOUSE_LBUTTON); return in_rect(mp, (gs_vec2){_x, _y}, (gs_vec2){_w, _h}) && clicked ; } #define __gui_interaction(x, y, w, h, c, str, id)\ do {\ if ((id) == g_material_selection) {\ const s32 b = 2;\ gui_rect(g_ui_buffer, x - b / 2, y - b / 2, w + b, h + b, (color_t){200, 150, 20, 255});\ }\ gs_vec2 mp = calculate_mouse_position();\ if (in_rect(mp, (gs_vec2){(x), (y)}, (gs_vec2){(w), (h)})) {\ interaction |= true;\ char _str[] = (str);\ color_t col = (color_t){255, 255, 255, 255};\ color_t s_col = (color_t){10, 10, 10, 255};\ color_t r_col = (color_t){5, 5, 5, 170};\ /*Draw rect around text as well for easier viewing*/\ gui_rect(g_ui_buffer, g_texture_width / 2 - 50, 15, 100, 20, r_col);\ draw_string_at(&g_font, g_ui_buffer, g_texture_width / 2 + 1 - (sizeof(str) * 5) / 2, 20 - 1, _str, sizeof(_str), s_col);\ draw_string_at(&g_font, g_ui_buffer, g_texture_width / 2 - (sizeof(str) * 5) / 2, 20, _str, sizeof(_str), col);\ }\ if (gui_rect(g_ui_buffer, x, y, w, h, c)) {\ g_material_selection = id;\ }\ } while (0) b32 update_ui(gs_command_buffer_t* cb) { b32 interaction = false; // Cache transformed mouse position gs_vec2 mp = calculate_mouse_position(); // Do ui stuff memset(g_ui_buffer, 0, g_texture_width * g_texture_height * sizeof(color_t)); // Material selection panel gui if (g_show_material_selection_panel) { const s32 offset = 12; s32 xoff = 20; s32 base = 10; // Sand Selection __gui_interaction(g_texture_width - xoff, base + offset * 0, 10, 10, mat_col_sand, "Sand", mat_sel_sand); __gui_interaction(g_texture_width - xoff, base + offset * 1, 10, 10, mat_col_water, "Water", mat_sel_water); __gui_interaction(g_texture_width - xoff, base + offset * 2, 10, 10, mat_col_smoke, "Smoke", mat_sel_smoke); __gui_interaction(g_texture_width - xoff, base + offset * 3, 10, 10, mat_col_fire, "Fire", mat_sel_fire); __gui_interaction(g_texture_width - xoff, base + offset * 4, 10, 10, mat_col_steam, "Steam", mat_sel_steam); __gui_interaction(g_texture_width - xoff, base + offset * 5, 10, 10, mat_col_oil, "Oil", mat_sel_oil); __gui_interaction(g_texture_width - xoff, base + offset * 6, 10, 10, mat_col_salt, "Salt", mat_sel_salt); __gui_interaction(g_texture_width - xoff, base + offset * 7, 10, 10, mat_col_wood, "Wood", mat_sel_wood); __gui_interaction(g_texture_width - xoff, base + offset * 8, 10, 10, mat_col_stone, "Stone", mat_sel_stone); __gui_interaction(g_texture_width - xoff, base + offset * 9, 10, 10, mat_col_lava, "Lava", mat_sel_lava); __gui_interaction(g_texture_width - xoff, base + offset * 10, 10, 10, mat_col_gunpowder, "GunPowder", mat_sel_gunpowder); __gui_interaction(g_texture_width - xoff, base + offset * 11, 10, 10, mat_col_acid, "Acid", mat_sel_acid); } if (g_show_frame_count) { char frame_time_str[256]; gs_snprintf (frame_time_str, sizeof(frame_time_str), "frame: %.2f ms", gs_engine_subsystem(platform)->time.frame); draw_string_at(&g_font, g_ui_buffer, 10, 10, frame_time_str, strlen(frame_time_str), (color_t){255, 255, 255, 255}); char sim_state_str[256]; gs_snprintf (sim_state_str, sizeof(sim_state_str), "state: %s", g_run_simulation ? "running" : "paused"); draw_string_at(&g_font, g_ui_buffer, 10, 20, sim_state_str, strlen(sim_state_str), (color_t){255, 255, 255, 255}); } // Draw circle around mouse pointer s32 _R = g_selection_radius; circleBres((s32)mp.x, (s32)mp.y, _R); // Request to upload our updated texture data to GPU gs_graphics_texture_desc_t desc = gs_default_val(); desc.format = GS_GRAPHICS_TEXTURE_FORMAT_RGBA8; desc.mag_filter = GS_GRAPHICS_TEXTURE_FILTER_NEAREST; desc.min_filter = GS_GRAPHICS_TEXTURE_FILTER_NEAREST; desc.num_mips = 0; desc.width = g_texture_width; desc.height = g_texture_height; desc.data = g_ui_buffer; gs_graphics_texture_request_update(cb, g_tex_ui, &desc); return interaction; } void render_scene(gs_command_buffer_t* cb) { // Upload our updated texture data to GPU gs_graphics_texture_desc_t desc = gs_default_val(); desc.format = GS_GRAPHICS_TEXTURE_FORMAT_RGBA8; desc.mag_filter = GS_GRAPHICS_TEXTURE_FILTER_NEAREST; desc.min_filter = GS_GRAPHICS_TEXTURE_FILTER_NEAREST; desc.num_mips = 0; desc.width = g_texture_width; desc.height = g_texture_height; desc.data = g_texture_buffer; gs_graphics_texture_request_update(cb, g_tex, &desc); gs_vec2 ws = gs_platform_window_sizev(gs_platform_main_window()); b32 flip_y = false; // Render pass action for clearing the screen { gs_graphics_clear_desc_t clear = (gs_graphics_clear_desc_t){ .actions = &(gs_graphics_clear_action_t){.color = {0.1f, 0.1f, 0.1f, 1.f}} }; // Uniform buffer array gs_graphics_bind_uniform_desc_t uniforms[] = { (gs_graphics_bind_uniform_desc_t){.uniform = u_tex, .data = &g_tex, .binding = 0}, (gs_graphics_bind_uniform_desc_t){.uniform = u_flip_y, .data = &flip_y} }; // Binding descriptor for vertex buffer gs_graphics_bind_desc_t binds = { .vertex_buffers = {.desc = &(gs_graphics_bind_vertex_buffer_desc_t){.buffer = g_vbo}}, .index_buffers = {.desc = &(gs_graphics_bind_index_buffer_desc_t){.buffer = g_ibo}}, .uniforms = {.desc = uniforms, .size = sizeof(uniforms)} }; // Bind render pass, bind pipeline, set up everything... gs_graphics_begin_render_pass(cb, g_rp); gs_graphics_bind_pipeline(cb, g_pip); gs_graphics_set_viewport(cb, 0, 0, (u32)(g_texture_width), (u32)(g_texture_height)); gs_graphics_clear(cb, &clear); gs_graphics_apply_bindings(cb, &binds); gs_graphics_draw(cb, &(gs_graphics_draw_desc_t){.start = 0, .count = 6}); gs_graphics_end_render_pass(cb); } // Bind frame buffer for post processing { // Brightness pass { bright_filter_pass_parameters_t params = (bright_filter_pass_parameters_t){g_rt}; render_pass_i* p = gs_cast(render_pass_i, &g_bright_pass); p->pass(&g_cb, p, &params); } // Blur pass { blur_pass_parameters_t params = (blur_pass_parameters_t){g_bright_pass.data.rt}; render_pass_i* p = gs_cast(render_pass_i, &g_blur_pass); p->pass(&g_cb, p, &params); } // composite pass w/ gamma correction { composite_pass_parameters_t params = (composite_pass_parameters_t){g_rt, g_blur_pass.data.blur_render_target_b}; render_pass_i* p = gs_cast(render_pass_i, &g_composite_pass); p->pass(&g_cb, p, &params); } } // Back buffer Presentation { gs_graphics_clear_desc_t clear = (gs_graphics_clear_desc_t){ .actions = &(gs_graphics_clear_action_t){.color = {0.2f, 0.2f, 0.2f, 1.f}} }; b32 flip_y = true; // Binding descriptor for vertex buffer gs_graphics_bind_desc_t vbinds = { .vertex_buffers = {.desc = &(gs_graphics_bind_vertex_buffer_desc_t){.buffer = g_vbo}}, .index_buffers = {.desc = &(gs_graphics_bind_index_buffer_desc_t){.buffer = g_ibo}}, .uniforms = {.desc = &(gs_graphics_bind_uniform_desc_t){.uniform = u_flip_y, .data = &flip_y}} }; gs_vec2 fbs = gs_platform_framebuffer_sizev(gs_platform_main_window()); // Bind render pass, bind pipeline, set up everything... gs_graphics_begin_render_pass(cb, GS_GRAPHICS_RENDER_PASS_DEFAULT); gs_graphics_bind_pipeline(cb, g_pip); gs_graphics_set_viewport(cb, 0, 0, (u32)(fbs.x), (u32)(fbs.y)); gs_graphics_clear(cb, &clear); gs_graphics_apply_bindings(cb, &vbinds); gs_graphics_bind_desc_t tbind = (gs_graphics_bind_desc_t){ .uniforms = {.desc = &(gs_graphics_bind_uniform_desc_t){.uniform = u_tex, .data = &g_composite_pass.data.rt, .binding = 0}} }; gs_graphics_apply_bindings(cb, &tbind); gs_graphics_draw(cb, &(gs_graphics_draw_desc_t){.start = 0, .count = 6}); // Do UI on top tbind = (gs_graphics_bind_desc_t){ .uniforms = {.desc = &(gs_graphics_bind_uniform_desc_t){.uniform = u_tex, .data = &g_tex_ui, .binding = 0}} }; gs_graphics_apply_bindings(cb, &tbind); gs_graphics_draw(cb, &(gs_graphics_draw_desc_t){.start = 0, .count = 6}); gs_graphics_end_render_pass(cb); } // Submit command buffer for rendering gs_graphics_submit_command_buffer(&g_cb); } void write_data(u32 idx, particle_t p) { // Write into particle data for id value g_world_particle_data[idx] = p; g_texture_buffer[idx] = p.color; } void update_salt(u32 x, u32 y) { f32 dt = gs_platform_delta_time(); u32 read_idx = compute_idx(x, y); particle_t* p = &g_world_particle_data[read_idx]; u32 write_idx = read_idx; u32 fall_rate = 2; u32 spread_rate = 5; s32 lx, ly; p->velocity.y = gs_clamp(p->velocity.y + (gravity * dt), -10.f, 10.f); p->has_been_updated_this_frame = true; // If in liquid, chance to dissolve itself. if (is_in_liquid(x, y, &lx, &ly)) { if (random_val(0, 1000) == 0) { write_data(read_idx, particle_empty()); return; } } // Just check if you can move directly beneath you. If not, then reset your velocity. God, this is going to blow. // if (in_bounds(x, y + 1) && !is_empty(x, y + 1) && get_particle_at(x, y + 1).id != mat_id_water) { if (in_bounds(x, y + 1) && !is_empty(x, y + 1)) { p->velocity.y /= 2.f; } s32 r = 1; s32 l = -r; s32 u = fall_rate; s32 v_idx = compute_idx (x + (s32)p->velocity.x, y + (s32)p->velocity.y); s32 b_idx = compute_idx(x, y + u); s32 bl_idx = compute_idx(x + l, y + u); s32 br_idx = compute_idx(x + r, y + u); s32 l_idx = compute_idx(x + l, y); s32 r_idx = compute_idx(x + r, y); s32 vx = (s32)p->velocity.x, vy = (s32)p->velocity.y; if (in_bounds(x + vx, y + vy) && (is_empty(x + vx, y + vy))) { write_data(v_idx, *p); write_data(read_idx, particle_empty()); } else if (is_in_liquid(x, y, &lx, &ly) && random_val(0, 10) == 0) { particle_t tmp_b = get_particle_at(lx, ly); write_data(compute_idx(lx, ly), *p); write_data(read_idx, tmp_b); } // Simple falling, changing the velocity here ruins everything. I need to redo this entire simulation. else if (in_bounds(x, y + 1) && ((is_empty(x, y + 1)))) { u32 idx = compute_idx(x, y + 1); p->velocity.y += (gravity * dt); particle_t tmp_a = g_world_particle_data[read_idx]; particle_t tmp_b = g_world_particle_data[idx]; write_data(idx, tmp_a); write_data(read_idx, tmp_b); } else if (in_bounds(x - 1, y + 1) && (is_empty(x - 1, y + 1))) { u32 idx = compute_idx(x - 1, y + 1); p->velocity.x = random_val(0, 1) == 0 ? -1.2f : 1.2f; p->velocity.y += (gravity * dt); particle_t tmp_a = g_world_particle_data[read_idx]; particle_t tmp_b = g_world_particle_data[idx]; write_data(idx, tmp_a); write_data(read_idx, tmp_b); } else if (in_bounds(x + 1, y + 1) && (is_empty(x + 1, y + 1))) { u32 idx = compute_idx(x + 1, y + 1); p->velocity.x = random_val(0, 1) == 0 ? -1.2f : 1.2f; p->velocity.y += (gravity * dt); particle_t tmp_a = g_world_particle_data[read_idx]; particle_t tmp_b = g_world_particle_data[idx]; write_data(idx, tmp_a); write_data(read_idx, tmp_b); } } void update_sand(u32 x, u32 y) { f32 dt = gs_platform_delta_time(); // For water, same as sand, but we'll check immediate left and right as well u32 read_idx = compute_idx(x, y); particle_t* p = &g_world_particle_data[read_idx]; u32 write_idx = read_idx; u32 fall_rate = 4; p->velocity.y = gs_clamp(p->velocity.y + (gravity * dt), -10.f, 10.f); // Just check if you can move directly beneath you. If not, then reset your velocity. God, this is going to blow. if (in_bounds(x, y + 1) && !is_empty(x, y + 1) && get_particle_at(x, y + 1).id != mat_id_water) { p->velocity.y /= 2.f; } s32 vi_x = x + (s32)p->velocity.x; s32 vi_y = y + (s32)p->velocity.y; // Check to see if you can swap first with other element below you u32 b_idx = compute_idx(x, y + 1); u32 br_idx = compute_idx(x + 1, y + 1); u32 bl_idx = compute_idx(x - 1, y + 1); s32 lx, ly; particle_t tmp_a = g_world_particle_data[read_idx]; // Physics (using velocity) if (in_bounds(vi_x, vi_y) && ((is_empty(vi_x, vi_y) || (((g_world_particle_data[compute_idx(vi_x, vi_y)].id == mat_id_water) && !g_world_particle_data[compute_idx(vi_x, vi_y)].has_been_updated_this_frame && gs_vec2_len(g_world_particle_data[compute_idx(vi_x, vi_y)].velocity) - gs_vec2_len(tmp_a.velocity) > 10.f))))) { particle_t tmp_b = g_world_particle_data[compute_idx(vi_x, vi_y)]; // Try to throw water out if (tmp_b.id == mat_id_water) { s32 rx = random_val(-2, 2); tmp_b.velocity = (gs_vec2){rx, -4.f}; write_data(compute_idx(vi_x, vi_y), tmp_a); for(s32 i = -10; i < 0; ++i) { for (s32 j = -10; j < 10; ++j) { if (is_empty(vi_x + j, vi_y + i)) { write_data(compute_idx(vi_x + j, vi_y + i), tmp_b); break; } } } // Couldn't write there, so, uh, destroy it. write_data(read_idx, particle_empty()); } else if (is_empty(vi_x, vi_y)) { write_data(compute_idx(vi_x, vi_y), tmp_a); write_data(read_idx, tmp_b); } } // Simple falling, changing the velocity here ruins everything. I need to redo this entire simulation. else if (in_bounds(x, y + 1) && ((is_empty(x, y + 1) || (g_world_particle_data[b_idx].id == mat_id_water)))) { p->velocity.y += (gravity * dt); particle_t tmp_b = get_particle_at(x, y + 1); write_data(b_idx, *p); write_data(read_idx, tmp_b); } else if (in_bounds(x - 1, y + 1) && ((is_empty(x - 1, y + 1) || g_world_particle_data[bl_idx].id == mat_id_water))) { p->velocity.x = is_in_liquid(x, y, &lx, &ly) ? 0.f : random_val(0, 1) == 0 ? -1.f : 1.f; p->velocity.y += (gravity * dt); particle_t tmp_b = get_particle_at(x - 1, y + 1); write_data(bl_idx, *p); write_data(read_idx, tmp_b); } else if (in_bounds(x + 1, y + 1) && ((is_empty(x + 1, y + 1) || g_world_particle_data[br_idx].id == mat_id_water))) { p->velocity.x = is_in_liquid(x, y, &lx, &ly) ? 0.f : random_val(0, 1) == 0 ? -1.f : 1.f; p->velocity.y += (gravity * dt); particle_t tmp_b = get_particle_at(x + 1, y + 1); write_data(br_idx, *p); write_data(read_idx, tmp_b); } else if (is_in_liquid(x, y, &lx, &ly) && random_val(0, 10) == 0) { particle_t tmp_b = get_particle_at(lx, ly); write_data(compute_idx(lx, ly), *p); write_data(read_idx, tmp_b); } } void update_gunpowder(u32 x, u32 y) { f32 dt = gs_platform_delta_time(); // For water, same as sand, but we'll check immediate left and right as well u32 read_idx = compute_idx(x, y); particle_t* p = &g_world_particle_data[read_idx]; u32 write_idx = read_idx; u32 fall_rate = 4; p->velocity.y = gs_clamp(p->velocity.y + (gravity * dt), -10.f, 10.f); // p->velocity.x = gs_clamp(p->velocity.x, -5.f, 5.f); // Just check if you can move directly beneath you. If not, then reset your velocity. God, this is going to blow. if (in_bounds(x, y + 1) && !is_empty(x, y + 1) && get_particle_at(x, y + 1).id != mat_id_water) { p->velocity.y /= 2.f; // p->velocity.x /= 1.2f; } s32 vi_x = x + (s32)p->velocity.x; s32 vi_y = y + (s32)p->velocity.y; // Check to see if you can swap first with other element below you u32 b_idx = compute_idx(x, y + 1); u32 br_idx = compute_idx(x + 1, y + 1); u32 bl_idx = compute_idx(x - 1, y + 1); s32 lx, ly; particle_t tmp_a = g_world_particle_data[read_idx]; // Physics (using velocity) if (in_bounds(vi_x, vi_y) && ((is_empty(vi_x, vi_y) || (((g_world_particle_data[compute_idx(vi_x, vi_y)].id == mat_id_water) && !g_world_particle_data[compute_idx(vi_x, vi_y)].has_been_updated_this_frame && gs_vec2_len(g_world_particle_data[compute_idx(vi_x, vi_y)].velocity) - gs_vec2_len(tmp_a.velocity) > 10.f))))) { particle_t tmp_b = g_world_particle_data[compute_idx(vi_x, vi_y)]; // Try to throw water out if (tmp_b.id == mat_id_water) { s32 rx = random_val(-2, 2); tmp_b.velocity = (gs_vec2){rx, -4.f}; write_data(compute_idx(vi_x, vi_y), tmp_a); for(s32 i = -10; i < 0; ++i) { for (s32 j = -10; j < 10; ++j) { if (is_empty(vi_x + j, vi_y + i)) { write_data(compute_idx(vi_x + j, vi_y + i), tmp_b); break; } } } // Couldn't write there, so, uh, destroy it. write_data(read_idx, particle_empty()); } else if (is_empty(vi_x, vi_y)) { write_data(compute_idx(vi_x, vi_y), tmp_a); write_data(read_idx, tmp_b); } } // Simple falling, changing the velocity here ruins everything. I need to redo this entire simulation. else if (in_bounds(x, y + 1) && ((is_empty(x, y + 1) || (g_world_particle_data[b_idx].id == mat_id_water)))) { p->velocity.y += (gravity * dt); particle_t tmp_b = get_particle_at(x, y + 1); write_data(b_idx, *p); write_data(read_idx, tmp_b); } else if (in_bounds(x - 1, y + 1) && ((is_empty(x - 1, y + 1) || g_world_particle_data[bl_idx].id == mat_id_water))) { p->velocity.x = is_in_liquid(x, y, &lx, &ly) ? 0.f : random_val(0, 1) == 0 ? -1.f : 1.f; p->velocity.y += (gravity * dt); particle_t tmp_b = get_particle_at(x - 1, y + 1); write_data(bl_idx, *p); write_data(read_idx, tmp_b); } else if (in_bounds(x + 1, y + 1) && ((is_empty(x + 1, y + 1) || g_world_particle_data[br_idx].id == mat_id_water))) { p->velocity.x = is_in_liquid(x, y, &lx, &ly) ? 0.f : random_val(0, 1) == 0 ? -1.f : 1.f; p->velocity.y += (gravity * dt); particle_t tmp_b = get_particle_at(x + 1, y + 1); write_data(br_idx, *p); write_data(read_idx, tmp_b); } else if (is_in_liquid(x, y, &lx, &ly) && random_val(0, 10) == 0) { particle_t tmp_b = get_particle_at(lx, ly); write_data(compute_idx(lx, ly), *p); write_data(read_idx, tmp_b); } } void update_steam(u32 x, u32 y) { f32 dt = gs_platform_delta_time(); // For water, same as sand, but we'll check immediate left and right as well u32 read_idx = compute_idx(x, y); particle_t* p = &g_world_particle_data[read_idx]; u32 write_idx = read_idx; u32 fall_rate = 4; if (p->life_time > 10.f) { write_data(read_idx, particle_empty()); return; } if (p->has_been_updated_this_frame) { return; } p->has_been_updated_this_frame = true; // Smoke rises over time. This might cause issues, actually... p->velocity.y = gs_clamp(p->velocity.y - (gravity * dt), -2.f, 10.f); p->velocity.x = gs_clamp(p->velocity.x + (f32)random_val(-100, 100) / 100.f, -1.f, 1.f); // Change color based on life_time p->color.r = (u8)(gs_clamp((gs_interp_linear(0.f, 10.f, p->life_time) / 10.f) * 255.f, 150.f, 255.f)); p->color.g = (u8)(gs_clamp((gs_interp_linear(0.f, 10.f, p->life_time) / 10.f) * 255.f, 150.f, 255.f)); p->color.b = (u8)(gs_clamp((gs_interp_linear(0.f, 10.f, p->life_time) / 10.f) * 255.f, 150.f, 255.f)); p->color.a = (u8)(gs_clamp((gs_interp_linear(10.f, 0.f, p->life_time) / 10.f) * 255.f, 10.f, 255.f)); // Just check if you can move directly beneath you. If not, then reset your velocity. God, this is going to blow. if (in_bounds(x, y - 1) && !is_empty(x, y - 1) && get_particle_at(x, y - 1).id != mat_id_water) { p->velocity.y /= 2.f; } s32 vi_x = x + (s32)p->velocity.x; s32 vi_y = y + (s32)p->velocity.y; if (in_bounds(vi_x, vi_y) && ((is_empty(vi_x, vi_y) || get_particle_at(vi_x, vi_y).id == mat_id_water || get_particle_at(vi_x, vi_y).id == mat_id_fire))) { particle_t tmp_b = g_world_particle_data[compute_idx(vi_x, vi_y)]; // Try to throw water out if (tmp_b.id == mat_id_water) { tmp_b.has_been_updated_this_frame = true; s32 rx = random_val(-2, 2); tmp_b.velocity = (gs_vec2){rx, -3.f}; write_data(compute_idx(vi_x, vi_y), *p); write_data(read_idx, tmp_b); } else if (is_empty(vi_x, vi_y)) { write_data(compute_idx(vi_x, vi_y), *p); write_data(read_idx, tmp_b); } } // Simple falling, changing the velocity here ruins everything. I need to redo this entire simulation. else if (in_bounds(x, y - 1) && ((is_empty(x, y - 1) || (get_particle_at(x, y - 1).id == mat_id_water) || get_particle_at(x,y-1).id == mat_id_fire))) { p->velocity.y -= (gravity * dt); particle_t tmp_b = get_particle_at(x, y - 1); write_data(compute_idx(x, y - 1), *p); write_data(read_idx, tmp_b); } else if (in_bounds(x - 1, y - 1) && ((is_empty(x - 1, y - 1) || get_particle_at(x - 1, y - 1).id == mat_id_water) || get_particle_at(x-1, y-1).id == mat_id_fire)) { p->velocity.x = random_val(0, 1) == 0 ? -1.2f : 1.2f; p->velocity.y -= (gravity * dt); particle_t tmp_b = get_particle_at(x - 1, y - 1); write_data(compute_idx(x - 1, y - 1), *p); write_data(read_idx, tmp_b); } else if (in_bounds(x + 1, y - 1) && ((is_empty(x + 1, y - 1) || get_particle_at(x + 1, y - 1).id == mat_id_water) || get_particle_at(x+1, y-1).id == mat_id_fire)) { p->velocity.x = random_val(0, 1) == 0 ? -1.2f : 1.2f; p->velocity.y -= (gravity * dt); particle_t tmp_b = get_particle_at(x + 1, y - 1); write_data(compute_idx(x + 1, y - 1), *p); write_data(read_idx, tmp_b); } // Can move if in liquid else if (in_bounds(x + 1, y) && (get_particle_at(x + 1, y).id == mat_id_water )) { u32 idx = compute_idx(x + 1, y); particle_t tmp_b = g_world_particle_data[idx]; write_data(idx, *p); write_data(read_idx, tmp_b); } else if (in_bounds(x - 1, y) && (g_world_particle_data[compute_idx(x - 1, y)].id == mat_id_water)) { u32 idx = compute_idx(x - 1, y); particle_t tmp_b = g_world_particle_data[idx]; write_data(idx, *p); write_data(read_idx, tmp_b); } else { write_data(read_idx, *p); } } void update_smoke(u32 x, u32 y) { f32 dt = gs_platform_delta_time(); // For water, same as sand, but we'll check immediate left and right as well u32 read_idx = compute_idx(x, y); particle_t* p = &g_world_particle_data[read_idx]; u32 write_idx = read_idx; u32 fall_rate = 4; if (p->life_time > 10.f) { write_data(read_idx, particle_empty()); return; } if (p->has_been_updated_this_frame) { return; } p->has_been_updated_this_frame = true; // Smoke rises over time. This might cause issues, actually... p->velocity.y = gs_clamp(p->velocity.y - (gravity * dt), -2.f, 10.f); p->velocity.x = gs_clamp(p->velocity.x + (f32)random_val(-100, 100) / 100.f, -1.f, 1.f); // Change color based on life_time p->color.r = (u8)(gs_clamp((gs_interp_linear(10.f, 0.f, p->life_time * 0.5f) / 10.f) * 150.f, 0.f, 150.f)); p->color.g = (u8)(gs_clamp((gs_interp_linear(10.f, 0.f, p->life_time * 0.5f) / 10.f) * 120.f, 0.f, 120.f)); p->color.b = (u8)(gs_clamp((gs_interp_linear(10.f, 0.f, p->life_time * 0.5f) / 10.f) * 100.f, 0.f, 100.f)); // Just check if you can move directly beneath you. If not, then reset your velocity. God, this is going to blow. if (in_bounds(x, y - 1) && !is_empty(x, y - 1) && get_particle_at(x, y - 1).id != mat_id_water) { p->velocity.y /= 2.f; } s32 vi_x = x + (s32)p->velocity.x; s32 vi_y = y + (s32)p->velocity.y; // if (in_bounds(vi_x, vi_y) && ((is_empty(vi_x, vi_y) || get_particle_at(vi_x, vi_y).id == mat_id_water || get_particle_at(vi_x, vi_y).id == mat_id_fire))) { if (in_bounds(vi_x, vi_y) && get_particle_at(vi_x, vi_y).id != mat_id_smoke) { particle_t tmp_b = g_world_particle_data[compute_idx(vi_x, vi_y)]; // Try to throw water out if (tmp_b.id == mat_id_water) { tmp_b.has_been_updated_this_frame = true; s32 rx = random_val(-2, 2); tmp_b.velocity = (gs_vec2){rx, -3.f}; write_data(compute_idx(vi_x, vi_y), *p); write_data(read_idx, tmp_b); } else if (is_empty(vi_x, vi_y)) { write_data(compute_idx(vi_x, vi_y), *p); write_data(read_idx, tmp_b); } } // Simple falling, changing the velocity here ruins everything. I need to redo this entire simulation. else if (in_bounds(x, y - 1) && get_particle_at(x, y - 1).id != mat_id_smoke && get_particle_at(x, y - 1).id != mat_id_wood && get_particle_at(x, y - 1).id != mat_id_stone) { p->velocity.y -= (gravity * dt); particle_t tmp_b = get_particle_at(x, y - 1); write_data(compute_idx(x, y - 1), *p); write_data(read_idx, tmp_b); } else if (in_bounds(x - 1, y - 1) && get_particle_at(x - 1, y - 1).id != mat_id_smoke && get_particle_at(x - 1, y - 1).id != mat_id_wood && get_particle_at(x - 1, y - 1).id != mat_id_stone) { p->velocity.x = random_val(0, 1) == 0 ? -1.2f : 1.2f; p->velocity.y -= (gravity * dt); particle_t tmp_b = get_particle_at(x - 1, y - 1); write_data(compute_idx(x - 1, y - 1), *p); write_data(read_idx, tmp_b); } else if (in_bounds(x + 1, y - 1) && get_particle_at(x + 1, y - 1).id != mat_id_smoke && get_particle_at(x + 1, y - 1).id != mat_id_wood && get_particle_at(x + 1, y - 1).id != mat_id_stone) { p->velocity.x = random_val(0, 1) == 0 ? -1.2f : 1.2f; p->velocity.y -= (gravity * dt); particle_t tmp_b = get_particle_at(x + 1, y - 1); write_data(compute_idx(x + 1, y - 1), *p); write_data(read_idx, tmp_b); } // Can move if in liquid else if (in_bounds(x + 1, y) && get_particle_at(x + 1, y).id != mat_id_smoke && get_particle_at(x + 1, y).id != mat_id_wood && get_particle_at(x + 1, y).id != mat_id_stone) { u32 idx = compute_idx(x + 1, y); particle_t tmp_b = g_world_particle_data[idx]; write_data(idx, *p); write_data(read_idx, tmp_b); } else if (in_bounds(x - 1, y) && get_particle_at(x - 1, y).id != mat_id_smoke && get_particle_at(x - 1, y).id != mat_id_wood && get_particle_at(x - 1, y).id != mat_id_stone) { u32 idx = compute_idx(x - 1, y); particle_t tmp_b = g_world_particle_data[idx]; write_data(idx, *p); write_data(read_idx, tmp_b); } else { write_data(read_idx, *p); } } void update_ember(u32 x, u32 y) { f32 dt = gs_platform_delta_time(); // For water, same as sand, but we'll check immediate left and right as well u32 read_idx = compute_idx(x, y); particle_t* p = &g_world_particle_data[read_idx]; u32 write_idx = read_idx; u32 fall_rate = 4; if (p->life_time > 0.5f) { write_data(read_idx, particle_empty()); return; } if (p->has_been_updated_this_frame) { return; } p->has_been_updated_this_frame = true; p->velocity.y = gs_clamp(p->velocity.y - (gravity * dt), -2.f, 10.f); p->velocity.x = gs_clamp(p->velocity.x + (f32)random_val(-100, 100) / 100.f, -1.f, 1.f); // If directly on top of some wall, then replace it if (in_bounds(x, y + 1) && get_particle_at(x, y + 1).id == mat_id_wood && random_val(0, 200) == 0) { write_data(compute_idx(x, y + 1), particle_fire()); } else if (in_bounds(x + 1, y + 1) && get_particle_at(x + 1, y + 1).id == mat_id_wood && random_val(0, 200) == 0) { write_data(compute_idx(x + 1, y + 1), particle_fire()); } else if (in_bounds(x - 1, y + 1) && get_particle_at(x - 1, y + 1).id == mat_id_wood && random_val(0, 200) == 0) { write_data(compute_idx(x - 1, y + 1), particle_fire()); } else if (in_bounds(x - 1, y) && get_particle_at(x - 1, y).id == mat_id_wood && random_val(0, 200) == 0) { write_data(compute_idx(x - 1, y), particle_fire()); } else if (in_bounds(x + 1, y) && get_particle_at(x + 1, y).id == mat_id_wood && random_val(0, 200) == 0) { write_data(compute_idx(x + 1, y), particle_fire()); } else if (in_bounds(x + 1, y - 1) && get_particle_at(x + 1, y - 1).id == mat_id_wood && random_val(0, 200) == 0) { write_data(compute_idx(x + 1, y - 1), particle_fire()); } else if (in_bounds(x - 1, y - 1) && get_particle_at(x - 1, y - 1).id == mat_id_wood && random_val(0, 200) == 0) { write_data(compute_idx(x - 1, y - 1), particle_fire()); } // Just check if you can move directly beneath you. If not, then reset your velocity. God, this is going to blow. if (in_bounds(x, y - 1) && !is_empty(x, y - 1) && get_particle_at(x, y - 1).id != mat_id_water) { p->velocity.y /= 2.f; } s32 vi_x = x + (s32)p->velocity.x; s32 vi_y = y + (s32)p->velocity.y; if (in_bounds(vi_x, vi_y) && (is_empty(vi_x, vi_y) || get_particle_at(vi_x, vi_y).id == mat_id_water || get_particle_at(vi_x, vi_y).id == mat_id_fire || get_particle_at(vi_x, vi_y).id == mat_id_smoke || get_particle_at(vi_x, vi_y).id == mat_id_ember)) { particle_t tmp_b = g_world_particle_data[compute_idx(vi_x, vi_y)]; // Try to throw water out if (tmp_b.id == mat_id_water) { tmp_b.has_been_updated_this_frame = true; s32 rx = random_val(-2, 2); tmp_b.velocity = (gs_vec2){rx, -3.f}; write_data(compute_idx(vi_x, vi_y), *p); write_data(read_idx, tmp_b); } else if (is_empty(vi_x, vi_y)) { write_data(compute_idx(vi_x, vi_y), *p); write_data(read_idx, tmp_b); } } // Simple falling, changing the velocity here ruins everything. I need to redo this entire simulation. else if (in_bounds(x, y - 1) && ((is_empty(x, y - 1) || (get_particle_at(x, y - 1).id == mat_id_water) || get_particle_at(x,y-1).id == mat_id_fire))) { p->velocity.y -= (gravity * dt); particle_t tmp_b = get_particle_at(x, y - 1); write_data(compute_idx(x, y - 1), *p); write_data(read_idx, tmp_b); } else if (in_bounds(x - 1, y - 1) && ((is_empty(x - 1, y - 1) || get_particle_at(x - 1, y - 1).id == mat_id_water) || get_particle_at(x-1, y-1).id == mat_id_fire)) { p->velocity.x = random_val(0, 1) == 0 ? -1.2f : 1.2f; p->velocity.y -= (gravity * dt); particle_t tmp_b = get_particle_at(x - 1, y - 1); write_data(compute_idx(x - 1, y - 1), *p); write_data(read_idx, tmp_b); } else if (in_bounds(x + 1, y - 1) && ((is_empty(x + 1, y - 1) || get_particle_at(x + 1, y - 1).id == mat_id_water) || get_particle_at(x+1, y+1).id == mat_id_fire)) { p->velocity.x = random_val(0, 1) == 0 ? -1.2f : 1.2f; p->velocity.y -= (gravity * dt); particle_t tmp_b = get_particle_at(x + 1, y - 1); write_data(compute_idx(x + 1, y - 1), *p); write_data(read_idx, tmp_b); } // Can move if in liquid else if (in_bounds(x + 1, y) && (is_empty(x + 1, y) || get_particle_at(x + 1, y).id == mat_id_fire )) { u32 idx = compute_idx(x + 1, y); particle_t tmp_b = g_world_particle_data[idx]; write_data(idx, *p); write_data(read_idx, tmp_b); } else if (in_bounds(x - 1, y) && (is_empty(x - 1, y) || get_particle_at(x - 1, y).id == mat_id_fire)) { u32 idx = compute_idx(x - 1, y); particle_t tmp_b = g_world_particle_data[idx]; write_data(idx, *p); write_data(read_idx, tmp_b); } else { write_data(read_idx, *p); } } void update_fire(u32 x, u32 y) { f32 dt = gs_platform_delta_time(); // For water, same as sand, but we'll check immediate left and right as well u32 read_idx = compute_idx(x, y); particle_t* p = &g_world_particle_data[read_idx]; u32 write_idx = read_idx; u32 fall_rate = 4; if (p->has_been_updated_this_frame) { return; } p->has_been_updated_this_frame = true; if (p->life_time > 0.2f) { if (random_val(0, 100) == 0) { write_data(read_idx, particle_empty()); return; } } f32 st = sin(gs_platform_elapsed_time()); // f32 grav_mul = random_val(0, 10) == 0 ? 2.f : 1.f; p->velocity.y = gs_clamp(p->velocity.y - ((gravity * dt)) * 0.2f , -5.0f, 0.f); // p->velocity.x = gs_clamp(st, -1.f, 1.f); p->velocity.x = gs_clamp(p->velocity.x + (f32)random_val(-100, 100) / 200.f, -0.5f, 0.5f); // Change color based on life_time if (random_val(0, (s32)(p->life_time * 100.f)) % 200 == 0) { s32 ran = random_val(0, 3); switch (ran) { case 0: p->color = (color_t){255, 80, 20, 255}; break; case 1: p->color = (color_t){250, 150, 10, 255}; break; case 2: p->color = (color_t){200, 150, 0, 255}; break; case 3: p->color = (color_t){100, 50, 2, 255}; break; } } if (p->life_time < 0.02f) { p->color.r = 200; } else { p->color.r = 255; } // In water, so create steam and DIE // Should also kill the water... s32 lx, ly; if (is_in_water(x, y, &lx, &ly)) { if (random_val(0, 1) == 0) { s32 ry = random_val(-5, -1); s32 rx = random_val(-5, 5); for (s32 i = ry; i > -5; --i) { for (s32 j = rx; j < 5; ++j) { particle_t p = particle_steam(); if (in_bounds(x + j, y + i) && is_empty(x + j, y + i)) { particle_t p = particle_steam(); write_data(compute_idx(x + j, y + i), p); } } } particle_t p = particle_steam(); write_data(read_idx, particle_empty()); write_data(read_idx, p); write_data(compute_idx(lx, ly), particle_empty()); return; } } // Just check if you can move directly beneath you. If not, then reset your velocity. God, this is going to blow. if (in_bounds(x, y + 1) && !is_empty(x, y + 1) && (get_particle_at(x, y + 1).id != mat_id_water || get_particle_at(x, y + 1).id != mat_id_smoke)) { p->velocity.y /= 2.f; } if (random_val(0, 10) == 0) { // p->velocity.x = gs_clamp(p->velocity.x + (f32)random_val(-1, 1) / 2.f, -1.f, 1.f); } // p->velocity.x = gs_clamp(p->velocity.x, -0.5f, 0.5f); // Kill fire underneath if (in_bounds(x, y + 3) && get_particle_at(x, y + 3).id == mat_id_fire && random_val(0, 100) == 0) { write_data(compute_idx(x, y +3), *p); write_data(read_idx, particle_empty()); return; } // Chance to kick itself up (to simulate flames) if (in_bounds(x, y + 1) && get_particle_at(x, y + 1).id == mat_id_fire && in_bounds(x, y - 1) && get_particle_at(x, y - 1).id == mat_id_empty) { if (random_val(0, 10) == 0 * p->life_time < 10.f && p->life_time > 1.f) { s32 r = random_val(0, 1); s32 rh = random_val(-10, -1); s32 spread = 3; for (s32 i = rh; i < 0; ++i) { for (s32 j = r ? -spread : spread; r ? j < spread : j > -spread; r ? ++j : --j) { s32 rx = j, ry = i; if (in_bounds(x + rx, y + ry) && is_empty(x + rx, y + ry)) { write_data(compute_idx(x + rx, y + ry), *p); write_data(read_idx, particle_empty()); break; } } } } return; } s32 vi_x = x + (s32)p->velocity.x; s32 vi_y = y + (s32)p->velocity.y; // Check to see if you can swap first with other element below you u32 b_idx = compute_idx(x, y + 1); u32 br_idx = compute_idx(x + 1, y + 1); u32 bl_idx = compute_idx(x - 1, y + 1); const s32 wood_chance = 100; const s32 gun_powder_chance = 1; const s32 oil_chance = 5; // Chance to spawn smoke above for (u32 i = 0; i < random_val(1, 10); ++i) { if (random_val(0, 500) == 0) { if (in_bounds(x, y - 1) && is_empty(x, y - 1)) { write_data(compute_idx(x, y - 1), particle_smoke()); } else if (in_bounds(x + 1, y - 1) && is_empty(x + 1, y - 1)) { write_data(compute_idx(x + 1, y - 1), particle_smoke()); } else if (in_bounds(x - 1, y - 1) && is_empty(x - 1, y - 1)) { write_data(compute_idx(x - 1, y - 1), particle_smoke()); } } } // Spawn embers if (random_val(0, 250) == 0 && p->life_time < 3.f) { for (u32 i = 0; i < random_val(1, 100); ++i) { if (in_bounds(x, y - 1) && is_empty(x, y - 1)) { particle_t e = particle_ember(); e.velocity = (gs_vec2){(f32)random_val(-5, 5) / 5.f, -(f32)random_val(2, 10) / 10.f}; write_data(compute_idx(x, y - 1), e); } else if (in_bounds(x + 1, y - 1) && is_empty(x + 1, y - 1)) { particle_t e = particle_ember(); e.velocity = (gs_vec2){(f32)random_val(-5, 5) / 5.f, -(f32)random_val(2, 10) / 10.f}; write_data(compute_idx(x + 1, y - 1), e); } else if (in_bounds(x - 1, y - 1) && is_empty(x - 1, y - 1)) { particle_t e = particle_ember(); e.velocity = (gs_vec2){(f32)random_val(-5, 5) / 5.f, -(f32)random_val(2, 10) / 10.f}; write_data(compute_idx(x - 1, y - 1), e); } } } // If directly on top of some wall, then replace it if (in_bounds(x, y + 1) && ((get_particle_at(x, y + 1).id == mat_id_wood && random_val(0, wood_chance) == 0) || (get_particle_at(x, y + 1).id == mat_id_gunpowder && random_val(0, gun_powder_chance) == 0) || (get_particle_at(x, y + 1).id == mat_id_oil && random_val(0, oil_chance) == 0) )) { write_data(compute_idx(x, y + 1), particle_fire()); if (random_val(0, 5) == 0) { s32 r = random_val(0, 1); for (s32 i = -3; i < 2; ++i) { for (s32 j = r ? -3 : 2; r ? j < 2 : j > -3; r ? ++j : --j) { s32 rx = j, ry = i; if (in_bounds(x + rx, y + ry) && is_empty(x + rx, y + ry)) { // particle_t fp = particle_fire(); p->life_time += 0.1f; write_data(compute_idx(x + rx, y + ry), *p); write_data(read_idx, particle_empty()); break; } } } } } else if (in_bounds(x + 1, y + 1) && ((get_particle_at(x + 1, y + 1).id == mat_id_wood && random_val(0, wood_chance) == 0) || (get_particle_at(x + 1, y + 1).id == mat_id_gunpowder && random_val(0, gun_powder_chance) == 0) || (get_particle_at(x + 1, y + 1).id == mat_id_oil && random_val(0, oil_chance) == 0) )) { write_data(compute_idx(x + 1, y + 1), particle_fire()); if (random_val(0, 5) == 0) { s32 r = random_val(0, 1); for (s32 i = -3; i < 2; ++i) { for (s32 j = r ? -3 : 2; r ? j < 2 : j > -3; r ? ++j : --j) { s32 rx = j, ry = i; if (in_bounds(x + rx, y + ry) && is_empty(x + rx, y + ry)) { // particle_t fp = particle_fire(); p->life_time += 0.1f; write_data(compute_idx(x + rx, y + ry), *p); write_data(read_idx, particle_empty()); break; } } } } } else if (in_bounds(x - 1, y + 1) && ((get_particle_at(x - 1, y + 1).id == mat_id_wood && random_val(0, wood_chance) == 0) || (get_particle_at(x - 1, y + 1).id == mat_id_gunpowder && random_val(0, gun_powder_chance) == 0) || (get_particle_at(x - 1, y + 1).id == mat_id_oil && random_val(0, oil_chance) == 0) )) { write_data(compute_idx(x - 1, y + 1), particle_fire()); if (random_val(0, 5) == 0) { s32 r = random_val(0, 1); for (s32 i = -3; i < 2; ++i) { for (s32 j = r ? -3 : 2; r ? j < 2 : j > -3; r ? ++j : --j) { s32 rx = j, ry = i; if (in_bounds(x + rx, y + ry) && is_empty(x + rx, y + ry)) { // particle_t fp = particle_fire(); p->life_time += 0.1f; write_data(compute_idx(x + rx, y + ry), *p); write_data(read_idx, particle_empty()); break; } } } } } else if (in_bounds(x - 1, y) && ((get_particle_at(x - 1, y).id == mat_id_wood && random_val(0, wood_chance) == 0) || (get_particle_at(x - 1, y).id == mat_id_gunpowder && random_val(0, gun_powder_chance) == 0) || (get_particle_at(x - 1, y).id == mat_id_oil && random_val(0, oil_chance) == 0) )) { write_data(compute_idx(x - 1, y), particle_fire()); if (random_val(0, 5) == 0) { s32 r = random_val(0, 1); for (s32 i = -3; i < 2; ++i) { for (s32 j = r ? -3 : 2; r ? j < 2 : j > -3; r ? ++j : --j) { s32 rx = j, ry = i; if (in_bounds(x + rx, y + ry) && is_empty(x + rx, y + ry)) { // particle_t fp = particle_fire(); p->life_time += 0.1f; write_data(compute_idx(x + rx, y + ry), *p); write_data(read_idx, particle_empty()); break; } } } } } else if (in_bounds(x + 1, y) && ((get_particle_at(x + 1, y).id == mat_id_wood && random_val(0, wood_chance) == 0) || (get_particle_at(x + 1, y).id == mat_id_gunpowder && random_val(0, gun_powder_chance) == 0) || (get_particle_at(x + 1, y).id == mat_id_oil && random_val(0, oil_chance) == 0) )) { write_data(compute_idx(x + 1, y), particle_fire()); if (random_val(0, 5) == 0) { s32 r = random_val(0, 1); for (s32 i = -3; i < 2; ++i) { for (s32 j = r ? -3 : 2; r ? j < 2 : j > -3; r ? ++j : --j) { s32 rx = j, ry = i; if (in_bounds(x + rx, y + ry) && is_empty(x + rx, y + ry)) { // particle_t fp = particle_fire(); p->life_time += 0.1f; write_data(compute_idx(x + rx, y + ry), *p); write_data(read_idx, particle_empty()); break; } } } } } else if (in_bounds(x + 1, y - 1) && ((get_particle_at(x + 1, y - 1).id == mat_id_wood && random_val(0, wood_chance) == 0) || (get_particle_at(x + 1, y - 1).id == mat_id_gunpowder && random_val(0, gun_powder_chance) == 0) || (get_particle_at(x + 1, y - 1).id == mat_id_oil && random_val(0, oil_chance) == 0) )) { write_data(compute_idx(x + 1, y - 1), particle_fire()); if (random_val(0, 5) == 0) { s32 r = random_val(0, 1); for (s32 i = -3; i < 2; ++i) { for (s32 j = r ? -3 : 2; r ? j < 2 : j > -3; r ? ++j : --j) { s32 rx = j, ry = i; if (in_bounds(x + rx, y + ry) && is_empty(x + rx, y + ry)) { // particle_t fp = particle_fire(); p->life_time += 0.1f; write_data(compute_idx(x + rx, y + ry), *p); write_data(read_idx, particle_empty()); break; } } } } } else if (in_bounds(x - 1, y - 1) && ((get_particle_at(x - 1, y - 1).id == mat_id_wood && random_val(0, wood_chance) == 0) || (get_particle_at(x - 1, y - 1).id == mat_id_gunpowder && random_val(0, gun_powder_chance) == 0) || (get_particle_at(x - 1, y - 1).id == mat_id_oil && random_val(0, oil_chance) == 0) )) { write_data(compute_idx(x - 1, y - 1), particle_fire()); if (random_val(0, 5) == 0) { s32 r = random_val(0, 1); for (s32 i = -3; i < 2; ++i) { for (s32 j = r ? -3 : 2; r ? j < 2 : j > -3; r ? ++j : --j) { s32 rx = j, ry = i; if (in_bounds(x + rx, y + ry) && is_empty(x + rx, y + ry)) { // particle_t fp = particle_fire(); p->life_time += 0.1f; write_data(compute_idx(x + rx, y + ry), *p); write_data(read_idx, particle_empty()); break; } } } } } else if (in_bounds(x, y - 1) && is_empty(x, y - 1)) { if (random_val(0, 50) == 0) { write_data(read_idx, particle_empty()); return; } } if (in_bounds(vi_x, vi_y) && (is_empty(vi_x, vi_y) || get_particle_at(vi_x, vi_y).id == mat_id_fire || get_particle_at(vi_x, vi_y).id == mat_id_smoke)) { // p->velocity.y -= (gravity * dt); particle_t tmp_b = g_world_particle_data[compute_idx(vi_x, vi_y)]; write_data(compute_idx(vi_x, vi_y), *p); write_data(read_idx, tmp_b); } // Simple falling, changing the velocity here ruins everything. I need to redo this entire simulation. else if (in_bounds(x, y + 1) && ((is_empty(x, y + 1) || (g_world_particle_data[b_idx].id == mat_id_water)))) { // p->velocity.y -= (gravity * dt); // p->velocity.x = random_val(0, 1) == 0 ? -1.f : 1.f; particle_t tmp_b = g_world_particle_data[b_idx]; write_data(b_idx, *p); write_data(read_idx, tmp_b); } else if (in_bounds(x - 1, y + 1) && ((is_empty(x - 1, y + 1) || g_world_particle_data[bl_idx].id == mat_id_water))) { // p->velocity.x = random_val(0, 1) == 0 ? -1.f : 1.f; // p->velocity.y -= (gravity * dt); particle_t tmp_b = g_world_particle_data[bl_idx]; write_data(bl_idx, *p); write_data(read_idx, tmp_b); } else if (in_bounds(x + 1, y + 1) && ((is_empty(x + 1, y + 1) || g_world_particle_data[br_idx].id == mat_id_water))) { // p->velocity.x = random_val(0, 1) == 0 ? -1.f : 1.f; // p->velocity.y -= (gravity * dt); particle_t tmp_b = g_world_particle_data[br_idx]; write_data(br_idx, *p); write_data(read_idx, tmp_b); } else if (in_bounds(x - 1, y - 1) && (g_world_particle_data[compute_idx(x - 1, y - 1)].id == mat_id_water )) { u32 idx = compute_idx(x - 1, y - 1); // p->velocity.x = random_val(0, 1) == 0 ? -1.f : 1.f; particle_t tmp_b = g_world_particle_data[idx]; write_data(idx, *p); write_data(read_idx, tmp_b); } else if (in_bounds(x + 1, y - 1) && (g_world_particle_data[compute_idx(x + 1, y - 1)].id == mat_id_water )) { u32 idx = compute_idx(x + 1, y - 1); // p->velocity.x = random_val(0, 1) == 0 ? -1.f : 1.f; particle_t tmp_b = g_world_particle_data[idx]; write_data(idx, *p); write_data(read_idx, tmp_b); } else if (in_bounds(x, y - 1) && (g_world_particle_data[compute_idx(x, y - 1)].id == mat_id_water )) { u32 idx = compute_idx(x, y - 1); // p->velocity.x = random_val(0, 1) == 0 ? -1.f : 1.f; particle_t tmp_b = g_world_particle_data[idx]; write_data(idx, *p); write_data(read_idx, tmp_b); } else { // p->velocity.x = random_val(0, 1) == 0 ? -1.f : 1.f; write_data(read_idx, *p); } } void update_lava(u32 x, u32 y) { f32 dt = gs_platform_delta_time(); // For water, same as sand, but we'll check immediate left and right as well u32 read_idx = compute_idx(x, y); particle_t* p = &g_world_particle_data[read_idx]; u32 write_idx = read_idx; u32 fall_rate = 4; if (p->has_been_updated_this_frame) { return; } p->has_been_updated_this_frame = true; p->velocity.y = gs_clamp(p->velocity.y + ((gravity * dt)), -10.f, 10.f); // Change color based on life_time if (random_val(0, (s32)(p->life_time * 100.f)) % 200 == 0) { s32 ran = random_val(0, 3); switch (ran) { case 0: p->color = (color_t){255, 80, 20, 255}; break; case 1: p->color = (color_t){255, 100, 10, 255}; break; case 2: p->color = (color_t){255, 50, 0, 255}; break; case 3: p->color = (color_t){200, 50, 2, 255}; break; } } // In water, so create steam and DIE // Should also kill the water... s32 lx, ly; if (is_in_water(x, y, &lx, &ly)) { if (random_val(0, 1) == 0) { s32 ry = random_val(-5, -1); s32 rx = random_val(-5, 5); for (s32 i = ry; i > -5; --i) { for (s32 j = rx; j < 5; ++j) { particle_t p = particle_steam(); if (in_bounds(x + j, y + i) && is_empty(x + j, y + i)) { particle_t p = particle_steam(); write_data(compute_idx(x + j, y + i), p); } } } particle_t p = particle_steam(); write_data(read_idx, particle_empty()); write_data(read_idx, p); write_data(compute_idx(lx, ly), particle_stone()); return; } } // Otherwise destroy anything that isn't fire or lava...eventually... // Just check if you can move directly beneath you. If not, then reset your velocity. God, this is going to blow. if (in_bounds(x, y + 1) && !is_empty(x, y + 1) && (get_particle_at(x, y + 1).id != mat_id_water || get_particle_at(x, y + 1).id != mat_id_smoke)) { p->velocity.y /= 2.f; } s32 vi_x = x + (s32)p->velocity.x; s32 vi_y = y + (s32)p->velocity.y; const s32 spread_rate = 1; s32 ran = random_val(0, 1); s32 r = spread_rate; s32 l = -r; s32 u = fall_rate; s32 v_idx = compute_idx (x + (s32)p->velocity.x, y + (s32)p->velocity.y); s32 b_idx = compute_idx(x, y + u); s32 bl_idx = compute_idx(x + l, y + u); s32 br_idx = compute_idx(x + r, y + u); s32 l_idx = compute_idx(x + l, y); s32 r_idx = compute_idx(x + r, y); s32 vx = (s32)p->velocity.x, vy = (s32)p->velocity.y; const s32 wood_chance = 200; const s32 gun_powder_chance = 0; const s32 oil_chance = 5; // Chance to spawn smoke above for (u32 i = 0; i < random_val(1, 10); ++i) { if (random_val(0, 500) == 0) { if (in_bounds(x, y - 1) && is_empty(x, y - 1)) { write_data(compute_idx(x, y - 1), particle_smoke()); } else if (in_bounds(x + 1, y - 1) && is_empty(x + 1, y - 1)) { write_data(compute_idx(x + 1, y - 1), particle_smoke()); } else if (in_bounds(x - 1, y - 1) && is_empty(x - 1, y - 1)) { write_data(compute_idx(x - 1, y - 1), particle_smoke()); } } } // Spawn embers if (random_val(0, 250) == 0 && p->life_time < 3.f) { for (u32 i = 0; i < random_val(1, 100); ++i) { if (in_bounds(x, y - 1) && is_empty(x, y - 1)) { particle_t e = particle_ember(); e.velocity = (gs_vec2){(f32)random_val(-5, 5) / 5.f, -(f32)random_val(2, 10) / 2.f}; write_data(compute_idx(x, y - 1), e); } else if (in_bounds(x + 1, y - 1) && is_empty(x + 1, y - 1)) { particle_t e = particle_ember(); e.velocity = (gs_vec2){(f32)random_val(-5, 5) / 5.f, -(f32)random_val(2, 10) / 2.f}; write_data(compute_idx(x + 1, y - 1), e); } else if (in_bounds(x - 1, y - 1) && is_empty(x - 1, y - 1)) { particle_t e = particle_ember(); e.velocity = (gs_vec2){(f32)random_val(-5, 5) / 5.f, -(f32)random_val(2, 10) / 2.f}; write_data(compute_idx(x - 1, y - 1), e); } } } // If directly on top of some wall, then replace it if (in_bounds(x, y + 1) && ((get_particle_at(x, y + 1).id == mat_id_wood && random_val(0, wood_chance) == 0) || (get_particle_at(x, y + 1).id == mat_id_gunpowder && random_val(0, gun_powder_chance) == 0) || (get_particle_at(x, y + 1).id == mat_id_oil && random_val(0, oil_chance) == 0) )) { write_data(compute_idx(x, y + 1), particle_fire()); if (random_val(0, 5) == 0) { s32 r = random_val(0, 1); for (s32 i = -3; i < 2; ++i) { for (s32 j = r ? -3 : 2; r ? j < 2 : j > -3; r ? ++j : --j) { s32 rx = j, ry = i; if (in_bounds(x + rx, y + ry) && is_empty(x + rx, y + ry)) { particle_t fp = particle_fire(); p->life_time += 0.1f; write_data(compute_idx(x + rx, y + ry), fp); // write_data(read_idx, particle_empty()); break; } } } } } else if (in_bounds(x + 1, y + 1) && ((get_particle_at(x + 1, y + 1).id == mat_id_wood && random_val(0, wood_chance) == 0) || (get_particle_at(x + 1, y + 1).id == mat_id_gunpowder && random_val(0, gun_powder_chance) == 0) || (get_particle_at(x + 1, y + 1).id == mat_id_oil && random_val(0, oil_chance) == 0) )) { write_data(compute_idx(x + 1, y + 1), particle_fire()); if (random_val(0, 5) == 0) { s32 r = random_val(0, 1); for (s32 i = -3; i < 2; ++i) { for (s32 j = r ? -3 : 2; r ? j < 2 : j > -3; r ? ++j : --j) { s32 rx = j, ry = i; if (in_bounds(x + rx, y + ry) && is_empty(x + rx, y + ry)) { particle_t fp = particle_fire(); p->life_time += 0.1f; write_data(compute_idx(x + rx, y + ry), fp); break; } } } } } else if (in_bounds(x - 1, y + 1) && ((get_particle_at(x - 1, y + 1).id == mat_id_wood && random_val(0, wood_chance) == 0) || (get_particle_at(x - 1, y + 1).id == mat_id_gunpowder && random_val(0, gun_powder_chance) == 0) || (get_particle_at(x - 1, y + 1).id == mat_id_oil && random_val(0, oil_chance) == 0) )) { write_data(compute_idx(x - 1, y + 1), particle_fire()); if (random_val(0, 5) == 0) { s32 r = random_val(0, 1); for (s32 i = -3; i < 2; ++i) { for (s32 j = r ? -3 : 2; r ? j < 2 : j > -3; r ? ++j : --j) { s32 rx = j, ry = i; if (in_bounds(x + rx, y + ry) && is_empty(x + rx, y + ry)) { particle_t fp = particle_fire(); p->life_time += 0.1f; write_data(compute_idx(x + rx, y + ry), fp); break; } } } } } else if (in_bounds(x - 1, y) && ((get_particle_at(x - 1, y).id == mat_id_wood && random_val(0, wood_chance) == 0) || (get_particle_at(x - 1, y).id == mat_id_gunpowder && random_val(0, gun_powder_chance) == 0) || (get_particle_at(x - 1, y).id == mat_id_oil && random_val(0, oil_chance) == 0) )) { write_data(compute_idx(x - 1, y), particle_fire()); if (random_val(0, 5) == 0) { s32 r = random_val(0, 1); for (s32 i = -3; i < 2; ++i) { for (s32 j = r ? -3 : 2; r ? j < 2 : j > -3; r ? ++j : --j) { s32 rx = j, ry = i; if (in_bounds(x + rx, y + ry) && is_empty(x + rx, y + ry)) { particle_t fp = particle_fire(); p->life_time += 0.1f; write_data(compute_idx(x + rx, y + ry), fp); break; } } } } } else if (in_bounds(x + 1, y) && ((get_particle_at(x + 1, y).id == mat_id_wood && random_val(0, wood_chance) == 0) || (get_particle_at(x + 1, y).id == mat_id_gunpowder && random_val(0, gun_powder_chance) == 0) || (get_particle_at(x + 1, y).id == mat_id_oil && random_val(0, oil_chance) == 0) )) { write_data(compute_idx(x + 1, y), particle_fire()); if (random_val(0, 5) == 0) { s32 r = random_val(0, 1); for (s32 i = -3; i < 2; ++i) { for (s32 j = r ? -3 : 2; r ? j < 2 : j > -3; r ? ++j : --j) { s32 rx = j, ry = i; if (in_bounds(x + rx, y + ry) && is_empty(x + rx, y + ry)) { particle_t fp = particle_fire(); p->life_time += 0.1f; write_data(compute_idx(x + rx, y + ry), fp); break; } } } } } else if (in_bounds(x + 1, y - 1) && ((get_particle_at(x + 1, y - 1).id == mat_id_wood && random_val(0, wood_chance) == 0) || (get_particle_at(x + 1, y - 1).id == mat_id_gunpowder && random_val(0, gun_powder_chance) == 0) || (get_particle_at(x + 1, y - 1).id == mat_id_oil && random_val(0, oil_chance) == 0) )) { write_data(compute_idx(x + 1, y - 1), particle_fire()); if (random_val(0, 5) == 0) { s32 r = random_val(0, 1); for (s32 i = -3; i < 2; ++i) { for (s32 j = r ? -3 : 2; r ? j < 2 : j > -3; r ? ++j : --j) { s32 rx = j, ry = i; if (in_bounds(x + rx, y + ry) && is_empty(x + rx, y + ry)) { particle_t fp = particle_fire(); p->life_time += 0.1f; write_data(compute_idx(x + rx, y + ry), fp); break; } } } } } else if (in_bounds(x - 1, y - 1) && ((get_particle_at(x - 1, y - 1).id == mat_id_wood && random_val(0, wood_chance) == 0) || (get_particle_at(x - 1, y - 1).id == mat_id_gunpowder && random_val(0, gun_powder_chance) == 0) || (get_particle_at(x - 1, y - 1).id == mat_id_oil && random_val(0, oil_chance) == 0) )) { write_data(compute_idx(x - 1, y - 1), particle_fire()); if (random_val(0, 5) == 0) { s32 r = random_val(0, 1); for (s32 i = -3; i < 2; ++i) { for (s32 j = r ? -3 : 2; r ? j < 2 : j > -3; r ? ++j : --j) { s32 rx = j, ry = i; if (in_bounds(x + rx, y + ry) && is_empty(x + rx, y + ry)) { particle_t fp = particle_fire(); p->life_time += 0.1f; write_data(compute_idx(x + rx, y + ry), fp); break; } } } } } // If in water, then need to float upwards // s32 lx, ly; // if (is_in_liquid(x, y, &lx, &ly) && in_bounds(x, y - 1) && get_particle_at(x, y - 1).id == mat_id_water) { // particle_t tmp = get_particle_at(x, y - 1); // write_data(compute_idx(x, y - 1), *p); // write_data(read_idx, tmp); // // return; //} if (in_bounds(x + vx, y + vy) && (is_empty(x + vx, y + vy))) { write_data(v_idx, *p); write_data(read_idx, particle_empty()); } else if (is_empty(x, y + u)) { write_data(b_idx, *p); write_data(read_idx, particle_empty()); } else if (is_empty(x + r, y + u)) { write_data(br_idx, *p); write_data(read_idx, particle_empty()); } else if (is_empty(x + l, y + u)) { write_data(bl_idx, *p); write_data(read_idx, particle_empty()); } else { particle_t tmp = *p; b32 found = false; for (u32 i = 0; i < fall_rate; ++i) { for (s32 j = spread_rate; j > 0; --j) { if (is_empty(x - j, y + i)) { write_data(compute_idx(x - j, y + i), *p); write_data(read_idx, particle_empty()); found = true; break; } else if (is_empty(x + j, y + i)) { write_data(compute_idx(x + j, y + i), *p); write_data(read_idx, particle_empty()); found = true; break; } } } if (!found) { write_data(read_idx, tmp); } } } void update_oil(u32 x, u32 y) { f32 dt = gs_platform_delta_time(); u32 read_idx = compute_idx(x, y); particle_t* p = &g_world_particle_data[read_idx]; u32 write_idx = read_idx; u32 fall_rate = 2; u32 spread_rate = 4; p->velocity.y = gs_clamp(p->velocity.y + (gravity * dt), -10.f, 10.f); p->has_been_updated_this_frame = true; // Just check if you can move directly beneath you. If not, then reset your velocity. God, this is going to blow. // if (in_bounds(x, y + 1) && !is_empty(x, y + 1) && get_particle_at(x, y + 1).id != mat_id_water) { if (in_bounds(x, y + 1) && !is_empty(x, y + 1)) { p->velocity.y /= 2.f; } // Change color depending on pressure? Pressure would dictate how "deep" the water is, I suppose. if (random_val(0, (s32)(p->life_time * 100.f)) % 20 == 0) { f32 r = (f32)(random_val(0, 1)) / 2.f; p->color.r = (u8)(gs_interp_linear(0.2f, 0.25f, r) * 255.f); p->color.g = (u8)(gs_interp_linear(0.2f, 0.25f, r) * 255.f); p->color.b = (u8)(gs_interp_linear(0.2f, 0.25f, r) * 255.f); } s32 ran = random_val(0, 1); s32 r = ran ? spread_rate : -spread_rate; s32 l = -r; s32 u = fall_rate; s32 v_idx = compute_idx (x + (s32)p->velocity.x, y + (s32)p->velocity.y); s32 b_idx = compute_idx(x, y + u); s32 bl_idx = compute_idx(x + l, y + u); s32 br_idx = compute_idx(x + r, y + u); s32 l_idx = compute_idx(x + l, y); s32 r_idx = compute_idx(x + r, y); s32 vx = (s32)p->velocity.x, vy = (s32)p->velocity.y; // If in water, then need to float upwards // s32 lx, ly; // if (is_in_liquid(x, y, &lx, &ly) && in_bounds(x, y - 1) && get_particle_at(x, y - 1).id == mat_id_water) { // particle_t tmp = get_particle_at(x, y - 1); // write_data(compute_idx(x, y - 1), *p); // write_data(read_idx, tmp); // // return; //} if (in_bounds(x + vx, y + vy) && (is_empty(x + vx, y + vy))) { write_data(v_idx, *p); write_data(read_idx, particle_empty()); } else if (is_empty(x, y + u)) { write_data(b_idx, *p); write_data(read_idx, particle_empty()); } else if (is_empty(x + r, y + u)) { write_data(br_idx, *p); write_data(read_idx, particle_empty()); } else if (is_empty(x + l, y + u)) { write_data(bl_idx, *p); write_data(read_idx, particle_empty()); } else { particle_t tmp = *p; b32 found = false; for (u32 i = 0; i < fall_rate; ++i) { for (s32 j = spread_rate; j > 0; --j) { if (is_empty(x - j, y + i)) { write_data(compute_idx(x - j, y + i), *p); write_data(read_idx, particle_empty()); found = true; break; } else if (is_empty(x + j, y + i)) { write_data(compute_idx(x + j, y + i), *p); write_data(read_idx, particle_empty()); found = true; break; } } } if (!found) { write_data(read_idx, tmp); } } } void update_acid(u32 x, u32 y) { f32 dt = gs_platform_delta_time(); u32 read_idx = compute_idx(x, y); particle_t* p = &g_world_particle_data[read_idx]; u32 write_idx = read_idx; u32 fall_rate = 2; u32 spread_rate = 5; s32 lx, ly; p->velocity.y = gs_clamp(p->velocity.y + (gravity * dt), -10.f, 10.f); p->has_been_updated_this_frame = true; // Just check if you can move directly beneath you. If not, then reset your velocity. God, this is going to blow. // if (in_bounds(x, y + 1) && !is_empty(x, y + 1) && get_particle_at(x, y + 1).id != mat_id_water) { if (in_bounds(x, y + 1) && !is_empty(x, y + 1)) { p->velocity.y /= 2.f; } // Change color depending on pressure? Pressure would dictate how "deep" the water is, I suppose. if (random_val(0, (s32)(p->life_time * 100.f)) % 20 == 0) { f32 r = (f32)(random_val(0, 1)) / 2.f; p->color.r = (u8)(gs_interp_linear(0.05f, 0.06f, r) * 255.f); p->color.g = (u8)(gs_interp_linear(0.8f, 0.85f, r) * 255.f); p->color.b = (u8)(gs_interp_linear(0.1f, 0.12f, r) * 255.f); } const s32 wood_chance = 100; const s32 stone_chance = 300; const s32 sand_chance = 50; const s32 salt_chance = 20; // Random chance to die if in water if (is_in_water(x, y, &lx, &ly) && random_val(0, 250) == 0) { write_data(read_idx, particle_empty()); return; } // If directly on top of some wall, then replace it if (in_bounds(x, y + 1) && ((get_particle_at(x, y + 1).id == mat_id_wood && random_val(0, wood_chance) == 0) || (get_particle_at(x, y + 1).id == mat_id_stone && random_val(0, stone_chance) == 0) || (get_particle_at(x, y + 1).id == mat_id_sand && random_val(0, sand_chance) == 0) || (get_particle_at(x, y + 1).id == mat_id_salt && random_val(0, salt_chance) == 0) )) { write_data(compute_idx(x, y + 1), *p); write_data(read_idx, particle_empty()); } else if (in_bounds(x + 1, y + 1) && ((get_particle_at(x + 1, y + 1).id == mat_id_wood && random_val(0, wood_chance) == 0) || (get_particle_at(x + 1, y + 1).id == mat_id_stone && random_val(0, stone_chance) == 0) || (get_particle_at(x + 1, y + 1).id == mat_id_sand && random_val(0, sand_chance) == 0) || (get_particle_at(x + 1, y + 1).id == mat_id_salt && random_val(0, salt_chance) == 0) )) { write_data(compute_idx(x + 1, y + 1), *p); write_data(read_idx, particle_empty()); } else if (in_bounds(x - 1, y + 1) && ((get_particle_at(x - 1, y + 1).id == mat_id_wood && random_val(0, wood_chance) == 0) || (get_particle_at(x - 1, y + 1).id == mat_id_stone && random_val(0, stone_chance) == 0) || (get_particle_at(x - 1, y + 1).id == mat_id_sand && random_val(0, sand_chance) == 0) || (get_particle_at(x - 1, y + 1).id == mat_id_salt && random_val(0, salt_chance) == 0) )) { write_data(compute_idx(x - 1, y + 1), *p); write_data(read_idx, particle_empty()); } else if (in_bounds(x - 1, y) && ((get_particle_at(x - 1, y).id == mat_id_wood && random_val(0, wood_chance) == 0) || (get_particle_at(x - 1, y).id == mat_id_stone && random_val(0, stone_chance) == 0) || (get_particle_at(x - 1, y).id == mat_id_sand && random_val(0, sand_chance) == 0) || (get_particle_at(x - 1, y).id == mat_id_salt && random_val(0, salt_chance) == 0) )) { write_data(compute_idx(x - 1, y), *p); write_data(read_idx, particle_empty()); } else if (in_bounds(x + 1, y) && ((get_particle_at(x + 1, y).id == mat_id_wood && random_val(0, wood_chance) == 0) || (get_particle_at(x + 1, y).id == mat_id_stone && random_val(0, stone_chance) == 0) || (get_particle_at(x + 1, y).id == mat_id_sand && random_val(0, sand_chance) == 0) || (get_particle_at(x + 1, y).id == mat_id_salt && random_val(0, sand_chance) == 0) )) { write_data(compute_idx(x + 1, y), *p); write_data(read_idx, particle_empty()); } else if (in_bounds(x + 1, y - 1) && ((get_particle_at(x + 1, y - 1).id == mat_id_wood && random_val(0, wood_chance) == 0) || (get_particle_at(x + 1, y - 1).id == mat_id_stone && random_val(0, stone_chance) == 0) || (get_particle_at(x + 1, y - 1).id == mat_id_sand && random_val(0, sand_chance) == 0) || (get_particle_at(x + 1, y - 1).id == mat_id_salt && random_val(0, salt_chance) == 0) )) { write_data(compute_idx(x + 1, y - 1), *p); write_data(read_idx, particle_empty()); } else if (in_bounds(x - 1, y - 1) && ((get_particle_at(x - 1, y - 1).id == mat_id_wood && random_val(0, wood_chance) == 0) || (get_particle_at(x - 1, y - 1).id == mat_id_stone && random_val(0, stone_chance) == 0) || (get_particle_at(x - 1, y - 1).id == mat_id_sand && random_val(0, sand_chance) == 0) || (get_particle_at(x - 1, y - 1).id == mat_id_salt && random_val(0, salt_chance) == 0) )) { write_data(compute_idx(x - 1, y - 1), *p); write_data(read_idx, particle_empty()); } s32 ran = random_val(0, 1); s32 r = ran ? spread_rate : -spread_rate; s32 l = -r; s32 u = fall_rate; s32 v_idx = compute_idx (x + (s32)p->velocity.x, y + (s32)p->velocity.y); s32 b_idx = compute_idx(x, y + u); s32 bl_idx = compute_idx(x + l, y + u); s32 br_idx = compute_idx(x + r, y + u); s32 l_idx = compute_idx(x + l, y); s32 r_idx = compute_idx(x + r, y); s32 vx = (s32)p->velocity.x, vy = (s32)p->velocity.y; // If touching wood or stone, destroy it if (in_bounds(x + vx, y + vy) && (is_empty(x + vx, y + vy))) { write_data(v_idx, *p); write_data(read_idx, particle_empty()); } else if (is_empty(x, y + u)) { write_data(b_idx, *p); write_data(read_idx, particle_empty()); } else if (is_empty(x + r, y + u)) { write_data(br_idx, *p); write_data(read_idx, particle_empty()); } else if (is_empty(x + l, y + u)) { write_data(bl_idx, *p); write_data(read_idx, particle_empty()); } // Simple falling, changing the velocity here ruins everything. I need to redo this entire simulation. else if (in_bounds(x, y + u) && ((is_empty(x, y + u)))) { p->velocity.y += (gravity * dt); particle_t tmp_b = get_particle_at(x, y + u); write_data(b_idx, *p); write_data(read_idx, tmp_b); } else if (in_bounds(x + l, y + u) && ((is_empty(x + l, y + u)))) { p->velocity.x = is_in_liquid(x, y, &lx, &ly) ? 0.f : random_val(0, 1) == 0 ? -1.f : 1.f; p->velocity.y += (gravity * dt); particle_t tmp_b = get_particle_at(x + l, y + u); write_data(bl_idx, *p); write_data(read_idx, tmp_b); } else if (in_bounds(x + r, y + u) && ((is_empty(x + r, y + u)))) { p->velocity.x = is_in_liquid(x, y, &lx, &ly) ? 0.f : random_val(0, 1) == 0 ? -1.f : 1.f; p->velocity.y += (gravity * dt); particle_t tmp_b = get_particle_at(x + r, y + u); write_data(br_idx, *p); write_data(read_idx, tmp_b); } else if (is_in_liquid(x, y, &lx, &ly) && random_val(0, 10) == 0) { particle_t tmp_b = get_particle_at(lx, ly); write_data(compute_idx(lx, ly), *p); write_data(read_idx, tmp_b); } else { particle_t tmp = *p; b32 found = false; // Don't try to spread if something is directly above you? if (completely_surrounded(x, y)) { write_data(read_idx, tmp); return; } else { for (u32 i = 0; i < fall_rate; ++i) { for (s32 j = spread_rate; j > 0; --j) { if (in_bounds(x - j, y + i) && (is_empty(x - j, y + i) || get_particle_at(x - j, y + i).id == mat_id_oil)) { particle_t tmp = get_particle_at(x - j, y + i); write_data(compute_idx(x - j, y + i), *p); write_data(read_idx, tmp); found = true; break; } if (in_bounds(x + j, y + i) && (is_empty(x + j, y + i) || get_particle_at(x + j, y + i).id == mat_id_oil)) { particle_t tmp = get_particle_at(x + j, y + i); write_data(compute_idx(x + j, y + i), *p); write_data(read_idx, tmp); found = true; break; } } } if (!found) { write_data(read_idx, tmp); } } } } void update_water(u32 x, u32 y) { f32 dt = gs_platform_delta_time(); u32 read_idx = compute_idx(x, y); particle_t* p = &g_world_particle_data[read_idx]; u32 write_idx = read_idx; u32 fall_rate = 2; u32 spread_rate = 5; p->velocity.y = gs_clamp(p->velocity.y + (gravity * dt), -10.f, 10.f); p->has_been_updated_this_frame = true; // Just check if you can move directly beneath you. If not, then reset your velocity. God, this is going to blow. // if (in_bounds(x, y + 1) && !is_empty(x, y + 1) && get_particle_at(x, y + 1).id != mat_id_water) { if (in_bounds(x, y + 1) && !is_empty(x, y + 1)) { p->velocity.y /= 2.f; } // Change color depending on pressure? Pressure would dictate how "deep" the water is, I suppose. if (random_val(0, (s32)(p->life_time * 100.f)) % 20 == 0) { f32 r = (f32)(random_val(0, 1)) / 2.f; p->color.r = (u8)(gs_interp_linear(0.1f, 0.15f, r) * 255.f); p->color.g = (u8)(gs_interp_linear(0.3f, 0.35f, r) * 255.f); p->color.b = (u8)(gs_interp_linear(0.7f, 0.8f, r) * 255.f); } s32 ran = random_val(0, 1); s32 r = ran ? spread_rate : -spread_rate; s32 l = -r; s32 u = fall_rate; s32 v_idx = compute_idx (x + (s32)p->velocity.x, y + (s32)p->velocity.y); s32 b_idx = compute_idx(x, y + u); s32 bl_idx = compute_idx(x + l, y + u); s32 br_idx = compute_idx(x + r, y + u); s32 l_idx = compute_idx(x + l, y); s32 r_idx = compute_idx(x + r, y); s32 vx = (s32)p->velocity.x, vy = (s32)p->velocity.y; s32 lx, ly; if (in_bounds(x + vx, y + vy) && (is_empty(x + vx, y + vy))) { write_data(v_idx, *p); write_data(read_idx, particle_empty()); } else if (is_empty(x, y + u)) { write_data(b_idx, *p); write_data(read_idx, particle_empty()); } else if (is_empty(x + r, y + u)) { write_data(br_idx, *p); write_data(read_idx, particle_empty()); } else if (is_empty(x + l, y + u)) { write_data(bl_idx, *p); write_data(read_idx, particle_empty()); } // Simple falling, changing the velocity here ruins everything. I need to redo this entire simulation. else if (in_bounds(x, y + u) && ((is_empty(x, y + u) || (g_world_particle_data[b_idx].id == mat_id_oil)))) { p->velocity.y += (gravity * dt); particle_t tmp_b = get_particle_at(x, y + u); write_data(b_idx, *p); write_data(read_idx, tmp_b); } else if (in_bounds(x + l, y + u) && ((is_empty(x + l, y + u) || g_world_particle_data[bl_idx].id == mat_id_oil))) { p->velocity.x = is_in_liquid(x, y, &lx, &ly) ? 0.f : random_val(0, 1) == 0 ? -1.f : 1.f; p->velocity.y += (gravity * dt); particle_t tmp_b = get_particle_at(x + l, y + u); write_data(bl_idx, *p); write_data(read_idx, tmp_b); } else if (in_bounds(x + r, y + u) && ((is_empty(x + r, y + u) || g_world_particle_data[br_idx].id == mat_id_oil))) { p->velocity.x = is_in_liquid(x, y, &lx, &ly) ? 0.f : random_val(0, 1) == 0 ? -1.f : 1.f; p->velocity.y += (gravity * dt); particle_t tmp_b = get_particle_at(x + r, y + u); write_data(br_idx, *p); write_data(read_idx, tmp_b); } else if (is_in_liquid(x, y, &lx, &ly) && random_val(0, 10) == 0) { particle_t tmp_b = get_particle_at(lx, ly); write_data(compute_idx(lx, ly), *p); write_data(read_idx, tmp_b); } else { particle_t tmp = *p; b32 found = false; // Don't try to spread if something is directly above you? if (completely_surrounded(x, y)) { write_data(read_idx, tmp); return; } else { for (u32 i = 0; i < fall_rate; ++i) { for (s32 j = spread_rate; j > 0; --j) { if (in_bounds(x - j, y + i) && (is_empty(x - j, y + i) || get_particle_at(x - j, y + i).id == mat_id_oil)) { particle_t tmp = get_particle_at(x - j, y + i); write_data(compute_idx(x - j, y + i), *p); write_data(read_idx, tmp); found = true; break; } if (in_bounds(x + j, y + i) && (is_empty(x + j, y + i) || get_particle_at(x + j, y + i).id == mat_id_oil)) { particle_t tmp = get_particle_at(x + j, y + i); write_data(compute_idx(x + j, y + i), *p); write_data(read_idx, tmp); found = true; break; } } } if (!found) { write_data(read_idx, tmp); } } } } void update_default(u32 w, u32 h) { u32 read_idx = compute_idx(w, h); write_data(read_idx, get_particle_at(w, h)); } particle_t particle_empty() { particle_t p = {0}; p.id = mat_id_empty; p.color = mat_col_empty; return p; } particle_t particle_sand() { particle_t p = {0}; p.id = mat_id_sand; // Random sand color f32 r = (f32)(random_val(0, 10)) / 10.f; p.color.r = (u8)(gs_interp_linear(0.8f, 1.f, r) * 255.f); p.color.g = (u8)(gs_interp_linear(0.5f, 0.6f, r) * 255.f); p.color.b = (u8)(gs_interp_linear(0.2f, 0.25f, r) * 255.f); p.color.a = 255; return p; } particle_t particle_water() { particle_t p = {0}; p.id = mat_id_water; f32 r = (f32)(random_val(0, 1)) / 2.f; p.color.r = (u8)(gs_interp_linear(0.1f, 0.15f, r) * 255.f); p.color.g = (u8)(gs_interp_linear(0.3f, 0.35f, r) * 255.f); p.color.b = (u8)(gs_interp_linear(0.7f, 0.8f, r) * 255.f); p.color.a = 255; return p; } particle_t particle_salt() { particle_t p = {0}; p.id = mat_id_salt; f32 r = (f32)(random_val(0, 1)) / 2.f; p.color.r = (u8)(gs_interp_linear(0.9f, 1.0f, r) * 255.f); p.color.g = (u8)(gs_interp_linear(0.8f, 0.85f, r) * 255.f); p.color.b = (u8)(gs_interp_linear(0.8f, 0.9f, r) * 255.f); p.color.a = 255; return p; } particle_t particle_wood() { particle_t p = {0}; p.id = mat_id_wood; f32 r = (f32)(random_val(0, 1)) / 2.f; p.color.r = (u8)(gs_interp_linear(0.23f, 0.25f, r) * 255.f); p.color.g = (u8)(gs_interp_linear(0.15f, 0.18f, r) * 255.f); p.color.b = (u8)(gs_interp_linear(0.02f, 0.03f, r) * 255.f); p.color.a = 255; return p; } particle_t particle_gunpowder() { particle_t p = {0}; p.id = mat_id_gunpowder; f32 r = (f32)(random_val(0, 1)) / 2.f; p.color.r = (u8)(gs_interp_linear(0.15f, 0.2f, r) * 255.f); p.color.g = (u8)(gs_interp_linear(0.15f, 0.2f, r) * 255.f); p.color.b = (u8)(gs_interp_linear(0.15f, 0.2f, r) * 255.f); p.color.a = 255; return p; } particle_t particle_oil() { particle_t p = {0}; p.id = mat_id_oil; f32 r = (f32)(random_val(0, 1)) / 2.f; p.color.r = (u8)(gs_interp_linear(0.12f, 0.15f, r) * 255.f); p.color.g = (u8)(gs_interp_linear(0.10f, 0.12f, r) * 255.f); p.color.b = (u8)(gs_interp_linear(0.08f, 0.10f, r) * 255.f); p.color.a = 255; return p; } particle_t particle_fire() { particle_t p = {0}; p.id = mat_id_fire; p.color = mat_col_fire; return p; } particle_t particle_lava() { particle_t p = {0}; p.id = mat_id_lava; p.color = mat_col_fire; return p; } particle_t particle_ember() { particle_t p = {0}; p.id = mat_id_ember; p.color = mat_col_ember; return p; } particle_t particle_smoke() { particle_t p = {0}; p.id = mat_id_smoke; p.color = mat_col_smoke; return p; } particle_t particle_steam() { particle_t p = {0}; p.id = mat_id_steam; p.color = mat_col_steam; return p; } particle_t particle_stone() { particle_t p = {0}; p.id = mat_id_stone; f32 r = (f32)(random_val(0, 1)) / 2.f; p.color.r = (u8)(gs_interp_linear(0.5f, 0.65f, r) * 255.f); p.color.g = (u8)(gs_interp_linear(0.5f, 0.65f, r) * 255.f); p.color.b = (u8)(gs_interp_linear(0.5f, 0.65f, r) * 255.f); p.color.a = 255; return p; } particle_t particle_acid() { particle_t p = {0}; p.id = mat_id_acid; f32 r = (f32)(random_val(0, 1)) / 2.f; p.color.r = (u8)(gs_interp_linear(0.05f, 0.06f, r) * 255.f); p.color.g = (u8)(gs_interp_linear(0.8f, 0.85f, r) * 255.f); p.color.b = (u8)(gs_interp_linear(0.1f, 0.12f, r) * 255.f); p.color.a = 200; return p; }
33.148586
165
0.620495
[ "render", "object", "solid" ]
c576364fd052ce7eadc892ce25b784d2c7dba392
4,386
h
C
src/apps/distest/value_collection.h
itm/shawn
49cb715d0044a20a01a19bc4d7b62f9f209df83c
[ "BSD-3-Clause" ]
15
2015-07-07T15:48:30.000Z
2019-10-27T18:49:49.000Z
src/apps/distest/value_collection.h
itm/shawn
49cb715d0044a20a01a19bc4d7b62f9f209df83c
[ "BSD-3-Clause" ]
null
null
null
src/apps/distest/value_collection.h
itm/shawn
49cb715d0044a20a01a19bc4d7b62f9f209df83c
[ "BSD-3-Clause" ]
4
2016-11-23T05:50:01.000Z
2019-09-18T12:44:36.000Z
/************************************************************************ ** This file is part of the network simulator Shawn. ** ** Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de) project ** ** Shawn is free software; you can redistribute it and/or modify it ** ** under the terms of the BSD License. Refer to the shawn-licence.txt ** ** file in the root of the Shawn source tree for further details. ** ************************************************************************/ #ifndef __SHAWN_APPS_VALUE_COLLECTION_H #define __SHAWN_APPS_VALUE_COLLECTION_H #include "_apps_enable_cmake.h" #ifdef ENABLE_DISTEST /* #include "sys/simulation/simulation_controller.h" #include "sys/simulation/simulation_task.h" #include "sys/vec.h" #include "apps/distest/histogram.h" #include "sys/node_distance_estimate.h" #include "apps/distest/distest_postscript_writer.h" #include "sys/distance_estimates/perfect_distance_estimate.h" //#include "apps/distest/distest_task.h"*/ #include <map> #include <vector> #include <set> #include <sstream> #include <fstream> #include <deque> #include <algorithm> #include <fstream> #include <sstream> #include <iostream> #include <assert.h> using namespace std; //namespace shawn {class Node;} //typedef unsigned int uint; //typedef vector< vector<double> > FloatMatrix; //typedef vector< vector<uint> > UINTMatrix; namespace distest { class FileHandleCache { private: struct Data { Data(int key, const string& id) : key_(key), id_(id) {} std::ofstream* fh_; int key_; string id_; bool operator==(const Data& other) { return key_ == other.key_ && id_ == other.id_; } }; string prefix_; int max_; deque<Data> cache_; public: FileHandleCache(string prefix, int max = 500) : prefix_(prefix), max_(max) {} ~FileHandleCache() { //cout << "Destructor called" << endl << flush; emptyCache(); } void emptyCache(){ for(deque<Data>::iterator it = cache_.begin(), end = cache_.end(); it!=end; ++it) { std::ofstream* tmpfh = (*it).fh_; if(tmpfh!=NULL) { //cout << "Closing file key["<<(*it).key_<<"], ident["<<(*it).id_<<"]" << endl << flush; tmpfh->flush(); tmpfh->close(); delete tmpfh; (*it).fh_ = NULL; } } } std::ofstream* get(int key, const std::string& id) { deque<Data>::iterator it = find(cache_.begin(), cache_.end(), Data(key, id)); std::ofstream* fh = NULL; //Gefunden im Cache -> nach vorne in die queue if( it != cache_.end() ) { fh = (*it).fh_; cache_.push_back( (*it) ); cache_.erase(it); } //Nicht gefunden im Cache -> neu anlegen, evtl. alten loeschen und nach vorne in die queue else { if( int(cache_.size()) >= max_ ) { cache_.back().fh_->flush(); cache_.back().fh_->close(); //cout << "Closing file key["<<cache_.back().key_<<"], ident["<<cache_.back().id_<<"] --> Remove from cache." << endl << flush; cache_.pop_back(); } ostringstream os; os << prefix_ << key << "_"<<id<< ".ms"; //cout << "FHC: Creating file " << os.str() << "..." << flush; cache_.push_front( Data(key, id) ); fh = new std::ofstream(os.str().c_str(), ofstream::out | ofstream::app ); cache_.front().fh_ = fh; assert( cache_.front().fh_->is_open() ); //cout << " success" << endl << flush; } assert(fh != NULL); return fh; } }; class valueCollection { public: valueCollection(); void insert( int key, std::string ident, float val ); void set_file_handle_cache(FileHandleCache*); //void close(); void clear(); multiset<float>* getVals(int key, std::string ident); ~valueCollection(); // protected: //friend class MultihopDistanceEstimateTask; //friend class DistanceEstimateTask; private: FileHandleCache* fhc_; //std::ofstream* newFile(int key, std::string ident); bool file; multiset<float>* err; //std::ofstream* fh; }; } #endif #endif /*----------------------------------------------------------------------- * Source $Source: /cvs/shawn/shawn/apps/distest/value_collection.h,v $ * Version $Revision: 197 $ * Date $Date: 2008-04-29 17:40:51 +0200 (Tue, 29 Apr 2008) $ *----------------------------------------------------------------------- * $Log: value_collection.h,v $ *-----------------------------------------------------------------------*/
26.263473
132
0.584815
[ "vector" ]
c57c652c6aebda25c100efb701d0b7abdec259ef
29,002
c
C
c++/tools/vips.c
aisaac-lab/washi
f7158cc2647dd2b688ab4cffb9f21d1a7fb76ef8
[ "MIT" ]
null
null
null
c++/tools/vips.c
aisaac-lab/washi
f7158cc2647dd2b688ab4cffb9f21d1a7fb76ef8
[ "MIT" ]
null
null
null
c++/tools/vips.c
aisaac-lab/washi
f7158cc2647dd2b688ab4cffb9f21d1a7fb76ef8
[ "MIT" ]
1
2022-02-16T19:12:02.000Z
2022-02-16T19:12:02.000Z
/* VIPS universal main program. * * J. Cupitt, 8/4/93. * 12/5/06 * - use GOption. g_*_prgname() * 16/7/06 * - hmm, was broken for function name as argv1 case * 11/7/06 * - add "all" option to -l * 14/7/06 * - ignore "--" arguments. * 2/9/06 * - do less init ... im_init_world() does more now * 18/8/06 * - use IM_EXEEXT * 16/10/06 * - add --version * 17/10/06 * - add --swig * - cleanups * - remove --swig again, sigh * - add throw() decls to C++ to help SWIG * 14/1/07 * - add --list packages * 26/2/07 * - add input *VEC arg types to C++ binding * 17/8/08 * - add --list formats * 29/11/08 * - add --list interpolators * 9/2/09 * - and now we just have --list packages/classes/package-name * 13/11/09 * - drop _f postfixes, drop many postfixes * 24/6/10 * - less chatty error messages * - oops, don't rename "copy_set" as "copy_" * 6/2/12 * - long arg names in decls to help SWIG * - don't wrap im_remainderconst_vec() * 31/12/12 * - parse options in two passes (thanks Haida) */ /* This file is part of VIPS. VIPS is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk */ /* #define DEBUG #define DEBUG_FATAL */ /* Need to disable these sometimes. #undef DEBUG_FATAL */ #ifdef HAVE_CONFIG_H #include <config.h> #endif /*HAVE_CONFIG_H*/ #include <vips/intl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <locale.h> #include <vips/vips.h> #include <vips/internal.h> #ifdef OS_WIN32 #define strcasecmp(a,b) _stricmp(a,b) #endif static char *main_option_plugin = NULL; static gboolean main_option_version; static void * list_class( GType type ) { VipsObjectClass *class = VIPS_OBJECT_CLASS( g_type_class_ref( type ) ); int depth = vips_type_depth( type ); int i; if( class->deprecated ) return( NULL ); if( VIPS_IS_OPERATION_CLASS( class ) && (VIPS_OPERATION_CLASS( class )->flags & VIPS_OPERATION_DEPRECATED) ) return( NULL ); for( i = 0; i < depth * 2; i++ ) printf( " " ); vips_object_print_summary_class( VIPS_OBJECT_CLASS( g_type_class_ref( type ) ) ); return( NULL ); } static void * test_nickname( GType type, void *data ) { const char *nickname = (const char *) data; VipsObjectClass *class; if( (class = VIPS_OBJECT_CLASS( g_type_class_ref( type ) )) && strcmp( class->nickname, nickname ) == 0 ) return( class ); return( NULL ); } static gboolean parse_main_option_list( const gchar *option_name, const gchar *value, gpointer data, GError **error ) { VipsObjectClass *class; if( value && (class = (VipsObjectClass *) vips_type_map_all( g_type_from_name( "VipsObject" ), test_nickname, (void *) value )) ) { vips_type_map_all( G_TYPE_FROM_CLASS( class ), (VipsTypeMapFn) list_class, NULL ); } else if( value ) { vips_error( g_get_prgname(), _( "'%s' is not the name of a vips class" ), value ); vips_error_g( error ); return( FALSE ); } else { vips_type_map_all( g_type_from_name( "VipsOperation" ), (VipsTypeMapFn) list_class, NULL ); } exit( 0 ); } static GOptionEntry main_option[] = { { "list", 'l', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_CALLBACK, (GOptionArgFunc) parse_main_option_list, N_( "list objects" ), N_( "BASE-NAME" ) }, { "plugin", 'p', 0, G_OPTION_ARG_FILENAME, &main_option_plugin, N_( "load PLUGIN" ), N_( "PLUGIN" ) }, { "version", 'v', 0, G_OPTION_ARG_NONE, &main_option_version, N_( "print version" ), NULL }, { NULL } }; typedef void *(*map_name_fn)( im_function * ); /* Loop over a package. */ static void * map_package( im_package *pack, map_name_fn fn ) { int i; void *result; for( i = 0; i < pack->nfuncs; i++ ) if( (result = fn( pack->table[i] )) ) return( result ); return( NULL ); } /* Apply a function to a vips operation, or map over a package of operations. */ static void * map_name( const char *name, map_name_fn fn ) { im_package *pack; im_function *func; if( !name || strcmp( name, "all" ) == 0 ) /* Do all packages. */ im_map_packages( (VSListMap2Fn) map_package, fn ); else if( (pack = im_find_package( name )) ) /* Do one package. */ map_package( pack, fn ); else if( (func = im_find_function( name )) ) /* Do a single function. */ fn( func ); else { vips_error( "map_name", _( "no package or function \"%s\"" ), name ); return( fn ); } return( NULL ); } static void * list_package( im_package *pack ) { printf( "%-20s - %d operations\n", pack->name, pack->nfuncs ); return( NULL ); } static void * list_function( im_function *func ) { printf( "%-20s - %s\n", func->name, _( func->desc ) ); return( NULL ); } static int print_list( int argc, char **argv ) { if( !argv[0] || strcmp( argv[0], "packages" ) == 0 ) im_map_packages( (VSListMap2Fn) list_package, NULL ); else if( strcmp( argv[0], "classes" ) == 0 ) vips_type_map_all( g_type_from_name( "VipsObject" ), (VipsTypeMapFn) list_class, NULL ); else if( g_type_from_name( argv[0] ) && g_type_is_a( g_type_from_name( argv[0] ), VIPS_TYPE_OBJECT ) ) { vips_type_map_all( g_type_from_name( argv[0] ), (VipsTypeMapFn) list_class, NULL ); } else { if( map_name( argv[0], list_function ) ) vips_error_exit( "unknown package \"%s\"", argv[0] ); } return( 0 ); } /* Print "ln -s" lines for this package. */ static void * print_links_package( im_package *pack ) { int i; for( i = 0; i < pack->nfuncs; i++ ) printf( "rm -f %s" IM_EXEEXT "; " "ln -s vips" IM_EXEEXT " %s" IM_EXEEXT "\n", pack->table[i]->name, pack->table[i]->name ); return( NULL ); } /* Print "ln -s" lines for this package. */ static int print_links( int argc, char **argv ) { im_map_packages( (VSListMap2Fn) print_links_package, NULL ); return( 0 ); } /* Does a function have any printing output? */ static int has_print( im_function *fn ) { int i; for( i = 0; i < fn->argc; i++ ) if( fn->argv[i].print ) return( -1 ); return( 0 ); } static int isvips( const char *name ) { /* If we're running uninstalled we get the lt- prefix. */ if( vips_isprefix( "lt-", name ) ) name += 3; return( vips_isprefix( "vips", name ) ); } /* Print a usage string from an im_function descriptor. */ static void usage( im_function *fn ) { int i; im_package *pack = im_package_of_function( fn->name ); /* Don't print the prgname if we're being run as a symlink. */ fprintf( stderr, "usage: " ); if( isvips( g_get_prgname() ) ) fprintf( stderr, "%s ", g_get_prgname() ); fprintf( stderr, "%s ", fn->name ); /* Print args requiring command-line input. */ for( i = 0; i < fn->argc; i++ ) if( fn->argv[i].desc->flags & IM_TYPE_ARG ) fprintf( stderr, "%s ", fn->argv[i].name ); /* Print types of command line args. */ fprintf( stderr, "\nwhere:\n" ); for( i = 0; i < fn->argc; i++ ) if( fn->argv[i].desc->flags & IM_TYPE_ARG ) fprintf( stderr, "\t%s is of type \"%s\"\n", fn->argv[i].name, fn->argv[i].desc->type ); /* Print output print args. */ if( has_print( fn ) ) { fprintf( stderr, "prints:\n" ); for( i = 0; i < fn->argc; i++ ) if( fn->argv[i].print ) fprintf( stderr, "\t%s of type \"%s\"\n", fn->argv[i].name, fn->argv[i].desc->type ); } /* Print description of this function, and package it comes from. */ fprintf( stderr, "%s", _( fn->desc ) ); if( pack ) fprintf( stderr, ", from package \"%s\"", pack->name ); fprintf( stderr, "\n" ); /* Print any flags this function has. */ fprintf( stderr, "flags: " ); if( fn->flags & IM_FN_PIO ) fprintf( stderr, "(PIO function) " ); else fprintf( stderr, "(WIO function) " ); if( fn->flags & IM_FN_TRANSFORM ) fprintf( stderr, "(coordinate transformer) " ); else fprintf( stderr, "(no coordinate transformation) " ); if( fn->flags & IM_FN_PTOP ) fprintf( stderr, "(point-to-point operation) " ); else fprintf( stderr, "(area operation) " ); if( fn->flags & IM_FN_NOCACHE ) fprintf( stderr, "(nocache operation) " ); else fprintf( stderr, "(result can be cached) " ); fprintf( stderr, "\n" ); } /* Convert VIPS type name to C++ type name. NULL for type unsupported by C++ * layer. */ static char * vips2cpp( im_type_desc *ty ) { int k; /* VIPS types. */ static char *vtypes[] = { IM_TYPE_DOUBLE, IM_TYPE_INT, IM_TYPE_COMPLEX, IM_TYPE_STRING, IM_TYPE_IMAGE, IM_TYPE_IMASK, IM_TYPE_DMASK, IM_TYPE_DISPLAY, IM_TYPE_IMAGEVEC, IM_TYPE_DOUBLEVEC, IM_TYPE_INTVEC, IM_TYPE_INTERPOLATE }; /* Corresponding C++ types. */ static char *ctypes[] = { "double", "int", "std::complex<double>", "char*", "VImage", "VIMask", "VDMask", "VDisplay", "std::vector<VImage>", "std::vector<double>", "std::vector<int>", "char*" }; for( k = 0; k < IM_NUMBER( vtypes ); k++ ) if( strcmp( ty->type, vtypes[k] ) == 0 ) return( ctypes[k] ); return( NULL ); } /* Test a function definition for C++ suitability. */ static int is_cppable( im_function *fn ) { int j; /* Don't wrap im_remainderconst_vec(). * * This has been replaced by the saner name im_remainder_vec(). If we * generate wrappers for both names we get a overloading clash. */ if( strcmp( fn->name, "im_remainderconst_vec" ) == 0 ) return( 0 ); /* Check we know all the types. */ for( j = 0; j < fn->argc; j++ ) { im_type_desc *ty = fn->argv[j].desc; if( !vips2cpp( ty ) ) return( 0 ); } /* We dont wrap output IMAGEVEC/DOUBLEVEC/INTVEC. */ for( j = 0; j < fn->argc; j++ ) { im_type_desc *ty = fn->argv[j].desc; if( ty->flags & IM_TYPE_OUTPUT ) if( strcmp( ty->type, IM_TYPE_IMAGEVEC ) == 0 || strcmp( ty->type, IM_TYPE_DOUBLEVEC ) == 0 || strcmp( ty->type, IM_TYPE_INTVEC ) == 0 ) return( 0 ); } /* Must be at least one image argument (input or output) ... since we * get inserted in the VImage class. Other funcs get wrapped by hand. */ for( j = 0; j < fn->argc; j++ ) if( strcmp( fn->argv[j].desc->type, IM_TYPE_IMAGE ) == 0 ) break; if( j == fn->argc ) return( 0 ); return( -1 ); } /* Search for the first output arg, and the first IMAGE input arg. */ static void find_ioargs( im_function *fn, int *ia, int *oa ) { int j; /* Look for first output arg - this will be the result of the * function. */ *oa = -1; for( j = 0; j < fn->argc; j++ ) { im_type_desc *ty = fn->argv[j].desc; if( ty->flags & IM_TYPE_OUTPUT ) { *oa = j; break; } } /* Look for first input IMAGE arg. This will become the implicit * "this" arg. */ *ia = -1; for( j = 0; j < fn->argc; j++ ) { im_type_desc *ty = fn->argv[j].desc; if( !(ty->flags & IM_TYPE_OUTPUT) && strcmp( ty->type, IM_TYPE_IMAGE ) == 0 ) { *ia = j; break; } } } static gboolean drop_postfix( char *str, const char *postfix ) { if( vips_ispostfix( str, postfix ) ) { str[strlen( str ) - strlen( postfix )] = '\0'; return( TRUE ); } return( FALSE ); } /* Turn a VIPS name into a C++ name. Eg. im_lintra_vec becomes lin. */ static void c2cpp_name( const char *in, char *out ) { static const char *dont_drop[] = { "_set", }; static const char *drop[] = { "_vec", "const", "tra", "set", "_f" }; int i; gboolean changed; /* Copy, chopping off "im_" prefix. */ if( vips_isprefix( "im_", in ) ) strcpy( out, in + 3 ); else strcpy( out, in ); /* Repeatedly drop postfixes while we can. Stop if we see a dont_drop * postfix. */ do { gboolean found; found = FALSE; for( i = 0; i < IM_NUMBER( dont_drop ); i++ ) if( vips_ispostfix( out, dont_drop[i] ) ) { found = TRUE; break; } if( found ) break; changed = FALSE; for( i = 0; i < IM_NUMBER( drop ); i++ ) changed |= drop_postfix( out, drop[i] ); } while( changed ); } /* Print prototype for a function (ie. will be followed by code). * * Eg.: * VImage VImage::lin( double a, double b ) throw( VError ) */ static void * print_cppproto( im_function *fn ) { int j; char name[4096]; int oa, ia; int flg; /* If it's not cppable, do nothing. */ if( !is_cppable( fn ) ) return( NULL ); /* Make C++ name. */ c2cpp_name( fn->name, name ); /* Find input and output args. */ find_ioargs( fn, &ia, &oa ); /* Print output type. */ if( oa == -1 ) printf( "void " ); else printf( "%s ", vips2cpp( fn->argv[oa].desc ) ); printf( "VImage::%s(", name ); /* Print arg list. */ flg = 0; for( j = 0; j < fn->argc; j++ ) { im_type_desc *ty = fn->argv[j].desc; /* Skip ia and oa. */ if( j == ia || j == oa ) continue; /* Print arg type. */ if( flg ) printf( ", %s", vips2cpp( ty ) ); else { printf( " %s", vips2cpp( ty ) ); flg = 1; } /* If it's an putput arg, print a "&" to make a reference * argument. */ if( ty->flags & IM_TYPE_OUTPUT ) printf( "&" ); /* Print arg name. */ printf( " %s", fn->argv[j].name ); } /* End of arg list! */ if( flg ) printf( " " ); printf( ") throw( VError )\n" ); return( NULL ); } /* Print cpp decl for a function. * * Eg. * VImage lin( double, double ) throw( VError ); */ static void * print_cppdecl( im_function *fn ) { int j; char name[4096]; int oa, ia; int flg; /* If it's not cppable, do nothing. */ if( !is_cppable( fn ) ) return( NULL ); /* Make C++ name. */ c2cpp_name( fn->name, name ); /* Find input and output args. */ find_ioargs( fn, &ia, &oa ); if( ia == -1 ) /* No input image, so make it a static in the class * declaration. */ printf( "static " ); /* Print output type. */ if( oa == -1 ) printf( "void " ); else printf( "%s ", vips2cpp( fn->argv[oa].desc ) ); /* Print function name and start arg list. */ printf( "%s(", name ); /* Print arg list. */ flg = 0; for( j = 0; j < fn->argc; j++ ) { im_type_desc *ty = fn->argv[j].desc; /* Skip ia and oa. */ if( j == ia || j == oa ) continue; /* Print arg type. */ if( flg ) printf( ", %s", vips2cpp( ty ) ); else { printf( " %s", vips2cpp( ty ) ); flg = 1; } /* If it's an putput arg, print a "&" to make a reference * argument. */ if( ty->flags & IM_TYPE_OUTPUT ) printf( "&" ); /* Print arg name. * * Prepend the member name to make the arg * unique. This is important for SWIG since it needs to have * unique names for %apply. */ printf( " %s_%s", name, fn->argv[j].name ); } /* End of arg list! */ if( flg ) printf( " " ); printf( ") throw( VError );\n" ); return( NULL ); } static void print_invec( int j, const char *arg, const char *vips_name, const char *c_name, const char *extract ) { printf( "\t((%s*) _vec.data(%d))->n = %s.size();\n", vips_name, j, arg ); printf( "\t((%s*) _vec.data(%d))->vec = new %s[%s.size()];\n", vips_name, j, c_name, arg ); printf( "\tfor( unsigned int i = 0; i < %s.size(); i++ )\n", arg ); printf( "\t\t((%s*) _vec.data(%d))->vec[i] = %s[i]%s;\n", vips_name, j, arg, extract ); } /* Print the definition for a function. */ static void * print_cppdef( im_function *fn ) { int j; int ia, oa; /* If it's not cppable, do nothing. */ if( !is_cppable( fn ) ) return( NULL ); find_ioargs( fn, &ia, &oa ); printf( "// %s: %s\n", fn->name, _( fn->desc ) ); print_cppproto( fn ); printf( "{\n" ); /* Declare the implicit input image. */ if( ia != -1 ) printf( "\tVImage %s = *this;\n", fn->argv[ia].name ); /* Declare return value, if any. */ if( oa != -1 ) printf( "\t%s %s;\n\n", vips2cpp( fn->argv[oa].desc ), fn->argv[oa].name ); /* Declare the arg vector. */ printf( "\tVargv _vec( \"%s\" );\n\n", fn->name ); /* Create the input args. */ for( j = 0; j < fn->argc; j++ ) { im_type_desc *ty = fn->argv[j].desc; /* Images are special - have to init the vector, even * for output args. Have to translate VImage. */ if( strcmp( ty->type, IM_TYPE_IMAGE ) == 0 ) { printf( "\t_vec.data(%d) = %s.image();\n", j, fn->argv[j].name ); continue; } /* For output masks, we have to set an input filename. Not * freed, so constant string is OK. */ if( (ty->flags & IM_TYPE_OUTPUT) && (strcmp( ty->type, IM_TYPE_IMASK ) == 0 || strcmp( ty->type, IM_TYPE_DMASK ) == 0) ) { printf( "\t((im_mask_object*) _vec.data(%d))->name = " "(char*)\"noname\";\n", j ); continue; } /* Skip other output args. */ if( ty->flags & IM_TYPE_OUTPUT ) continue; if( strcmp( ty->type, IM_TYPE_IMASK ) == 0 ) /* Mask types are different - have to use * im_mask_object. */ printf( "\t((im_mask_object*) " "_vec.data(%d))->mask = %s.mask().iptr;\n", j, fn->argv[j].name ); else if( strcmp( ty->type, IM_TYPE_DMASK ) == 0 ) printf( "\t((im_mask_object*) " "_vec.data(%d))->mask = %s.mask().dptr;\n", j, fn->argv[j].name ); else if( strcmp( ty->type, IM_TYPE_DISPLAY ) == 0 ) /* Display have to use VDisplay. */ printf( "\t_vec.data(%d) = %s.disp();\n", j, fn->argv[j].name ); else if( strcmp( ty->type, IM_TYPE_STRING ) == 0 ) /* Zap input strings directly into _vec. */ printf( "\t_vec.data(%d) = (im_object) %s;\n", j, fn->argv[j].name ); else if( strcmp( ty->type, IM_TYPE_IMAGEVEC ) == 0 ) print_invec( j, fn->argv[j].name, "im_imagevec_object", "IMAGE *", ".image()" ); else if( strcmp( ty->type, IM_TYPE_DOUBLEVEC ) == 0 ) print_invec( j, fn->argv[j].name, "im_doublevec_object", "double", "" ); else if( strcmp( ty->type, IM_TYPE_INTVEC ) == 0 ) print_invec( j, fn->argv[j].name, "im_intvec_object", "int", "" ); else if( strcmp( ty->type, IM_TYPE_INTERPOLATE ) == 0 ) { printf( "\tif( vips__input_interpolate_init( " "&_vec.data(%d), %s ) )\n", j, fn->argv[j].name ); printf( "\t\tverror();\n" ); } else /* Just use vips2cpp(). */ printf( "\t*((%s*) _vec.data(%d)) = %s;\n", vips2cpp( ty ), j, fn->argv[j].name ); } /* Call function. */ printf( "\t_vec.call();\n" ); /* Extract output args. */ for( j = 0; j < fn->argc; j++ ) { im_type_desc *ty = fn->argv[j].desc; /* Skip input args. */ if( !(ty->flags & IM_TYPE_OUTPUT) ) continue; /* Skip images (done on input side, really). */ if( strcmp( ty->type, IM_TYPE_IMAGE ) == 0 ) continue; if( strcmp( ty->type, IM_TYPE_IMASK ) == 0 || strcmp( ty->type, IM_TYPE_DMASK ) == 0 ) /* Mask types are different - have to use * im_mask_object. */ printf( "\t%s.embed( (DOUBLEMASK *)((im_mask_object*)" "_vec.data(%d))->mask );\n", fn->argv[j].name, j ); else if( strcmp( ty->type, IM_TYPE_STRING ) == 0 ) /* Strings are grabbed out of the vec. */ printf( "\t%s = (char*) _vec.data(%d);\n", fn->argv[j].name, j ); else /* Just use vips2cpp(). */ printf( "\t%s = *((%s*)_vec.data(%d));\n", fn->argv[j].name, vips2cpp( ty ), j ); } /* Note dependancies if out is an image and this function uses * PIO. */ if( oa != -1 ) { im_type_desc *ty = fn->argv[oa].desc; if( strcmp( ty->type, IM_TYPE_IMAGE ) == 0 && (fn->flags & IM_FN_PIO) ) { /* Loop for all input args again .. */ for( j = 0; j < fn->argc; j++ ) { im_type_desc *ty2 = fn->argv[j].desc; /* Skip output args. */ if( ty2->flags & IM_TYPE_OUTPUT ) continue; /* Input image. */ if( strcmp( ty2->type, IM_TYPE_IMAGE ) == 0 ) printf( "\t%s._ref->addref( " "%s._ref );\n", fn->argv[oa].name, fn->argv[j].name ); else if( strcmp( ty2->type, IM_TYPE_IMAGEVEC ) == 0 ) { /* The out depends on every image in * the input vector. */ printf( "\tfor( unsigned int i = 0; " "i < %s.size(); i++ )\n", fn->argv[j].name ); printf( "\t\t%s._ref->addref( " "%s[i]._ref );\n", fn->argv[oa].name, fn->argv[j].name ); } } } } /* Return result. */ if( oa != -1 ) printf( "\n\treturn( %s );\n", fn->argv[oa].name ); printf( "}\n\n" ); return( NULL ); } /* Print C++ decls for function, package or all. */ static int print_cppdecls( int argc, char **argv ) { printf( "// this file automatically generated from\n" "// VIPS library %s\n", vips_version_string() ); if( map_name( argv[0], print_cppdecl ) ) vips_error_exit( NULL ); return( 0 ); } /* Print C++ bindings for function, package or all. */ static int print_cppdefs( int argc, char **argv ) { printf( "// this file automatically generated from\n" "// VIPS library %s\n", vips_version_string() ); if( map_name( argv[0], print_cppdef ) ) vips_error_exit( NULL ); return( 0 ); } static int print_help( int argc, char **argv ) { return( 0 ); } /* All our built-in actions. */ typedef int (*Action)( int argc, char **argv ); typedef struct _ActionEntry { char *name; char *description; GOptionEntry *group; Action action; } ActionEntry; static GOptionEntry empty_options[] = { { NULL } }; static ActionEntry actions[] = { { "list", N_( "list classes|packages|all|package-name|operation-name" ), &empty_options[0], print_list }, { "cpph", N_( "generate headers for C++ binding" ), &empty_options[0], print_cppdecls }, { "cppc", N_( "generate bodies for C++ binding" ), &empty_options[0], print_cppdefs }, { "links", N_( "generate links for vips/bin" ), &empty_options[0], print_links }, { "help", N_( "list possible actions" ), &empty_options[0], print_help }, }; static void parse_options( GOptionContext *context, int *argc, char **argv ) { char txt[1024]; VipsBuf buf = VIPS_BUF_STATIC( txt ); GError *error = NULL; int i, j; #ifdef DEBUG printf( "parse_options:\n" ); for( i = 0; i < *argc; i++ ) printf( "%d) %s\n", i, argv[i] ); #endif /*DEBUG*/ vips_buf_appendf( &buf, "%7s - %s\n", "OPER", _( "execute vips operation OPER" ) ); g_option_context_set_summary( context, vips_buf_all( &buf ) ); if( !g_option_context_parse( context, argc, &argv, &error ) ) { if( error ) { fprintf( stderr, "%s\n", error->message ); g_error_free( error ); } vips_error_exit( NULL ); } /* Remove any "--" argument. If one of our arguments is a negative * number, the user will need to have added the "--" flag to stop * GOption parsing. But "--" is still passed down to us and we need to * ignore it. */ for( i = 1; i < *argc - 1; i++ ) if( strcmp( argv[i], "--" ) == 0 ) { for( j = i; j < *argc; j++ ) argv[j] = argv[j + 1]; *argc -= 1; } } static GOptionGroup * add_operation_group( GOptionContext *context, VipsOperation *user_data ) { GOptionGroup *group; group = g_option_group_new( "operation", _( "Operation" ), _( "Operation help" ), user_data, NULL ); g_option_group_set_translation_domain( group, GETTEXT_PACKAGE ); g_option_context_add_group( context, group ); return( group ); } /* VIPS universal main program. */ int main( int argc, char **argv ) { char *action; GOptionContext *context; GOptionGroup *main_group; GOptionGroup *group; VipsOperation *operation; im_function *fn; int i, j; gboolean handled; GError *error = NULL; if( VIPS_INIT( argv[0] ) ) vips_error_exit( NULL ); textdomain( GETTEXT_PACKAGE ); setlocale( LC_ALL, "" ); #ifdef DEBUG_FATAL /* Set masks for debugging ... stop on any problem. */ g_log_set_always_fatal( G_LOG_FLAG_RECURSION | G_LOG_FLAG_FATAL | G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING ); #endif /*!DEBUG_FATAL*/ context = g_option_context_new( _( "[ACTION] [OPTIONS] [PARAMETERS] - " "VIPS driver program" ) ); /* Add and parse the outermost options: the ones this program uses. * For example, we need * to be able to spot that in the case of "--plugin ./poop.plg" we * must remove two args. */ main_group = g_option_group_new( NULL, NULL, NULL, NULL, NULL ); g_option_group_add_entries( main_group, main_option ); vips_add_option_entries( main_group ); g_option_group_set_translation_domain( main_group, GETTEXT_PACKAGE ); g_option_context_set_main_group( context, main_group ); /* We add more options later, for example as options to vips8 * operations. Ignore any unknown options in this first parse. */ g_option_context_set_ignore_unknown_options( context, TRUE ); /* "vips" with no arguments does "vips --help". */ if( argc == 1 ) { char *help; help = g_option_context_get_help( context, TRUE, NULL ); printf( "%s", help ); g_free( help ); exit( 0 ); } /* Also disable help output: we want to be able to display full help * in a second pass after all options have been created. */ g_option_context_set_help_enabled( context, FALSE ); if( !g_option_context_parse( context, &argc, &argv, &error ) ) { if( error ) { fprintf( stderr, "%s\n", error->message ); g_error_free( error ); } vips_error_exit( NULL ); } if( main_option_plugin ) { if( !im_load_plugin( main_option_plugin ) ) vips_error_exit( NULL ); } if( main_option_version ) printf( "vips-%s\n", vips_version_string() ); /* Reenable help and unknown option detection ready for the second * option parse. */ g_option_context_set_ignore_unknown_options( context, FALSE ); g_option_context_set_help_enabled( context, TRUE ); /* Try to find our action. */ handled = FALSE; action = NULL; /* Should we try to run the thing we are named as? */ if( !isvips( g_get_prgname() ) ) action = argv[0]; if( !action ) { /* Look for the first non-option argument, if any, and make * that our action. The parse above will have removed most of * them, but --help (for example) could still remain. */ for( i = 1; i < argc; i++ ) if( argv[i][0] != '-' ) { action = argv[i]; /* Remove the action from argv. */ for( j = i; j < argc; j++ ) argv[j] = argv[j + 1]; argc -= 1; break; } } /* Could be one of our built-in actions. */ if( action ) for( i = 0; i < VIPS_NUMBER( actions ); i++ ) if( strcmp( action, actions[i].name ) == 0 ) { group = add_operation_group( context, NULL ); g_option_group_add_entries( group, actions[i].group ); parse_options( context, &argc, argv ); if( actions[i].action( argc - 1, argv + 1 ) ) vips_error_exit( "%s", action ); handled = TRUE; break; } /* Could be a vips7 im_function. We need to test for vips7 first, * since we don't want to use the vips7 compat wrappers in vips8 * unless we have to. They don't support all args types. */ if( action && !handled && (fn = im_find_function( action )) ) { if( im_run_command( action, argc - 1, argv + 1 ) ) { if( argc == 1 ) usage( fn ); else vips_error_exit( NULL ); } handled = TRUE; } /* im_find_function() set an error msg. */ if( action && !handled ) vips_error_clear(); /* Could be a vips8 VipsOperation. */ if( action && !handled && (operation = vips_operation_new( action )) ) { group = add_operation_group( context, operation ); vips_call_options( group, operation ); parse_options( context, &argc, argv ); if( vips_call_argv( operation, argc - 1, argv + 1 ) ) { if( argc == 1 ) vips_operation_class_print_usage( VIPS_OPERATION_GET_CLASS( operation ) ); vips_object_unref_outputs( VIPS_OBJECT( operation ) ); g_object_unref( operation ); if( argc == 1 ) /* We don't exit with an error for something * like "vips fitsload" failing, we use it to * decide if an optional component has been * configured. If we've been built without * fits support, fitsload will fail to find * the operation and we'll error with "unknown * action" below. */ exit( 0 ); else vips_error_exit( NULL ); } vips_object_unref_outputs( VIPS_OBJECT( operation ) ); g_object_unref( operation ); handled = TRUE; } /* vips_operation_new() sets an error msg for unknown operation. */ if( action && !handled ) vips_error_clear(); if( action && !handled ) { vips_error_exit( _( "unknown action \"%s\"" ), action ); } /* Still not handled? We may not have called parse_options(), so * --help args may not have been processed. */ if( !handled ) parse_options( context, &argc, argv ); g_option_context_free( context ); vips_shutdown(); return( 0 ); }
22.5521
79
0.60682
[ "vector" ]
c57cc6a8d9a374eb67ed3a507c844df22ddb6b3d
99,316
h
C
include/cutlass/gemm/warp/mma_tensor_op_tile_iterator_sm70.h
igormp/cutlass
6dd610eee98afbf237b19dd02f81c52cca9eb428
[ "BSD-3-Clause" ]
28
2020-09-29T03:00:31.000Z
2022-03-29T12:38:52.000Z
include/cutlass/gemm/warp/mma_tensor_op_tile_iterator_sm70.h
Akimoto-Cris/cutlass
ccb697bac77fcc898e9c897b2c90aa5b60ac72fb
[ "BSD-3-Clause" ]
5
2020-10-10T13:48:42.000Z
2022-03-31T06:06:52.000Z
include/cutlass/gemm/warp/mma_tensor_op_tile_iterator_sm70.h
Akimoto-Cris/cutlass
ccb697bac77fcc898e9c897b2c90aa5b60ac72fb
[ "BSD-3-Clause" ]
9
2020-10-24T06:47:24.000Z
2022-01-21T15:32:56.000Z
/*************************************************************************************************** * Copyright (c) 2017-2020, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION 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 TOR (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 \brief Defines iterators used by warp-level matrix multiply operations targeting Tensor Cores. */ #pragma once #include "cutlass/cutlass.h" #include "cutlass/array.h" #include "cutlass/numeric_types.h" #include "cutlass/tensor_ref.h" #include "cutlass/matrix_shape.h" #include "cutlass/gemm/gemm.h" #include "cutlass/layout/matrix.h" #include "cutlass/layout/pitch_linear.h" #include "cutlass/layout/tensor_op_multiplicand_sm70.h" #include "cutlass/platform/platform.h" ///////////////////////////////////////////////////////////////////////////////////////////////// namespace cutlass { namespace gemm { namespace warp { ///////////////////////////////////////////////////////////////////////////////////////////////// template < /// Size of the matrix to load (concept: MatrixShape) typename Shape_, /// Operand identity Operand Operand, /// Data type of A elements typename Element_, /// Layout of operand typename Layout_, /// Shape of one matrix production operation (concept: GemmShape) typename InstructionShape_, /// Delta between *MMA operations (in units of *MMA operations, concept: /// MatrixShape) int OpDelta_, /// Number of threads participating in one matrix operation int Threads> class MmaVoltaTensorOpMultiplicandTileIterator; ///////////////////////////////////////////////////////////////////////////////////////////////// /// This tile iterator is specialized for 32-thread TensorOps. /// /// Satisfies: /// ReadableRandomAccessContiguousTileIteratorConcept /// template < /// Size of the matrix to load (concept: PitchLinearShape) typename Shape_, /// Data type of elements typename Element_, /// Shape of one matrix product operation (concept: PitchLinearShape) typename InstructionShape_, /// Interval between adjacent *MMA instructions (in units of MMA /// instructions) int OpDelta_> class MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand::kA, Element_, cutlass::layout::VoltaTensorOpMultiplicandCongruous< sizeof_bits<Element_>::value>, InstructionShape_, OpDelta_, 32> { public: /// Shape of tile to load (concept: PitchLinearShape) using Shape = Shape_; /// Operand tag static Operand const kOperand = Operand::kA; /// Element type using Element = Element_; /// Layout of source tile using Layout = cutlass::layout::VoltaTensorOpMultiplicandCongruous<sizeof_bits<Element_>::value>; /// Shape of one matrix product operation (concept: GemmShape) using InstructionShape = InstructionShape_; /// Delta between *MMA operations (in units of *MMA operations, concept: MatrixShape) static int const kOpDelta = OpDelta_; /// Number of participating threads static int const kThreads = 32; /// TensorRef type for loading element from a tensor using TensorRef = TensorRef<Element, Layout>; /// Index type using Index = typename TensorRef::Index; /// Long Index type using LongIndex = typename TensorRef::LongIndex; /// Coordinate for an element in the tensor using TensorCoord = typename TensorRef::TensorCoord; /// Internal structure of iterator - made public to enable introspection struct Policy { static_assert( !(Shape::kContiguous % InstructionShape::kContiguous), "Shape of warp-level Mma must be divisible by operator shape."); // Shape of one individual LDS.128 // TODO: 32 and 4 are hardcoded, 32-by-4 is logical shape using LdsShape = layout::PitchLinearShape< 32, 4 >; // LdsShapes are arranged in the strided direction in SMEM using LdsIterations = layout::PitchLinearShape< InstructionShape::kStrided / LdsShape::kStrided, Shape::kContiguous / LdsShape::kContiguous >; }; private: /// Not working on this feature at the moment. static_assert(kOpDelta == 1, "Alternative arrangements not supported at present."); /// Number of internal pointers needed to reference shared memory static int const kPointerCount = 2; /// Pointer type used for accesses using AccessType = AlignedArray<Element, Layout::kElementsPerAccess>; public: // // Derived quantities // /// Fragment object holding a thread's part of a tile using Fragment = Array<Element, Shape::kContiguous * InstructionShape::kStrided / kThreads * 2>; private: /// Layout object storing stride values Index stride_; /// Shared memory base pointers - not advanced AccessType const *pointer_[kPointerCount]; /// Byte offset incremented as iterator advances Index byte_offset_; public: /// Default ctor constructs null iterator CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator(): stride_(0), byte_offset_(0) { } /// Constructor from TensorRef CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator( TensorRef const &ref, int lane_id ): stride_(ref.stride(0) / Layout::kElementsPerAccess), byte_offset_(0) { // swizzle patterns for operandA LDS are // 1. (tid[4] << 3) | (tid[2:0] ^ tid[4]) // 2. (tid[4] << 3) | (tid[2:0] ^ tid[4] ^ 0b10010) int vec_row = (lane_id >> 4); // tid[4] int vec_col = ((lane_id & 4) >> 2); // tid[2] CUTLASS_PRAGMA_UNROLL for (int i = 0; i < kPointerCount; ++i) { if(i == 1) { vec_row |= 2; } int access_contiguous_idx = (vec_col << 2) | ((lane_id & 3) ^ vec_row); int access_contiguous = access_contiguous_idx; int access_strided = vec_row; pointer_[i] = reinterpret_cast<AccessType const *>(ref.data()) + access_contiguous + access_strided * stride_; } } /// Adds a pointer offset to internal pointer(s) to advance through memory CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &add_pointer_offset(LongIndex offset) { byte_offset_ += offset * sizeof(Element); return *this; } /// Advances an iterator along logical dimensions of matrix in units of whole tiles CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &add_tile_offset(TensorCoord const &tile_offset) { int contiguous_offset = tile_offset.contiguous(); int strided_offset = tile_offset.strided(); // To support 32x32 tile size if (Shape::kContiguous == Policy::LdsShape::kContiguous) { if (contiguous_offset % 2) { AccessType const *tmp_pointer = pointer_[0]; pointer_[0] = pointer_[1]; pointer_[1] = tmp_pointer; } contiguous_offset = contiguous_offset / 2; } int offset = (strided_offset * InstructionShape::kStrided) * stride_ * Layout::kElementsPerAccess + contiguous_offset * Shape::kContiguous; add_pointer_offset(offset); return *this; } /// Advances the iterator along the advance dimension CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator & operator++() { byte_offset_ += stride_ * InstructionShape::kStrided * sizeof(Element) * Layout::kElementsPerAccess; return *this; } /// Advances the iterator along the advance dimension CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator & operator--() { byte_offset_ -= stride_ * InstructionShape::kStrided * sizeof(Element) * Layout::kElementsPerAccess; return *this; } ///< advances in units of whole tiles along the logical coordinate space of the tensor CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator & operator+=(TensorCoord const &tile_offset) { add_tile_offset(tile_offset); return *this; } ///< advances in units of whole tiles along the logical coordinate space of the tensor CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator & operator-=(TensorCoord const &tile_offset) { add_tile_offset(-tile_offset); return *this; } /// Loads a fragment from memory at the location pointed to by the iterator. CUTLASS_HOST_DEVICE void load(Fragment &frag) const { load_with_byte_offset(frag, 0); } /// Loads a fragment from memory with additional logical offset CUTLASS_DEVICE void load_with_byte_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a linear offset in units of bytes Index byte_offset) const { AccessType * fetch_ptr = reinterpret_cast<AccessType *>(&frag); CUTLASS_PRAGMA_UNROLL for (int s = 0; s < Policy::LdsIterations::kStrided; ++s) { CUTLASS_PRAGMA_UNROLL for (int c = 0; c < Policy::LdsIterations::kContiguous; ++c) { int access_idx = c + s * Policy::LdsIterations::kContiguous; AccessType const *source_ptr = pointer_[s & 1] + Policy::LdsShape::kContiguous * c + Policy::LdsShape::kStrided * (s / 2) * stride_; char const *source_byte_ptr = reinterpret_cast<char const *>(source_ptr) + byte_offset + byte_offset_; fetch_ptr[access_idx] = *(reinterpret_cast<AccessType const*> (source_byte_ptr)); } } } /// Loads a fragment from memory with additional logical offset CUTLASS_DEVICE void load_with_pointer_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a linear offset Index pointer_offset) const { load_with_byte_offset(frag, pointer_offset * sizeof(Element)); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset) const { load_with_byte_offset(frag, tile_offset, 0); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset, /// loads a tile with a logical offset AND a pointer offset Index pointer_offset) const { load_with_byte_offset(frag, tile_offset, pointer_offset * sizeof(Element)); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load_with_byte_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset, /// loads a tile with a logical offset AND a pointer offset Index byte_offset) const { Index pointer_offset = tile_offset.contiguous() * Shape::kContiguous / Layout::kElementsPerAccess + tile_offset.strided() * InstructionShape::kStrided * stride_; byte_offset += sizeof(AccessType) * pointer_offset; load_with_byte_offset(frag, byte_offset); } /// Notify the iterator which k-group it is currently pointing to. /// /// This does not advance the iterator. Rather, it overrides its internal /// tracking with constant-valued k-group index to enable the compiler to /// fold constants and achieve more efficient code. /// /// This is used by some nontrivial permuted layouts. CUTLASS_DEVICE void set_kgroup_index(int k_group) { // no operation here } }; ////////////////////////////////////////////////////////////////////////////////////////////////////////// /// This tile iterator is specialized for 32-thread TensorOps. /// /// Satisfies: /// ReadableRandomAccessContiguousTileIteratorConcept /// template < /// Size of the matrix to load (concept: PitchLinearShape) typename Shape_, /// Data type of elements typename Element_, /// Shape of one matrix product operation (concept: PitchLinearShape) typename InstructionShape_, /// Interval between adjacent *MMA instructions (in units of MMA /// instructions) int OpDelta_> class MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand::kB, Element_, cutlass::layout::VoltaTensorOpMultiplicandBCongruous< sizeof_bits<Element_>::value>, InstructionShape_, OpDelta_, 32> { public: /// Shape of tile to load (concept: PitchLinearShape) using Shape = Shape_; /// Operand tag static Operand const kOperand = Operand::kB; /// Element type using Element = Element_; /// Layout of source tile using Layout = cutlass::layout::VoltaTensorOpMultiplicandBCongruous<sizeof_bits<Element_>::value>; /// Shape of one matrix product operation (concept: GemmShape) using InstructionShape = InstructionShape_; /// Delta between *MMA operations (in units of *MMA operations, concept: MatrixShape) static int const kOpDelta = OpDelta_; /// Number of participating threads static int const kThreads = 32; /// TensorRef type for loading element from a tensor using TensorRef = TensorRef<Element, Layout>; /// Index type using Index = typename TensorRef::Index; /// Long Index type using LongIndex = typename TensorRef::LongIndex; /// Coordinate for an element in the tensor using TensorCoord = typename TensorRef::TensorCoord; /// Internal structure of iterator - made public to enable introspection struct Policy { static_assert( !(Shape::kContiguous % InstructionShape::kContiguous), "Shape of warp-level Mma must be divisible by operator shape."); // Shape of one individual LDS // TODO: remove hardcoded 32 and 4 using LdsShape = layout::PitchLinearShape< 32, 4 >; using LdsIterations = layout::PitchLinearShape< Shape::kContiguous / LdsShape::kContiguous, InstructionShape::kStrided / LdsShape::kStrided >; }; private: /// Not working on this feature at the moment. static_assert(kOpDelta == 1, "Alternative arrangements not supported at present."); /// Pointer type used for accesses using AccessType = AlignedArray<Element, Layout::kElementsPerAccess>; public: // // Derived quantities // /// Fragment object holding a thread's part of a tile, needs on more time number of registers using Fragment = Array<Element, Shape::kContiguous * InstructionShape::kStrided / kThreads * 2>; private: /// Layout object storing stride values Index stride_; /// Shared memory base pointers - not advanced AccessType const *pointer_; /// Byte offset incremented as iterator advances Index byte_offset_; public: /// Default ctor constructs null iterator CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator(): stride_(0), byte_offset_(0) { } /// Constructor from TensorRef CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator( TensorRef const &ref, int lane_id ): stride_(ref.stride(0) / Layout::kElementsPerAccess), byte_offset_(0) { // swizzle pattern is (tid & (3 << 3) | (tid[1:0] ^ tid[4:3])) int access_strided = (lane_id >> 3) & 0x3; int access_contiguous = ((lane_id ^ (lane_id >> 3)) & 0x3); pointer_ = reinterpret_cast<AccessType const *>(ref.data()) + access_contiguous + access_strided * stride_; } /// Adds a pointer offset to internal pointer(s) to advance through memory CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &add_pointer_offset(LongIndex offset) { byte_offset_ += offset * sizeof(Element); return *this; } /// Advances an iterator along logical dimensions of matrix in units of whole tiles CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &add_tile_offset(TensorCoord const &tile_offset) { int contiguous_offset = tile_offset.contiguous(); int strided_offset = tile_offset.strided(); int offset = (strided_offset * InstructionShape::kStrided) * stride_ * Layout::kElementsPerAccess + contiguous_offset * Shape::kContiguous; add_pointer_offset(offset); return *this; } /// Advances the iterator along the advance dimension CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator & operator++() { byte_offset_ += stride_ * InstructionShape::kStrided * sizeof(Element) * Layout::kElementsPerAccess; return *this; } /// Advances the iterator along the advance dimension CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator & operator--() { byte_offset_ += stride_ * InstructionShape::kStrided * sizeof(Element) * Layout::kElementsPerAccess; return *this; } ///< advances in units of whole tiles along the logical coordinate space of the tensor CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator & operator+=(TensorCoord const &tile_offset) { add_tile_offset(tile_offset); return *this; } ///< advances in units of whole tiles along the logical coordinate space of the tensor CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator & operator-=(TensorCoord const &tile_offset) { add_tile_offset(-tile_offset); return *this; } /// Loads a fragment from memory at the location pointed to by the iterator. CUTLASS_HOST_DEVICE void load(Fragment &frag) const { load_with_byte_offset(frag, 0); } /// Loads a fragment from memory with additional logical offset CUTLASS_DEVICE void load_with_byte_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a linear offset in units of bytes Index byte_offset) const { AccessType * fetch_ptr = reinterpret_cast<AccessType *>(&frag); CUTLASS_PRAGMA_UNROLL for (int s = 0; s < Policy::LdsIterations::kStrided; ++s) { CUTLASS_PRAGMA_UNROLL for (int c = 0; c < Policy::LdsIterations::kContiguous; ++c) { int access_idx = c + s * Policy::LdsIterations::kContiguous; AccessType const *source_ptr = pointer_ + Policy::LdsShape::kContiguous / Layout::kElementsPerAccess * c + Policy::LdsShape::kStrided * s * stride_; char const *source_byte_ptr = reinterpret_cast<char const *>(source_ptr) + byte_offset + byte_offset_; fetch_ptr[access_idx] = *(reinterpret_cast<AccessType const*> (source_byte_ptr)); } } } /// Loads a fragment from memory with additional logical offset CUTLASS_DEVICE void load_with_pointer_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a linear offset Index pointer_offset) const { load_with_byte_offset(frag, pointer_offset * sizeof(Element)); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset) const { load_with_byte_offset(frag, tile_offset, 0); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset, /// loads a tile with a logical offset AND a pointer offset Index pointer_offset) const { load_with_byte_offset(frag, tile_offset, pointer_offset * sizeof(Element)); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load_with_byte_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset, /// loads a tile with a logical offset AND a pointer offset Index byte_offset) const { Index pointer_offset = tile_offset.contiguous() * Shape::kContiguous / Layout::kElementsPerAccess + tile_offset.strided() * InstructionShape::kStrided * stride_; byte_offset += sizeof(AccessType) * pointer_offset; load_with_byte_offset(frag, byte_offset); } /// Notify the iterator which k-group it is currently pointing to. /// /// This does not advance the iterator. Rather, it overrides its internal /// tracking with constant-valued k-group index to enable the compiler to /// fold constants and achieve more efficient code. /// /// This is used by some nontrivial permuted layouts. CUTLASS_DEVICE void set_kgroup_index(int k_group) { // no operation here } }; ////////////////////////////////////////////////////////////////////////////////////////////////////////// /// This tile iterator is specialized for 32-thread TensorOps. It uses LDSM to load from shared /// memory and therefore must be initialized with a TensorRef to shared memory. /// /// Satisfies: /// ReadableRandomAccessContiguousTileIteratorConcept /// template < /// Size of the matrix to load (concept: MatrixShape) typename Shape_, /// Data type of elements typename Element_, /// Shape of one matrix product operation (concept: MatrixShape) typename InstructionShape_, /// Interval between adjacent *MMA instructions (in units of MMA /// instructions) int OpDelta_> class MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand::kA, Element_, cutlass::layout::ColumnMajorVoltaTensorOpMultiplicandCongruous< sizeof_bits<Element_>::value>, InstructionShape_, OpDelta_, 32> { public: /// Shape of tile to load (concept: PitchLinearShape) using Shape = Shape_; /// Operand tag static Operand const kOperand = Operand::kA; /// Element type using Element = Element_; /// Layout of source tile using Layout = cutlass::layout::ColumnMajorVoltaTensorOpMultiplicandCongruous<sizeof_bits<Element_>::value>; /// Shape of one matrix product operation (concept: MatrixShape) using InstructionShape = InstructionShape_; /// Delta between *MMA operations (in units of *MMA operations, concept: MatrixShape) static int const kOpDelta = OpDelta_; /// Number of participating threads static int const kThreads = 32; /// TensorRef type for loading element from a tensor using TensorRef = TensorRef<Element, Layout>; /// Index type using Index = typename TensorRef::Index; /// Long Index type using LongIndex = typename TensorRef::LongIndex; /// Coordinate for an element in the tensor using TensorCoord = typename TensorRef::TensorCoord; /// Underlying tile iterator implementation using Base = MmaVoltaTensorOpMultiplicandTileIterator< layout::PitchLinearShape<Shape::kRow, Shape::kColumn>, kOperand, Element, layout::VoltaTensorOpMultiplicandCongruous<sizeof_bits<Element_>::value>, layout::PitchLinearShape<InstructionShape::kRow, InstructionShape::kColumn>, kOpDelta, kThreads>; public: // // Derived quantities // /// Fragment object holding a thread's part of a tile using Fragment = typename Base::Fragment; private: /// Underlying tile iterator Base iterator_; public: /// Default ctor constructs null iterator CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator() { } /// Constructor from TensorRef CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator( TensorRef const &ref, int lane_id ): iterator_({ref.data(), ref.stride()}, lane_id) { } /// Adds a pointer offset to internal pointer(s) to advance through memory CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &add_pointer_offset(LongIndex offset) { iterator_.add_pointer_offset(offset); return *this; } /// Advances an iterator along logical dimensions of matrix in units of whole tiles CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &add_tile_offset(TensorCoord const &tile_offset) { iterator_.add_tile_offset({tile_offset.row(), tile_offset.column()}); return *this; } /// Advances the iterator along the advance dimension CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator & operator++() { ++iterator_; return *this; } /// Advances the iterator along the advance dimension CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator & operator--() { --iterator_; return *this; } ///< advances in units of whole tiles along the logical coordinate space of the tensor CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator & operator+=(TensorCoord const &tile_offset) { add_tile_offset(PitchLinearCoord(tile_offset.row(), tile_offset.column())); return *this; } ///< advances in units of whole tiles along the logical coordinate space of the tensor CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator & operator-=(TensorCoord const &tile_offset) { add_tile_offset(-PitchLinearCoord(tile_offset.row(), tile_offset.column())); return *this; } /// Loads a fragment from memory at the location pointed to by the iterator. CUTLASS_HOST_DEVICE void load(Fragment &frag) const { iterator_.load(frag); } /// Loads a fragment from memory with additional logical offset CUTLASS_DEVICE void load_with_pointer_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a linear offset Index pointer_offset) const { iterator_.load_with_pointer_offset(frag, pointer_offset); } /// Loads a fragment from memory with additional logical offset CUTLASS_DEVICE void load_with_byte_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a linear offset Index byte_offset) const { iterator_.load_with_byte_offset(frag, byte_offset); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset) const { // TODO } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset, /// loads a tile with a logical offset AND a pointer offset Index pointer_offset) const { // TODO } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load_with_byte_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset, /// loads a tile with a logical offset AND a pointer offset Index byte_offset) const { iterator_.load_with_byte_offset( frag, {tile_offset.contiguous(), tile_offset.strided()}, byte_offset); } /// Notify the iterator which k-group it is currently pointing to. /// /// This does not advance the iterator. Rather, it overrides its internal /// tracking with constant-valued k-group index to enable the compiler to /// fold constants and achieve more efficient code. /// /// This is used by some nontrivial permuted layouts. CUTLASS_DEVICE void set_kgroup_index(int k_group) { iterator_.set_kgroup_index(k_group); } }; ///////////////////////////////////////////////////////////////////////////////////////////////// /// This tile iterator is specialized for 32-thread TensorOps. It uses LDSM to load from shared /// memory and therefore must be initialized with a TensorRef to shared memory. /// /// Satisfies: /// ReadableRandomAccessContiguousTileIteratorConcept /// template < /// Size of the matrix to load (concept: MatrixShape) typename Shape_, /// Data type of elements typename Element_, /// Shape of one matrix product operation (concept: MatrixShape) typename InstructionShape_, /// Interval between adjacent *MMA instructions (in units of MMA /// instructions) int OpDelta_> class MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand::kB, Element_, cutlass::layout::RowMajorVoltaTensorOpMultiplicandBCongruous< sizeof_bits<Element_>::value>, InstructionShape_, OpDelta_, 32> { public: /// Shape of tile to load (concept: PitchLinearShape) using Shape = Shape_; /// Operand tag static Operand const kOperand = Operand::kB; static_assert(kOperand == Operand::kA || kOperand== Operand::kB, "MmaTensorOpMultiplicandIterator may only be instantiated for A or B operands to warp-level Mma."); /// Element type using Element = Element_; /// Layout of source tile using Layout = cutlass::layout::RowMajorVoltaTensorOpMultiplicandBCongruous<sizeof_bits<Element_>::value>; /// Shape of one matrix product operation (concept: MatrixShape) using InstructionShape = InstructionShape_; /// Delta between *MMA operations (in units of *MMA operations, concept: MatrixShape) static int const kOpDelta = OpDelta_; /// Number of participating threads static int const kThreads = 32; /// TensorRef type for loading element from a tensor using TensorRef = TensorRef<Element, Layout>; /// Index type using Index = typename TensorRef::Index; /// Long Index type using LongIndex = typename TensorRef::LongIndex; /// Coordinate for an element in the tensor using TensorCoord = typename TensorRef::TensorCoord; /// Underlying tile iterator implementation using Base = MmaVoltaTensorOpMultiplicandTileIterator< layout::PitchLinearShape<Shape::kColumn, Shape::kRow>, kOperand, Element, layout::VoltaTensorOpMultiplicandBCongruous<sizeof_bits<Element_>::value>, layout::PitchLinearShape<InstructionShape::kColumn, InstructionShape::kRow>, kOpDelta, kThreads>; public: // // Derived quantities // /// Fragment object holding a thread's part of a tile using Fragment = typename Base::Fragment; private: /// Underlying tile iterator Base iterator_; public: /// Default ctor constructs null iterator CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator() { } /// Constructor from TensorRef CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator( TensorRef const &ref, int lane_id ): iterator_({ref.data(), ref.stride()}, lane_id) { } /// Adds a pointer offset to internal pointer(s) to advance through memory CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &add_pointer_offset(LongIndex offset) { iterator_.add_pointer_offset(offset); return *this; } /// Advances an iterator along logical dimensions of matrix in units of whole tiles CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &add_tile_offset(TensorCoord const &tile_offset) { iterator_.add_tile_offset({tile_offset.column(), tile_offset.row()}); return *this; } /// Advances the iterator along the advance dimension CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator & operator++() { ++iterator_; return *this; } /// Advances the iterator along the advance dimension CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator & operator--() { --iterator_; return *this; } ///< advances in units of whole tiles along the logical coordinate space of the tensor CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator & operator+=(TensorCoord const &tile_offset) { add_tile_offset(PitchLinearCoord(tile_offset.column(), tile_offset.row())); return *this; } ///< advances in units of whole tiles along the logical coordinate space of the tensor CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator & operator-=(TensorCoord const &tile_offset) { add_tile_offset(-PitchLinearCoord(tile_offset.column(), tile_offset.row())); return *this; } /// Loads a fragment from memory at the location pointed to by the iterator. CUTLASS_HOST_DEVICE void load(Fragment &frag) const { iterator_.load(frag); } /// Loads a fragment from memory with additional logical offset CUTLASS_DEVICE void load_with_pointer_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a linear offset Index pointer_offset) const { iterator_.load_with_pointer_offset(frag, pointer_offset); } /// Loads a fragment from memory with additional logical offset CUTLASS_DEVICE void load_with_byte_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a linear offset Index byte_offset) const { iterator_.load_with_byte_offset(frag, byte_offset); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset) const { // TODO } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset, /// loads a tile with a logical offset AND a pointer offset Index pointer_offset) const { // TODO } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load_with_byte_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset, /// loads a tile with a logical offset AND a pointer offset Index byte_offset) const { iterator_.load_with_byte_offset( frag, {tile_offset.strided(), tile_offset.contiguous()}, byte_offset); } /// Notify the iterator which k-group it is currently pointing to. /// /// This does not advance the iterator. Rather, it overrides its internal /// tracking with constant-valued k-group index to enable the compiler to /// fold constants and achieve more efficient code. /// /// This is used by some nontrivial permuted layouts. CUTLASS_DEVICE void set_kgroup_index(int k_group) { iterator_.set_kgroup_index(k_group); } }; //////////////////////////////////////////////////////////////////////////////////////// /// This tile iterator is specialized for 32-thread TensorOps. It is used to load or store /// accumulators from memory and is agnostic to layout. It could be faster if it assumed row-major /// accumulator layout. /// /// Satisfies: /// ReadableRandomAccessContiguousTileIteratorConcept | /// WriteableRandomAccessContiguousTileIteratorConcept /// template < /// Size of the matrix to load (concept: MatrixShape) typename Shape_, /// Data type of elements typename Element_, /// Layout of operand in memory typename Layout_, /// Shape of one matrix product operation (concept: MatrixShape) typename InstructionShape_, /// Interval between adjacent *MMA instructions (in units of MMA /// instructions, concept: MatrixShape) typename OpDelta_> class MmaVoltaTensorOpAccumulatorTileIterator { public: /// Shape of tile to load (concept: MatrixShape) using Shape = Shape_; /// Operand tag static Operand const kOperand = Operand::kC; /// Element type using Element = Element_; /// Layout of source tile using Layout = Layout_; /// Shape of one matrix product operation (concept: MatrixShape) using InstructionShape = InstructionShape_; /// Delta between *MMA operations (in units of *MMA operations, concept: MatrixShape) using OpDelta = OpDelta_; /// Number of participating threads static int const kThreads = 32; /// TensorRef type for loading element from a tensor using TensorRef = TensorRef<Element, Layout>; /// Index type using Index = typename TensorRef::Index; /// Long Index type using LongIndex = typename TensorRef::LongIndex; /// Coordinate for an element in the tensor using TensorCoord = typename TensorRef::TensorCoord; /// Internal structure of iterator - made public to enable introspection struct Policy { /// Volta Tensor Op uses 32x32 interleaved tile using InterleavedTile = MatrixShape<32, 32>; static_assert(!(Shape::kRow % InterleavedTile::kRow) && !(Shape::kColumn % InterleavedTile::kColumn), "Shape of warp-level Mma must be divisible by operator shape."); static_assert(platform::is_same<TensorCoord, MatrixCoord>::value, "Layouts must be defined for logical MatrixCoord coordinate space."); /// Number of mma operations performed using TileIterations = MatrixShape< Shape::kRow / InterleavedTile::kRow, Shape::kColumn / InterleavedTile::kColumn >; using MmaIterations = MatrixShape<InterleavedTile::kRow / InstructionShape::kM, InterleavedTile::kColumn / InstructionShape::kN>; }; private: // Assume accumulator tile is multipile interleaved 32x32 tile. static int const kElementsPerPartial = 4; using EleShapePerPatial = typename platform::conditional< platform::is_same<Element, float>::value, MatrixShape<2, 2>, MatrixShape<1, 4> >::type; static int const kElementsPerMma = 8; static int const kAccumulatorPatials = 2; using QuadShapePerPatialMma = MatrixShape<4, 4>; public: // // Derived quantities // /// Fragment object holding a thread's part of a tile using Fragment = Array<Element, Shape::kCount / kThreads>; private: /// Reference to output tensor TensorRef ref_; public: /// Default ctor constructs null iterator CUTLASS_HOST_DEVICE MmaVoltaTensorOpAccumulatorTileIterator() { } /// Constructor from TensorRef CUTLASS_HOST_DEVICE MmaVoltaTensorOpAccumulatorTileIterator( TensorRef const &ref, int lane_id ): ref_(ref) { int quad = (lane_id >> 2); int lane_in_quad = (lane_id & 3); int accum_m, accum_n; if (platform::is_same<Element, float>::value) { // (quad[2],quad[0])+lane_in_quad[0] accum_m = (((quad & 0x4) >> 1) + (quad & 0x1)) * 8 + (lane_in_quad & 1); // (quad[1])+lane_in_quad[1] accum_n = ((quad >> 1) & 0x1) * kElementsPerPartial * kAccumulatorPatials + (lane_in_quad & 2); } else { accum_m = (((quad & 0x4) >> 1) + (quad & 0x1)) * 8 + lane_in_quad; // (quad[2],quad[0]) accum_n = ((quad >> 1) & 0x1) * kElementsPerPartial * kAccumulatorPatials; } MatrixCoord lane_offset(accum_m, accum_n); ref_.add_coord_offset(lane_offset); } /// Adds a pointer offset to internal pointer(s) to advance through memory CUTLASS_HOST_DEVICE MmaVoltaTensorOpAccumulatorTileIterator &add_pointer_offset(LongIndex offset) { ref_.add_pointer_offset(offset); return *this; } /// Advances an iterator along logical dimensions of matrix in units of whole tiles CUTLASS_HOST_DEVICE MmaVoltaTensorOpAccumulatorTileIterator &add_tile_offset(TensorCoord const &tile_offset) { ref_.add_coord_offset(tile_offset * make_Coord(Shape::kRow, Shape::kColumn)); return *this; } /// Advances the iterator along the advance dimension CUTLASS_HOST_DEVICE MmaVoltaTensorOpAccumulatorTileIterator & operator++() { // deliberate no-op return *this; } /// Advances the iterator along the advance dimension CUTLASS_HOST_DEVICE MmaVoltaTensorOpAccumulatorTileIterator & operator--() { // deliberate no-op return *this; } ///< advances in units of whole tiles along the logical coordinate space of the tensor CUTLASS_DEVICE MmaVoltaTensorOpAccumulatorTileIterator & operator+=(TensorCoord const &tile_offset) { add_tile_offset(tile_offset); return *this; } ///< advances in units of whole tiles along the logical coordinate space of the tensor CUTLASS_DEVICE MmaVoltaTensorOpAccumulatorTileIterator & operator-=(TensorCoord const &tile_offset) { add_tile_offset(-tile_offset); return *this; } /// Loads a fragment from memory at the location pointed to by the iterator. CUTLASS_HOST_DEVICE void load(Fragment &frag) const { load_with_pointer_offset(frag, 0); } /// Loads a fragment from memory with additional logical offset CUTLASS_HOST_DEVICE void load_with_pointer_offset( Fragment &frag, ///< fragment to load from the tensor Index pointer_offset) const { ///< loads a tile with a linear offset TensorRef offset_ref(ref_); offset_ref.add_pointer_offset(pointer_offset); CUTLASS_PRAGMA_UNROLL for (int tile_n = 0; tile_n < Policy::TileIterations::kColumn; ++tile_n) { CUTLASS_PRAGMA_UNROLL for (int tile_m = 0; tile_m < Policy::TileIterations::kRow; ++tile_m) { CUTLASS_PRAGMA_UNROLL for (int mma_n = 0; mma_n < Policy::MmaIterations::kColumn; ++mma_n) { CUTLASS_PRAGMA_UNROLL for (int mma_m = 0; mma_m < Policy::MmaIterations::kRow; ++mma_m) { int mma_accum_start = (((tile_n * Policy::TileIterations::kRow + tile_m) * Policy::MmaIterations::kColumn + mma_n) * Policy::MmaIterations::kRow + mma_m) * kElementsPerMma; CUTLASS_PRAGMA_UNROLL for (int p = 0; p < kAccumulatorPatials; ++p) { CUTLASS_PRAGMA_UNROLL for (int m = 0; m < EleShapePerPatial::kRow; ++m) { CUTLASS_PRAGMA_UNROLL for (int n = 0; n < EleShapePerPatial::kColumn; ++n) { int accum_m = tile_m * Policy::InterleavedTile::kRow + mma_m * QuadShapePerPatialMma::kRow + m * 2; int accum_n = tile_n * Policy::InterleavedTile::kColumn + mma_n * QuadShapePerPatialMma::kColumn + p * Policy::InterleavedTile::kColumn/2 + n; int idx = mma_accum_start + p * kElementsPerPartial + m * EleShapePerPatial::kColumn + n; frag[idx] = offset_ref.at({accum_m, accum_n}); } } } } } } } } /// Loads a fragment from memory with additional logical offset CUTLASS_DEVICE void load_with_byte_offset( Fragment &frag, ///< fragment to load from the tensor Index byte_offset) const { ///< loads a tile with a linear offset load_with_pointer_offset(byte_offset / sizeof(Element)); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_HOST_DEVICE void load( Fragment &frag, ///< fragment to load from the tensor TensorCoord const &tile_offset) const { ///< loads a tile with a logical offset in units of whole tiles load(frag, tile_offset, 0); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_HOST_DEVICE void load( Fragment &frag, ///< fragment to load from the tensor TensorCoord const &tile_offset, ///< loads a tile with a logical offset in units of whole tiles Index pointer_offset) const { ///< loads a tile with a logical offset AND a pointer offset load_with_pointer_offset(frag, ref_.offset(tile_offset) + pointer_offset); } /// Stores a fragment to memory CUTLASS_HOST_DEVICE void store(Fragment const &frag) const { store_with_pointer_offset(frag, 0); } /// Stores a fragment to memory with additional pointer offset CUTLASS_HOST_DEVICE void store_with_pointer_offset( Fragment const &frag, ///< fragment to store from the tensor Index pointer_offset) const { ///< store a tile with a linear offset TensorRef offset_ref(ref_); offset_ref.add_pointer_offset(pointer_offset); CUTLASS_PRAGMA_UNROLL for (int tile_n = 0; tile_n < Policy::TileIterations::kColumn; ++tile_n) { CUTLASS_PRAGMA_UNROLL for (int tile_m = 0; tile_m < Policy::TileIterations::kRow; ++tile_m) { CUTLASS_PRAGMA_UNROLL for (int mma_n = 0; mma_n < Policy::MmaIterations::kColumn; ++mma_n) { CUTLASS_PRAGMA_UNROLL for (int mma_m = 0; mma_m < Policy::MmaIterations::kRow; ++mma_m) { int mma_accum_start = (((tile_n * Policy::TileIterations::kRow + tile_m) * Policy::MmaIterations::kColumn + mma_n) * Policy::MmaIterations::kRow + mma_m) * kElementsPerMma; CUTLASS_PRAGMA_UNROLL for (int p = 0; p < kAccumulatorPatials; ++p) { CUTLASS_PRAGMA_UNROLL for (int m = 0; m < EleShapePerPatial::kRow; ++m) { CUTLASS_PRAGMA_UNROLL for (int n = 0; n < EleShapePerPatial::kColumn; ++n) { int accum_m = tile_m * Policy::InterleavedTile::kRow + mma_m * QuadShapePerPatialMma::kRow + m * 2; int accum_n = tile_n * Policy::InterleavedTile::kColumn + mma_n * QuadShapePerPatialMma::kColumn + p * Policy::InterleavedTile::kColumn/2 + n; int idx = mma_accum_start + p * kElementsPerPartial + m * EleShapePerPatial::kColumn + n; offset_ref.at({accum_m, accum_n}) = frag[idx]; } } } } } } } } /// Stores a fragment to memory with additional pointer offset CUTLASS_HOST_DEVICE void store_with_byte_offset( Fragment const &frag, ///< fragment to store from the tensor Index byte_offset) const { ///< store a tile with a linear offset store_with_pointer_offset(byte_offset / sizeof(Element)); } /// Stores a fragment to memory with logical offset in units of whole tiles. CUTLASS_HOST_DEVICE void store( Fragment &frag, ///< fragment to store to the tensor TensorCoord const &tile_offset) const { ///< stores a tile with a logical offset in units of whole tiles store(frag, tile_offset, 0); } /// Stores a fragment from memory with logical offset in units of whole tiles. CUTLASS_HOST_DEVICE void store( /// fragment to store to the tensor Fragment const &frag, /// stores a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset, /// stores a tile with a logical offset AND a pointer offset Index pointer_offset) const { store_with_pointer_offset(frag, ref_.offset(tile_offset) + pointer_offset); } }; /// This tile iterator is specialized for 32-thread TensorOps. It uses LDS to /// load from shared memory and therefore must be initialized with a TensorRef /// to shared memory. /// /// Satisfies: /// ReadableRandomAccessContiguousTileIteratorConcept /// template < /// Size of the matrix to load (concept: PitchLinearShape) typename Shape_, /// Identifies A or B multiplicand Operand Operand_, /// Data type of elements typename Element_, /// Shape of one matrix product operation (concept: PitchLinearShape) typename InstructionShape_, /// Interval between adjacent *MMA instructions (in units of MMA /// instructions) int OpDelta_, /// KBlock size (in units of elements) int KBlock> class MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand_, Element_, cutlass::layout::VoltaTensorOpMultiplicandCrosswise< sizeof_bits<Element_>::value, KBlock>, InstructionShape_, OpDelta_, 32> { public: /// Shape of tile to load (concept: PitchLinearShape) using Shape = Shape_; /// Operand tag static Operand const kOperand = Operand_; static_assert(kOperand == Operand::kA || kOperand == Operand::kB, "MmaVoltaTensorOpMultiplicandIterator may only be instantiated for " "A or B operands to warp-level Mma."); /// Element type using Element = Element_; /// KBlock size static int const kKBlock = KBlock; /// Layout of source tile using Layout = cutlass::layout::VoltaTensorOpMultiplicandCrosswise< sizeof_bits<Element_>::value, kKBlock>; /// Shape of one matrix product operation (concept: GemmShape) using InstructionShape = InstructionShape_; /// Delta between *MMA operations (in units of *MMA operations, concept: /// MatrixShape) static int const kOpDelta = OpDelta_; /// Number of participating threads static int const kThreads = 32; /// TensorRef type for loading element from a tensor using TensorRef = TensorRef<Element, Layout>; /// Index type using Index = typename TensorRef::Index; /// Long Index type using LongIndex = typename TensorRef::LongIndex; /// Coordinate for an element in the tensor using TensorCoord = typename TensorRef::TensorCoord; /// Internal structure of iterator - made public to enable introspection struct Policy { /// Shape of one individual LDS instruction using LdsShape = layout::PitchLinearShape<1, 32>; /// Number and arrangement of LDSM instructions using LdsIterations = layout::PitchLinearShape<1, Shape::kStrided / 32>; /// Using LDS.128 static int const kElementsPerAccess = 8; /// Contiguous elements per line static int const kContiguousElementsPerLine = 4; }; private: /// Not working on this feature at the moment. static_assert(kOpDelta == 1, "Alternative arrangements not supported at present."); /// Pointer type used for accesses using AccessType = AlignedArray<Element, Policy::kElementsPerAccess>; public: // // Derived quantities // /// Fragment object holding a thread's part of a tile using Fragment = Array<Element, Shape::kStrided * InstructionShape::kContiguous / kThreads * 2>; private: /// Layout object storing stride values Index stride_; /// Shared memory base pointers - not advanced AccessType const *pointer_; /// Byte offset incremented as iterator advances Index byte_offset_; /// Crosswised elements are arranged in a SMEM line /// in units of AccessType Index line_size; /// Internal counter used to determine load addr offset /// and when to swap higher 64bit with lower 64bit int k_group_idx_; public: /// Default ctor constructs null iterator CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator() : pointer_(nullptr), stride_(0), line_size(0), byte_offset_(0), k_group_idx_(0) {} /// Constructor from TensorRef CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator(TensorRef const &ref, int lane_id) : pointer_(reinterpret_cast<AccessType const *>(ref.data())), stride_(ref.stride(0) * Policy::kElementsPerAccess), line_size((ref.stride(0) * Policy::kContiguousElementsPerLine) / Policy::kElementsPerAccess), k_group_idx_(0), byte_offset_(0) { int quad = (lane_id / 4); int lane_in_quad = (lane_id % 4); int access_contiguous; if(kOperand == Operand::kA) { // swizzle id: tid[4]|tid[1:0]|(tid[2]^tid[4]) access_contiguous = ((quad & 0x4) << 1) + ((lane_in_quad) << 1) + ((quad & 0x1) ^ ((quad & 0x4) >> 2)); } else { // swizzle id: tid[4]|tid[1:0]|tid[3] access_contiguous = ((quad & 0x4) << 1) + (lane_in_quad << 1) + ((quad & 0x2) >> 1 ^ ((quad & 0x4) >> 2)); } byte_offset_ = access_contiguous * sizeof(Element) * Policy::kElementsPerAccess; } /// Adds a pointer offset to internal pointer(s) to advance through memory CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &add_pointer_offset(LongIndex offset) { byte_offset_ += offset * sizeof(Element); return *this; } /// Advances an iterator along logical dimensions of matrix in units of whole /// tiles CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &add_tile_offset( TensorCoord const &tile_offset) { int contiguous_offset = tile_offset.contiguous(); int strided_offset = tile_offset.strided(); k_group_idx_ = 0; pointer_ += contiguous_offset * (InstructionShape::kContiguous / Policy::kContiguousElementsPerLine) * line_size + strided_offset * Shape::kStrided / 2; return *this; } /// Advances the iterator along the advance dimension CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &operator++() { k_group_idx_ = (k_group_idx_ + 1) % 8; if (k_group_idx_ == 4 || k_group_idx_ == 0) { byte_offset_ ^= 1 * sizeof(Element) * Policy::kElementsPerAccess; } pointer_ += line_size; return *this; } /// Advances the iterator along the advance dimension CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &operator--() { assert(0); } ///< advances in units of whole tiles along the logical coordinate space of ///< the tensor CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &operator+=( TensorCoord const &tile_offset) { add_tile_offset(tile_offset); return *this; } ///< advances in units of whole tiles along the logical coordinate space of ///< the tensor CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &operator-=( TensorCoord const &tile_offset) { add_tile_offset(-tile_offset); return *this; } /// Loads a fragment from memory at the location pointed to by the iterator. CUTLASS_HOST_DEVICE void load(Fragment &frag) const { load_with_byte_offset(frag, 0); } /// Loads a fragment from memory with additional logical offset CUTLASS_DEVICE void load_with_byte_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a linear offset in units of bytes Index byte_offset) const { AccessType * fetch_ptr = reinterpret_cast<AccessType *>(&frag); CUTLASS_PRAGMA_UNROLL for (int s = 0; s < Policy::LdsIterations::kStrided; ++s) { CUTLASS_PRAGMA_UNROLL for (int c = 0; c < Policy::LdsIterations::kContiguous; ++c) { int access_idx = c + s * Policy::LdsIterations::kContiguous; AccessType const *source_ptr = pointer_ + Policy::LdsShape::kContiguous * c * line_size + Policy::LdsShape::kStrided * s / 2; char const *source_byte_ptr = reinterpret_cast<char const *>(source_ptr) + byte_offset + byte_offset_; fetch_ptr[access_idx] = *(reinterpret_cast<AccessType const*> (source_byte_ptr)); // swap higher 64bit and lower 64bit if (k_group_idx_ & 0x2) { uint64_t *low = reinterpret_cast<uint64_t *>(&frag) + access_idx * 2; uint64_t *high = reinterpret_cast<uint64_t *>(&frag) + access_idx * 2 + 1; uint64_t tmp = *low; *low = *high; *high = tmp; } } } } /// Loads a fragment from memory with additional logical offset CUTLASS_DEVICE void load_with_pointer_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a linear offset Index pointer_offset) const { load_with_byte_offset(frag, pointer_offset * sizeof(Element)); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset) const { load_with_byte_offset(frag, tile_offset, 0); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset, /// loads a tile with a logical offset AND a pointer offset Index pointer_offset) const { load_with_byte_offset(frag, tile_offset, pointer_offset * sizeof(Element)); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load_with_byte_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset, /// loads a tile with a logical offset AND a pointer offset Index byte_offset) const { Index pointer_offset = tile_offset.contiguous() * InstructionShape::kContiguous / Policy::kElementsPerAccess + tile_offset.strided() * Shape::kStrided * stride_; byte_offset += sizeof(AccessType) * pointer_offset; load_with_byte_offset(frag, byte_offset); } /// Notify the iterator which k-group it is currently pointing to. /// /// This does not advance the iterator. Rather, it overrides its internal /// tracking with constant-valued k-group index to enable the compiler to /// fold constants and achieve more efficient code. /// /// This is used by some nontrivial permuted layouts. CUTLASS_DEVICE void set_kgroup_index(int k_group) { k_group_idx_ = k_group; } }; /// This tile iterator is specialized for 32-thread TensorOps. It uses LDS to /// load from shared memory and therefore must be initialized with a TensorRef /// to shared memory. /// /// Satisfies: /// ReadableRandomAccessContiguousTileIteratorConcept /// template < /// Size of the matrix to load (concept: MatrixShape) typename Shape_, /// Identifies A or B multiplicand Operand Operand_, /// Data type of elements typename Element_, /// Shape of one matrix product operation (concept: MatrixShape) typename InstructionShape_, /// Interval between adjacent *MMA instructions (in units of MMA /// instructions) int OpDelta_, /// KBlock size (in units of elements) int KBlock> class MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand_, Element_, cutlass::layout::ColumnMajorVoltaTensorOpMultiplicandCrosswise< sizeof_bits<Element_>::value, KBlock>, InstructionShape_, OpDelta_, 32> { public: /// Shape of tile to load (concept: PitchLinearShape) using Shape = Shape_; /// Operand tag static Operand const kOperand = Operand_; static_assert(kOperand == Operand::kA || kOperand == Operand::kB, "MmaTensorOpMultiplicandIterator may only be instantiated for " "A or B operands to warp-level Mma."); /// Element type using Element = Element_; /// KBlock size static int const kKBlock = KBlock; /// Layout of source tile using Layout = cutlass::layout::ColumnMajorVoltaTensorOpMultiplicandCrosswise< sizeof_bits<Element_>::value, kKBlock>; /// Shape of one matrix product operation (concept: MatrixShape) using InstructionShape = InstructionShape_; /// Delta between *MMA operations (in units of *MMA operations, concept: /// MatrixShape) static int const kOpDelta = OpDelta_; /// Number of participating threads static int const kThreads = 32; /// TensorRef type for loading element from a tensor using TensorRef = TensorRef<Element, Layout>; /// Index type using Index = typename TensorRef::Index; /// Long Index type using LongIndex = typename TensorRef::LongIndex; /// Coordinate for an element in the tensor using TensorCoord = typename TensorRef::TensorCoord; /// Underlying tile iterator implementation using Base = MmaVoltaTensorOpMultiplicandTileIterator< layout::PitchLinearShape<Shape::kRow, Shape::kColumn>, kOperand, Element, layout::VoltaTensorOpMultiplicandCrosswise<sizeof_bits<Element_>::value, kKBlock>, layout::PitchLinearShape<InstructionShape::kRow, InstructionShape::kColumn>, kOpDelta, kThreads>; public: // // Derived quantities // /// Fragment object holding a thread's part of a tile using Fragment = typename Base::Fragment; private: /// Underlying tile iterator Base iterator_; public: /// Default ctor constructs null iterator CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator() {} /// Constructor from TensorRef CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator(TensorRef const &ref, int lane_id) : iterator_({ref.data(), ref.stride()}, lane_id) {} /// Adds a pointer offset to internal pointer(s) to advance through memory CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &add_pointer_offset(LongIndex offset) { iterator_.add_pointer_offset(offset); return *this; } /// Advances an iterator along logical dimensions of matrix in units of whole /// tiles CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &add_tile_offset( TensorCoord const &tile_offset) { iterator_.add_tile_offset({tile_offset.row(), tile_offset.column()}); return *this; } /// Advances the iterator along the advance dimension CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &operator++() { ++iterator_; return *this; } /// Advances the iterator along the advance dimension CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &operator--() { --iterator_; return *this; } ///< advances in units of whole tiles along the logical coordinate space of ///< the tensor CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &operator+=( TensorCoord const &tile_offset) { add_tile_offset(PitchLinearCoord(tile_offset.row(), tile_offset.column())); return *this; } ///< advances in units of whole tiles along the logical coordinate space of ///< the tensor CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &operator-=( TensorCoord const &tile_offset) { add_tile_offset(-PitchLinearCoord(tile_offset.row(), tile_offset.column())); return *this; } /// Loads a fragment from memory at the location pointed to by the iterator. CUTLASS_HOST_DEVICE void load(Fragment &frag) const { iterator_.load(frag); } /// Loads a fragment from memory with additional logical offset CUTLASS_DEVICE void load_with_pointer_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a linear offset Index pointer_offset) const { iterator_.load_with_pointer_offset(frag, pointer_offset); } /// Loads a fragment from memory with additional logical offset CUTLASS_DEVICE void load_with_byte_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a linear offset Index byte_offset) const { iterator_.load_with_byte_offset(frag, byte_offset); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset) const { // TODO assert(0); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset, /// loads a tile with a logical offset AND a pointer offset Index pointer_offset) const { // TODO assert(0); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load_with_byte_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset, /// loads a tile with a logical offset AND a pointer offset Index byte_offset) const { iterator_.load_with_byte_offset( frag, {tile_offset.contiguous(), tile_offset.strided()}, byte_offset); } /// Notify the iterator which k-group it is currently pointing to. /// /// This does not advance the iterator. Rather, it overrides its internal /// tracking with constant-valued k-group index to enable the compiler to /// fold constants and achieve more efficient code. /// /// This is used by some nontrivial permuted layouts. CUTLASS_DEVICE void set_kgroup_index(int k_group) { iterator_.set_kgroup_index(k_group); } }; ///////////////////////////////////////////////////////////////////////////////////////////////// /// This tile iterator is specialized for 32-thread TensorOps. It uses LDS to /// load from shared memory and therefore must be initialized with a TensorRef /// to shared memory. /// /// Satisfies: /// ReadableRandomAccessContiguousTileIteratorConcept /// template < /// Size of the matrix to load (concept: MatrixShape) typename Shape_, /// Identifies A or B multiplicand Operand Operand_, /// Data type of elements typename Element_, /// Shape of one matrix product operation (concept: MatrixShape) typename InstructionShape_, /// Interval between adjacent *MMA instructions (in units of MMA /// instructions) int OpDelta_, /// KBlock size (in units of elements) int KBlock> class MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand_, Element_, cutlass::layout::RowMajorVoltaTensorOpMultiplicandCrosswise< sizeof_bits<Element_>::value, KBlock>, InstructionShape_, OpDelta_, 32> { public: /// Shape of tile to load (concept: PitchLinearShape) using Shape = Shape_; /// Operand tag static Operand const kOperand = Operand_; static_assert(kOperand == Operand::kA || kOperand == Operand::kB, "MmaTensorOpMultiplicandIterator may only be instantiated for " "A or B operands to warp-level Mma."); /// Element type using Element = Element_; /// KBlock size static int const kKBlock = KBlock; /// Layout of source tile using Layout = cutlass::layout::RowMajorVoltaTensorOpMultiplicandCrosswise< sizeof_bits<Element_>::value, kKBlock>; /// Shape of one matrix product operation (concept: MatrixShape) using InstructionShape = InstructionShape_; /// Delta between *MMA operations (in units of *MMA operations, concept: /// MatrixShape) static int const kOpDelta = OpDelta_; /// Number of participating threads static int const kThreads = 32; /// TensorRef type for loading element from a tensor using TensorRef = TensorRef<Element, Layout>; /// Index type using Index = typename TensorRef::Index; /// Long Index type using LongIndex = typename TensorRef::LongIndex; /// Coordinate for an element in the tensor using TensorCoord = typename TensorRef::TensorCoord; /// Underlying tile iterator implementation using Base = MmaVoltaTensorOpMultiplicandTileIterator< layout::PitchLinearShape<Shape::kColumn, Shape::kRow>, kOperand, Element, layout::VoltaTensorOpMultiplicandCrosswise<sizeof_bits<Element_>::value, kKBlock>, layout::PitchLinearShape<InstructionShape::kColumn, InstructionShape::kRow>, kOpDelta, kThreads>; public: // // Derived quantities // /// Fragment object holding a thread's part of a tile using Fragment = typename Base::Fragment; private: /// Underlying tile iterator Base iterator_; public: /// Default ctor constructs null iterator CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator() {} /// Constructor from TensorRef CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator(TensorRef const &ref, int lane_id) : iterator_({ref.data(), ref.stride()}, lane_id) {} /// Adds a pointer offset to internal pointer(s) to advance through memory CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &add_pointer_offset(LongIndex offset) { iterator_.add_pointer_offset(offset); return *this; } /// Advances an iterator along logical dimensions of matrix in units of whole /// tiles CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &add_tile_offset( TensorCoord const &tile_offset) { iterator_.add_tile_offset({tile_offset.column(), tile_offset.row()}); return *this; } /// Advances the iterator along the advance dimension CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &operator++() { ++iterator_; return *this; } /// Advances the iterator along the advance dimension CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &operator--() { --iterator_; return *this; } ///< advances in units of whole tiles along the logical coordinate space of ///< the tensor CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &operator+=( TensorCoord const &tile_offset) { add_tile_offset(PitchLinearCoord(tile_offset.column(), tile_offset.row())); return *this; } ///< advances in units of whole tiles along the logical coordinate space of ///< the tensor CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIterator &operator-=( TensorCoord const &tile_offset) { add_tile_offset(-PitchLinearCoord(tile_offset.column(), tile_offset.row())); return *this; } /// Loads a fragment from memory at the location pointed to by the iterator. CUTLASS_HOST_DEVICE void load(Fragment &frag) const { iterator_.load(frag); } /// Loads a fragment from memory with additional logical offset CUTLASS_DEVICE void load_with_pointer_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a linear offset Index pointer_offset) const { iterator_.load_with_pointer_offset(frag, pointer_offset); } /// Loads a fragment from memory with additional logical offset CUTLASS_DEVICE void load_with_byte_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a linear offset Index byte_offset) const { iterator_.load_with_byte_offset(frag, byte_offset); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset) const { // TODO assert(0); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset, /// loads a tile with a logical offset AND a pointer offset Index pointer_offset) const { // TODO assert(0); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load_with_byte_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset, /// loads a tile with a logical offset AND a pointer offset Index byte_offset) const { iterator_.load_with_byte_offset( frag, {tile_offset.strided(), tile_offset.contiguous()}, byte_offset); } /// Notify the iterator which k-group it is currently pointing to. /// /// This does not advance the iterator. Rather, it overrides its internal /// tracking with constant-valued k-group index to enable the compiler to /// fold constants and achieve more efficient code. /// /// This is used by some nontrivial permuted layouts. CUTLASS_DEVICE void set_kgroup_index(int k_group) { iterator_.set_kgroup_index(k_group); } }; ///////////////////////////////////////////////////////////////////////////////////////////////// /// Tile iterator specialized for 'TN' arrangement template < /// Size of the matrix to load (concept: MatrixShape) typename Shape_, /// Operand identity Operand Operand_, /// Data type of A elements typename Element_, /// Layout of matrix operand typename Layout_, /// Shape of one matrix production operation (concept: MatrixShape) typename InstructionShape_, /// Delta between *MMA operations (in units of *MMA operations, concept: /// MatrixShape) int OpDelta_, /// Number of threads participating in one matrix operation int Threads = 32, /// Number of partitions along K dimension int PartitionsK_ = 1> class MmaVoltaTensorOpMultiplicandTileIteratorCanonicalInner { public: /// Shape of tile to load (concept: MatrixShape) using Shape = Shape_; /// Operand tag static Operand const kOperand = Operand_; /// Basic check static_assert(kOperand == Operand::kA || kOperand== Operand::kB, "MmaVoltaTensorOpMultiplicandIterator may only be instantiated for A or B operands to warp-level Mma."); /// Element type using Element = Element_; /// Layout of source tile using Layout = Layout_; /// Shape of one matrix product operation (concept: MatrixShape) using InstructionShape = InstructionShape_; /// Delta between *MMA operations (in units of *MMA operations, concept: MatrixShape) static int const kOpDelta = OpDelta_; /// Number of participating threads static int const kThreads = 32; /// TensorRef type for loading element from a tensor using TensorRef = TensorRef<Element, Layout>; /// Index type using Index = typename TensorRef::Index; /// Long Index type using LongIndex = typename TensorRef::LongIndex; /// Coordinate for an element in the tensor using TensorCoord = typename TensorRef::TensorCoord; /// Number of elements accessed per Shared Memory load static int const kElementsPerAccess = 4; private: static int const kInterleavedTileRows = 32; static int const kInterleavedTileColumns = 32; static int const kInstructionsPerTile = 2; /// Rounded up instruction counts using TileCount = MatrixShape< Shape::kRow / kInterleavedTileRows, Shape::kColumn / kInterleavedTileColumns >; using FragmentCount = MatrixShape< TileCount::kRow * kInstructionsPerTile, TileCount::kColumn * kInstructionsPerTile >; public: // // Derived quantities // /// Fragment object holding a thread's part of a tile using Fragment = Array< Element, (kOperand == Operand::kA ? FragmentCount::kRow : FragmentCount::kColumn) * kElementsPerAccess >; /// Memory access type using AccessType = AlignedArray<Element, kElementsPerAccess>; private: /// Underlying tensor reference TensorRef ref_; /// Extent of tensor MatrixCoord extent_; /// Origin MatrixCoord origin_; /// Used to conditionally enable extents checking bool divisible_; public: /// Default ctor constructs null iterator CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIteratorCanonicalInner(): divisible_(true) { } /// Constructor from TensorRef CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIteratorCanonicalInner( TensorRef const &ref, int lane_id ): ref_(ref), extent_(Shape::kRow, Shape::kColumn), divisible_(true) { int quad_id = lane_id / 4; int lane_in_quad = (lane_id % 4); if (kOperand == Operand::kA) { int row_idx = ((quad_id & 1) + ((quad_id & 4) / 2)) * 4 * kInstructionsPerTile + lane_in_quad; int col_idx = 0; origin_ = MatrixCoord(row_idx, col_idx); } else { int row_idx = 0; int col_idx = (quad_id / 2) * 4 * kInstructionsPerTile + lane_in_quad; origin_ = MatrixCoord(row_idx, col_idx); } ref_.add_coord_offset(origin_); } /// Constructor from TensorRef CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIteratorCanonicalInner( TensorRef const &ref, TensorCoord extent, int lane_id ): ref_(ref), extent_(extent), divisible_(false) { int quad_id = lane_id / 4; int lane_in_quad = (lane_id % 4); if (kOperand == Operand::kA) { int row_idx = ((quad_id & 1) + ((quad_id & 4) / 2)) * 4 * kInstructionsPerTile + lane_in_quad; int col_idx = 0; origin_ = MatrixCoord(row_idx, col_idx); } else { int row_idx = 0; int col_idx = (quad_id / 2) * 4 * kInstructionsPerTile + lane_in_quad; origin_ = MatrixCoord(row_idx, col_idx); } #if defined(__CUDA_ARCH__) __syncthreads(); #endif ref_.add_coord_offset(origin_); } /// Adds a pointer offset to internal pointer(s) to advance through memory CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIteratorCanonicalInner &add_pointer_offset(LongIndex offset) { ref_.add_pointer_offset(offset); return *this; } /// Advances an iterator along logical dimensions of matrix in units of whole tiles CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIteratorCanonicalInner &add_tile_offset(TensorCoord const &tile_offset) { TensorCoord coord_offset(tile_offset.row() * Shape::kRow, tile_offset.column() * Shape::kColumn); origin_ += coord_offset; ref_.add_coord_offset(coord_offset); return *this; } /// Advances the iterator along the advance dimension CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIteratorCanonicalInner & operator++() { if (kOperand == Operand::kA) { add_tile_offset({0, 1}); } else { add_tile_offset({1, 0}); } return *this; } /// Advances the iterator along the advance dimension CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIteratorCanonicalInner & operator--() { if (kOperand == Operand::kA) { add_tile_offset({0, -1}); } else { add_tile_offset({-1, 0}); } return *this; } ///< advances in units of whole tiles along the logical coordinate space of the tensor CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIteratorCanonicalInner & operator+=(TensorCoord const &tile_offset) { add_tile_offset(tile_offset); return *this; } ///< advances in units of whole tiles along the logical coordinate space of the tensor CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIteratorCanonicalInner & operator-=(TensorCoord const &tile_offset) { add_tile_offset(-tile_offset); return *this; } /// Loads a fragment from memory at the location pointed to by the iterator. CUTLASS_HOST_DEVICE void load(Fragment &frag) const { load_with_pointer_offset(frag, 0); } /// Loads a fragment from memory with additional logical offset CUTLASS_DEVICE void load_with_pointer_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a linear offset Index pointer_offset) const { AccessType *frag_ptr = reinterpret_cast<AccessType *>(&frag); AccessType const *access_ptr = reinterpret_cast<AccessType const *>(ref_.data()); int ldm = ref_.stride()[0]; if (kOperand == Operand::kA) { CUTLASS_PRAGMA_UNROLL for (int idx = 0; idx < FragmentCount::kRow; ++idx) { int tile_idx = idx / 2; int quad_idx = idx % 2; int row_offset = tile_idx * kInterleavedTileRows + quad_idx * 4; frag_ptr[idx] = access_ptr[row_offset * ldm / kElementsPerAccess]; } } else { CUTLASS_PRAGMA_UNROLL for (int idx = 0; idx < FragmentCount::kColumn; ++idx) { int tile_idx = idx / 2; int quad_idx = idx % 2; int col_offset = tile_idx * kInterleavedTileColumns + quad_idx * 4; frag_ptr[idx] = access_ptr[col_offset * ldm / kElementsPerAccess]; } } } /// Loads a fragment from memory with additional logical offset CUTLASS_DEVICE void load_with_byte_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a linear offset Index byte_offset) const { load_with_pointer_offset(frag, byte_offset * 8 / sizeof_bits<Element>::value); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset) const { TensorCoord coord_offset(tile_offset.row() * Shape::kRow, tile_offset.column() * Shape::kColumn); load_with_pointer_offset(frag, ref_.offset(coord_offset)); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset, /// loads a tile with a logical offset AND a pointer offset Index pointer_offset) const { TensorCoord coord_offset(tile_offset.row() * Shape::kRow, tile_offset.column() * Shape::kColumn); load_with_pointer_offset(frag, ref_.offset(coord_offset) + pointer_offset); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load_with_byte_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset, /// loads a tile with a logical offset AND a pointer offset Index byte_offset) const { TensorCoord coord_offset(tile_offset.row() * Shape::kRow, tile_offset.column() * Shape::kColumn); load_with_pointer_offset(frag, ref_.offset(coord_offset) + byte_offset * 8 / sizeof_bits<Element>::value); } /// Notify the iterator which k-group it is currently pointing to. /// /// This does not advance the iterator. Rather, it overrides its internal /// tracking with constant-valued k-group index to enable the compiler to /// fold constants and achieve more efficient code. /// /// This is used by some nontrivial permuted layouts. CUTLASS_DEVICE void set_kgroup_index(int k_group) { // no operation } }; /// Tile iterator specialized for 'NT' arrangement template < /// Size of the matrix to load (concept: MatrixShape) typename Shape_, /// Operand identity Operand Operand_, /// Data type of A elements typename Element_, /// Layout of matrix operand typename Layout_, /// Shape of one matrix production operation (concept: MatrixShape) typename InstructionShape_, /// Delta between *MMA operations (in units of *MMA operations, concept: /// MatrixShape) int OpDelta_, /// Number of threads participating in one matrix operation int Threads = 32, /// Number of partitions along K dimension int PartitionsK_ = 1> class MmaVoltaTensorOpMultiplicandTileIteratorCanonicalOuter { public: /// Shape of tile to load (concept: MatrixShape) using Shape = Shape_; /// Operand tag static Operand const kOperand = Operand_; /// Basic check static_assert(kOperand == Operand::kA || kOperand== Operand::kB, "MmaVoltaTensorOpMultiplicandIterator may only be instantiated for A or B operands to warp-level Mma."); /// Element type using Element = Element_; /// Layout of source tile using Layout = Layout_; /// Shape of one matrix product operation (concept: MatrixShape) using InstructionShape = InstructionShape_; /// Delta between *MMA operations (in units of *MMA operations, concept: MatrixShape) static int const kOpDelta = OpDelta_; /// Number of participating threads static int const kThreads = 32; /// TensorRef type for loading element from a tensor using TensorRef = TensorRef<Element, Layout>; /// Index type using Index = typename TensorRef::Index; /// Long Index type using LongIndex = typename TensorRef::LongIndex; /// Coordinate for an element in the tensor using TensorCoord = typename TensorRef::TensorCoord; /// Number of elements accessed per Shared Memory load static int const kElementsPerAccess = 4; private: static int const kInterleavedTileRows = 32; static int const kInterleavedTileColumns = 32; static int const kInstructionsPerTile = 2; /// Rounded up instruction counts using TileCount = MatrixShape< Shape::kRow / kInterleavedTileRows, Shape::kColumn / kInterleavedTileColumns >; using FragmentCount = MatrixShape< TileCount::kRow * kInstructionsPerTile, TileCount::kColumn * kInstructionsPerTile >; public: // // Derived quantities // /// Fragment object holding a thread's part of a tile using Fragment = Array< Element, (kOperand == Operand::kA ? FragmentCount::kRow : FragmentCount::kColumn) * kElementsPerAccess >; /// Memory access type using AccessType = AlignedArray<Element, kElementsPerAccess>; private: /// Underlying tensor reference TensorRef ref_; /// Extent of tensor MatrixCoord extent_; /// Origin MatrixCoord origin_; /// Used to conditionally enable extents checking bool divisible_; public: /// Default ctor constructs null iterator CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIteratorCanonicalOuter(): divisible_(true) { } /// Constructor from TensorRef CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIteratorCanonicalOuter( TensorRef const &ref, int lane_id ): ref_(ref), extent_(Shape::kRow, Shape::kColumn), divisible_(true) { int quad_id = lane_id / 4; int lane_in_quad = (lane_id % 4); if (kOperand == Operand::kA) { int row_idx = ((quad_id & 1) + ((quad_id & 4) / 2)) * 4 * kInstructionsPerTile; int col_idx = lane_in_quad; origin_ = MatrixCoord(row_idx, col_idx); } else { int row_idx = lane_in_quad; int col_idx = (quad_id / 2) * 4 * kInstructionsPerTile; origin_ = MatrixCoord(row_idx, col_idx); } ref_.add_coord_offset(origin_); } /// Constructor from TensorRef CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIteratorCanonicalOuter( TensorRef const &ref, TensorCoord extent, int lane_id ): ref_(ref), extent_(extent), divisible_(false) { int quad_id = lane_id / 4; int lane_in_quad = (lane_id % 4); if (kOperand == Operand::kA) { int row_idx = ((quad_id & 1) + ((quad_id & 4) / 2)) * 4 * kInstructionsPerTile; int col_idx = lane_in_quad; origin_ = MatrixCoord(row_idx, col_idx); } else { int row_idx = lane_in_quad; int col_idx = (quad_id / 2) * 4 * kInstructionsPerTile; origin_ = MatrixCoord(row_idx, col_idx); } #if defined(__CUDA_ARCH__) __syncthreads(); #endif ref_.add_coord_offset(origin_); } /// Adds a pointer offset to internal pointer(s) to advance through memory CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIteratorCanonicalOuter &add_pointer_offset(LongIndex offset) { ref_.add_pointer_offset(offset); return *this; } /// Advances an iterator along logical dimensions of matrix in units of whole tiles CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIteratorCanonicalOuter &add_tile_offset(TensorCoord const &tile_offset) { TensorCoord coord_offset(tile_offset.row() * Shape::kRow, tile_offset.column() * Shape::kColumn); origin_ += coord_offset; ref_.add_coord_offset(coord_offset); return *this; } /// Advances the iterator along the advance dimension CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIteratorCanonicalOuter & operator++() { if (kOperand == Operand::kA) { add_tile_offset({0, 1}); } else { add_tile_offset({1, 0}); } return *this; } /// Advances the iterator along the advance dimension CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIteratorCanonicalOuter & operator--() { if (kOperand == Operand::kA) { add_tile_offset({0, -1}); } else { add_tile_offset({-1, 0}); } return *this; } ///< advances in units of whole tiles along the logical coordinate space of the tensor CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIteratorCanonicalOuter & operator+=(TensorCoord const &tile_offset) { add_tile_offset(tile_offset); return *this; } ///< advances in units of whole tiles along the logical coordinate space of the tensor CUTLASS_DEVICE MmaVoltaTensorOpMultiplicandTileIteratorCanonicalOuter & operator-=(TensorCoord const &tile_offset) { add_tile_offset(-tile_offset); return *this; } /// Loads a fragment from memory at the location pointed to by the iterator. CUTLASS_HOST_DEVICE void load(Fragment &frag) const { load_with_pointer_offset(frag, 0); } /// Loads a fragment from memory with additional logical offset CUTLASS_DEVICE void load_with_pointer_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a linear offset Index pointer_offset) const { AccessType *frag_ptr = reinterpret_cast<AccessType *>(&frag); AccessType const *access_ptr = reinterpret_cast<AccessType const *>(ref_.data()); int ldm = ref_.stride()[0]; if (kOperand == Operand::kA) { CUTLASS_PRAGMA_UNROLL for (int idx = 0; idx < FragmentCount::kRow; ++idx) { int tile_idx = idx / 2; int quad_idx = idx % 2; int row_offset = tile_idx * kInterleavedTileRows; frag_ptr[idx] = access_ptr[row_offset / kElementsPerAccess + quad_idx]; } } else { CUTLASS_PRAGMA_UNROLL for (int idx = 0; idx < FragmentCount::kColumn; ++idx) { int tile_idx = idx / 2; int quad_idx = idx % 2; int col_offset = tile_idx * kInterleavedTileColumns; frag_ptr[idx] = access_ptr[col_offset / kElementsPerAccess + quad_idx]; } } } /// Loads a fragment from memory with additional logical offset CUTLASS_DEVICE void load_with_byte_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a linear offset Index byte_offset) const { load_with_pointer_offset(frag, byte_offset * 8 / sizeof_bits<Element>::value); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset) const { TensorCoord coord_offset(tile_offset.row() * Shape::kRow, tile_offset.column() * Shape::kColumn); load_with_pointer_offset(frag, ref_.offset(coord_offset)); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset, /// loads a tile with a logical offset AND a pointer offset Index pointer_offset) const { TensorCoord coord_offset(tile_offset.row() * Shape::kRow, tile_offset.column() * Shape::kColumn); load_with_pointer_offset(frag, ref_.offset(coord_offset) + pointer_offset); } /// Loads a fragment from memory with logical offset in units of whole tiles. CUTLASS_DEVICE void load_with_byte_offset( /// fragment to load from the tensor Fragment &frag, /// loads a tile with a logical offset in units of whole tiles TensorCoord const &tile_offset, /// loads a tile with a logical offset AND a pointer offset Index byte_offset) const { TensorCoord coord_offset(tile_offset.row() * Shape::kRow, tile_offset.column() * Shape::kColumn); load_with_pointer_offset(frag, ref_.offset(coord_offset) + byte_offset * 8 / sizeof_bits<Element>::value); } /// Notify the iterator which k-group it is currently pointing to. /// /// This does not advance the iterator. Rather, it overrides its internal /// tracking with constant-valued k-group index to enable the compiler to /// fold constants and achieve more efficient code. /// /// This is used by some nontrivial permuted layouts. CUTLASS_DEVICE void set_kgroup_index(int k_group) { // no operation } }; ///////////////////////////////////////////////////////////////////////////////////////////////// template < /// Size of the matrix to load (concept: MatrixShape) typename Shape_, /// Data type of elements typename Element_, /// Shape of one matrix product operation (concept: MatrixShape) typename InstructionShape_, /// Interval between adjacent *MMA instructions (in units of MMA /// instructions) int OpDelta_> class MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand::kA, Element_, cutlass::layout::RowMajor, InstructionShape_, OpDelta_, 32 > : public MmaVoltaTensorOpMultiplicandTileIteratorCanonicalInner< Shape_, Operand::kA, Element_, cutlass::layout::RowMajor, InstructionShape_, OpDelta_> { public: using Base = MmaVoltaTensorOpMultiplicandTileIteratorCanonicalInner< Shape_, Operand::kA, Element_, cutlass::layout::RowMajor, InstructionShape_, OpDelta_> ; using TensorRef = typename Base::TensorRef; /// Constructor from TensorRef CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator( TensorRef const &ref, int lane_id ): Base(ref, lane_id) { } }; template < /// Size of the matrix to load (concept: MatrixShape) typename Shape_, /// Data type of elements typename Element_, /// Shape of one matrix product operation (concept: MatrixShape) typename InstructionShape_, /// Interval between adjacent *MMA instructions (in units of MMA /// instructions) int OpDelta_> class MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand::kA, Element_, cutlass::layout::ColumnMajor, InstructionShape_, OpDelta_, 32 > : public MmaVoltaTensorOpMultiplicandTileIteratorCanonicalOuter< Shape_, Operand::kA, Element_, cutlass::layout::ColumnMajor, InstructionShape_, OpDelta_> { public: using Base = MmaVoltaTensorOpMultiplicandTileIteratorCanonicalOuter< Shape_, Operand::kA, Element_, cutlass::layout::ColumnMajor, InstructionShape_, OpDelta_> ; using TensorRef = typename Base::TensorRef; /// Constructor from TensorRef CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator( TensorRef const &ref, int lane_id ): Base(ref, lane_id) { } }; template < /// Size of the matrix to load (concept: MatrixShape) typename Shape_, /// Data type of elements typename Element_, /// Shape of one matrix product operation (concept: MatrixShape) typename InstructionShape_, /// Interval between adjacent *MMA instructions (in units of MMA /// instructions) int OpDelta_> class MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand::kB, Element_, cutlass::layout::ColumnMajor, InstructionShape_, OpDelta_, 32 > : public MmaVoltaTensorOpMultiplicandTileIteratorCanonicalInner< Shape_, Operand::kB, Element_, cutlass::layout::ColumnMajor, InstructionShape_, OpDelta_> { public: using Base = MmaVoltaTensorOpMultiplicandTileIteratorCanonicalInner< Shape_, Operand::kB, Element_, cutlass::layout::ColumnMajor, InstructionShape_, OpDelta_>; using TensorRef = typename Base::TensorRef; /// Constructor from TensorRef CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator( TensorRef const &ref, int lane_id ): Base(ref, lane_id) { } }; template < /// Size of the matrix to load (concept: MatrixShape) typename Shape_, /// Data type of elements typename Element_, /// Shape of one matrix product operation (concept: MatrixShape) typename InstructionShape_, /// Interval between adjacent *MMA instructions (in units of MMA /// instructions) int OpDelta_> class MmaVoltaTensorOpMultiplicandTileIterator< Shape_, Operand::kB, Element_, cutlass::layout::RowMajor, InstructionShape_, OpDelta_, 32 > : public MmaVoltaTensorOpMultiplicandTileIteratorCanonicalOuter< Shape_, Operand::kB, Element_, cutlass::layout::RowMajor, InstructionShape_, OpDelta_> { public: using Base = MmaVoltaTensorOpMultiplicandTileIteratorCanonicalOuter< Shape_, Operand::kB, Element_, cutlass::layout::RowMajor, InstructionShape_, OpDelta_>; using TensorRef = typename Base::TensorRef; /// Constructor from TensorRef CUTLASS_HOST_DEVICE MmaVoltaTensorOpMultiplicandTileIterator( TensorRef const &ref, int lane_id ): Base(ref, lane_id) { } }; ///////////////////////////////////////////////////////////////////////////////////////////////// } // namespace warp } // namespace gemm } // namespace cutlass /////////////////////////////////////////////////////////////////////////////////////////////////
32.12031
112
0.684401
[ "object", "shape" ]
c57e37e346335104f1d588bb48974112c111c51b
881
h
C
ios/dist/ViroRenderer/x86_64/ViroKit.framework/Headers/VRORenderParameters.h
ascorbic/viro
1e7527944d0063bed1b20bec64ee1b425d1a2eaf
[ "MIT" ]
null
null
null
ios/dist/ViroRenderer/x86_64/ViroKit.framework/Headers/VRORenderParameters.h
ascorbic/viro
1e7527944d0063bed1b20bec64ee1b425d1a2eaf
[ "MIT" ]
null
null
null
ios/dist/ViroRenderer/x86_64/ViroKit.framework/Headers/VRORenderParameters.h
ascorbic/viro
1e7527944d0063bed1b20bec64ee1b425d1a2eaf
[ "MIT" ]
null
null
null
// // VRORenderParameters.h // ViroRenderer // // Created by Raj Advani on 12/15/15. // Copyright © 2015 Viro Media. All rights reserved. // #ifndef VRORenderParameters_h #define VRORenderParameters_h #include <vector> #include <stack> #include "VROMatrix4f.h" class VROLight; /* Contains the per-frame render parameters for the current render pass. */ class VRORenderParameters { public: std::stack<float> opacities; std::vector<std::shared_ptr<VROLight>> lights; std::stack<int> hierarchyDepths; std::stack<float> distancesFromCamera; int hierarchyId; float furthestDistanceFromCamera; VRORenderParameters() { opacities.push(1.0); hierarchyDepths.push(-1); hierarchyId = 0; furthestDistanceFromCamera = 0; distancesFromCamera.push(0); } }; #endif /* VRORenderParameters_h */
20.022727
57
0.681044
[ "render", "vector" ]
c58d95d6e9e5da8f8825ec7c4ff575a7e397b6cf
3,977
h
C
comp_ltkplus/src/main/jni/include/LTKLipiEngineInterface.h
Simon-Initiative/RT_RoboTutor_2017_06_16
f307d594de7102dfcd819042420d37ca6965625f
[ "CC-BY-4.0", "BSD-3-Clause" ]
13
2019-05-17T06:00:11.000Z
2021-06-25T16:11:28.000Z
comp_ltkplus/src/main/jni/include/LTKLipiEngineInterface.h
Simon-Initiative/RT_RoboTutor_2017_06_16
f307d594de7102dfcd819042420d37ca6965625f
[ "CC-BY-4.0", "BSD-3-Clause" ]
48
2018-11-28T02:04:04.000Z
2020-06-01T20:10:47.000Z
comp_ltkplus/src/main/jni/include/LTKLipiEngineInterface.h
Simon-Initiative/RT_RoboTutor_2017_06_16
f307d594de7102dfcd819042420d37ca6965625f
[ "CC-BY-4.0", "BSD-3-Clause" ]
9
2019-09-14T03:20:19.000Z
2020-03-30T01:43:24.000Z
/***************************************************************************************** * Copyright (c) 2006 Hewlett-Packard Development Company, L.P. * 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. *****************************************************************************************/ /************************************************************************ * SVN MACROS * * $LastChangedDate: 2011-01-18 15:41:43 +0530 (Tue, 18 Jan 2011) $ * $Revision: 829 $ * $Author: mnab $ * ************************************************************************/ /************************************************************************ * FILE DESCR: Interface definition of LipiEngine interface * * CONTENTS: * * * AUTHOR: Thanigai Murugan K * * DATE: July 29 2005 * CHANGE HISTORY: * Author Date Description of change ************************************************************************/ #ifndef __LIPIENGINEINTERFACE_H_ #define __LIPIENGINEINTERFACE_H_ #include "LTKShapeRecognizer.h" #include "LTKWordRecognizer.h" #include "LTKRecognitionContext.h" class LTKLipiEngineInterface{ public: virtual void setLipiRootPath(const string& appLipiPath)=0; virtual int setLipiLogFileName(const string& appLipiPath) = 0; virtual int setLipiLogLevel(const string& appLogLevel)=0; /* To initialize the lipiengine */ virtual int initializeLipiEngine() = 0; /* use this to create shape recognizer object, by passing the logical project name */ virtual int createShapeRecognizer(string &strLogicalProjectName, LTKShapeRecognizer** outShapeRecognizerPtr) = 0; /* use this to create shape recognizer object, by passing the project name and profile name*/ virtual int createShapeRecognizer(const string& strProjectName, const string& strProfileName, LTKShapeRecognizer** outShapeRecognizerPtr) = 0; /* use this to delete the shape recognizer object created using createShapeRecognizer call */ virtual int deleteShapeRecognizer(LTKShapeRecognizer*) = 0; /* use this to create word recognizer object, by passing the project name and profile name*/ virtual int createWordRecognizer(const string& strProjectName, const string& strProfileName, LTKWordRecognizer** outWordRecPtr) = 0; /* use this to create word recognizer object, by passing the logical project name*/ virtual int createWordRecognizer(const string& strlogicalProjectName, LTKWordRecognizer** outWordRecPtr) = 0; /* use this to delete the word recognizer object created using createShapeRecognizer call */ virtual int deleteWordRecognizer(LTKWordRecognizer*) = 0; }; #endif //#ifndef __LIPIENGINEINTERFACE_H_
44.188889
129
0.614534
[ "object", "shape" ]
c59533e62b3d165b1afa7931d6898d0abc1529b2
5,283
h
C
PersistentStore/PersistentStore.h
MFransen69/rdkservices
ce13efeb95779bc04c20e69be5fe86fd8565a6c6
[ "BSD-2-Clause" ]
null
null
null
PersistentStore/PersistentStore.h
MFransen69/rdkservices
ce13efeb95779bc04c20e69be5fe86fd8565a6c6
[ "BSD-2-Clause" ]
null
null
null
PersistentStore/PersistentStore.h
MFransen69/rdkservices
ce13efeb95779bc04c20e69be5fe86fd8565a6c6
[ "BSD-2-Clause" ]
null
null
null
/* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: * * Copyright 2022 RDK Management * * 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. */ #pragma once #include "Module.h" #include "IStoreListing.h" #include <interfaces/IStore.h> #include <interfaces/IStoreCache.h> namespace WPEFramework { namespace Plugin { class PersistentStore: public PluginHost::IPlugin, public PluginHost::JSONRPC { private: class Config: public Core::JSON::Container { private: Config(const Config &) = delete; Config &operator=(const Config &) = delete; public: Config() : Core::JSON::Container(), Path(), Key(), MaxSize(0), MaxValue(0) { Add(_T("path"), &Path); Add(_T("key"), &Key); Add(_T("maxsize"), &MaxSize); Add(_T("maxvalue"), &MaxValue); } public: Core::JSON::String Path; Core::JSON::String Key; Core::JSON::DecUInt64 MaxSize; Core::JSON::DecUInt64 MaxValue; }; class StoreNotification: protected Exchange::IStore::INotification { private: StoreNotification(const StoreNotification &) = delete; StoreNotification &operator=(const StoreNotification &) = delete; public: explicit StoreNotification(PersistentStore *parent) : _parent(*parent), _client(nullptr) { ASSERT(parent != nullptr); } ~StoreNotification() = default; public: void Initialize(Exchange::IStore *client) { ASSERT(_client == nullptr); ASSERT(client != nullptr); _client = client; _client->AddRef(); _client->Register(this); } void Deinitialize() { ASSERT(_client != nullptr); if (_client != nullptr) { _client->Unregister(this); _client->Release(); _client = nullptr; } } public: // IStore::INotification methods virtual void ValueChanged(const string &ns, const string &key, const string &value) override { _parent.event_onValueChanged(ns, key, value); } virtual void StorageExceeded() override { _parent.event_onStorageExceeded(); } BEGIN_INTERFACE_MAP(StoreNotification) INTERFACE_ENTRY(Exchange::IStore::INotification) END_INTERFACE_MAP private: PersistentStore &_parent; Exchange::IStore *_client; }; private: PersistentStore(const PersistentStore &) = delete; PersistentStore &operator=(const PersistentStore &) = delete; public: PersistentStore(); virtual ~PersistentStore(); // Build QueryInterface implementation, specifying all possible interfaces to be returned. BEGIN_INTERFACE_MAP(PersistentStore) INTERFACE_ENTRY(PluginHost::IPlugin) INTERFACE_ENTRY(PluginHost::IDispatcher) INTERFACE_AGGREGATE(Exchange::IStore, _store) INTERFACE_AGGREGATE(Exchange::IStoreCache, _storeCache) END_INTERFACE_MAP public: // IPlugin methods // ------------------------------------------------------------------------------------------------------- virtual const string Initialize(PluginHost::IShell *service) override; virtual void Deinitialize(PluginHost::IShell *service) override; virtual string Information() const override; protected: void RegisterAll(); void UnregisterAll(); uint32_t endpoint_setValue(const JsonObject &parameters, JsonObject &response); uint32_t endpoint_getValue(const JsonObject &parameters, JsonObject &response); uint32_t endpoint_deleteKey(const JsonObject &parameters, JsonObject &response); uint32_t endpoint_deleteNamespace(const JsonObject &parameters, JsonObject &response); uint32_t endpoint_getKeys(const JsonObject &parameters, JsonObject &response); uint32_t endpoint_getNamespaces(const JsonObject &parameters, JsonObject &response); uint32_t endpoint_getStorageSize(const JsonObject &parameters, JsonObject &response); uint32_t endpoint_flushCache(const JsonObject &parameters, JsonObject &response); virtual void event_onValueChanged(const string &ns, const string &key, const string &value); virtual void event_onStorageExceeded(); protected: virtual std::vector<string> LegacyLocations() const; private: Config _config; Exchange::IStore *_store; Exchange::IStoreCache *_storeCache; IStoreListing *_storeListing; Core::Sink<StoreNotification> _storeSink; }; } // namespace Plugin } // namespace WPEFramework
30.894737
110
0.649442
[ "vector" ]
c595ec3eeede43b46becab11f64a20240239e00d
4,955
h
C
Interaction/Widgets/vtkCellCentersPointPlacer.h
satya-arjunan/vtk8
ee7ced57de6d382a2d12693c01e2fcdac350b25f
[ "BSD-3-Clause" ]
3
2015-07-28T18:07:50.000Z
2018-02-28T20:59:58.000Z
Interaction/Widgets/vtkCellCentersPointPlacer.h
satya-arjunan/vtk8
ee7ced57de6d382a2d12693c01e2fcdac350b25f
[ "BSD-3-Clause" ]
4
2018-10-25T09:46:11.000Z
2019-01-17T16:49:17.000Z
Interaction/Widgets/vtkCellCentersPointPlacer.h
satya-arjunan/vtk8
ee7ced57de6d382a2d12693c01e2fcdac350b25f
[ "BSD-3-Clause" ]
4
2016-09-08T02:11:00.000Z
2019-08-15T02:38:39.000Z
/*========================================================================= Program: Visualization Toolkit Module: vtkCellCentersPointPlacer.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /** * @class vtkCellCentersPointPlacer * @brief Snaps points at the center of a cell * * * vtkCellCentersPointPlacer is a class to snap points on the center of cells. * The class has 3 modes. In the ParametricCenter mode, it snaps points * to the parametric center of the cell (see vtkCell). In CellPointsMean * mode, points are snapped to the mean of the points in the cell. * In 'None' mode, no snapping is performed. The computed world position * is the picked position within the cell. * * @par Usage: * The actors that render data and wish to be considered for placement * by this placer are added to the list as * \code * placer->AddProp( actor ); * \endcode * * @sa * vtkPointPlacer */ #ifndef vtkCellCentersPointPlacer_h #define vtkCellCentersPointPlacer_h #include "vtkInteractionWidgetsModule.h" // For export macro #include "vtkPointPlacer.h" class vtkRenderer; class vtkPropCollection; class vtkProp; class vtkCellPicker; class VTKINTERACTIONWIDGETS_EXPORT vtkCellCentersPointPlacer : public vtkPointPlacer { public: /** * Instantiate this class. */ static vtkCellCentersPointPlacer *New(); //@{ /** * Standard methods for instances of this class. */ vtkTypeMacro(vtkCellCentersPointPlacer,vtkPointPlacer); void PrintSelf(ostream& os, vtkIndent indent) override; //@} // Descuription: // Add an actor (that represents a terrain in a rendererd scene) to the // list. Only props in this list are considered by the PointPlacer virtual void AddProp( vtkProp * ); virtual void RemoveViewProp(vtkProp *prop); virtual void RemoveAllProps(); int HasProp( vtkProp * ); int GetNumberOfProps(); /** * Given a renderer and a display position in pixel coordinates, * compute the world position and orientation where this point * will be placed. This method is typically used by the * representation to place the point initially. * For the Terrain point placer this computes world points that * lie at the specified height above the terrain. */ int ComputeWorldPosition( vtkRenderer *ren, double displayPos[2], double worldPos[3], double worldOrient[9] ) override; /** * Given a renderer, a display position, and a reference world * position, compute the new world position and orientation * of this point. This method is typically used by the * representation to move the point. */ int ComputeWorldPosition( vtkRenderer *ren, double displayPos[2], double refWorldPos[3], double worldPos[3], double worldOrient[9] ) override; /** * Given a world position check the validity of this * position according to the constraints of the placer */ int ValidateWorldPosition( double worldPos[3] ) override; /** * Given a display position, check the validity of this position. */ int ValidateDisplayPosition( vtkRenderer *, double displayPos[2] ) override; /** * Given a world position and a world orientation, * validate it according to the constraints of the placer. */ int ValidateWorldPosition( double worldPos[3], double worldOrient[9] ) override; //@{ /** * Get the Prop picker. */ vtkGetObjectMacro( CellPicker, vtkCellPicker ); //@} //@{ /** * Modes to change the point placement. Parametric center picks * the parametric center within the cell. CellPointsMean picks * the average of all points in the cell. When the mode is None, * the input point is passed through unmodified. Default is CellPointsMean. */ vtkSetMacro( Mode, int ); vtkGetMacro( Mode, int ); //@} enum { ParametricCenter = 0, CellPointsMean, None }; protected: vtkCellCentersPointPlacer(); ~vtkCellCentersPointPlacer() override; // The props that represents the terrain data (one or more) in a rendered // scene vtkPropCollection *PickProps; vtkCellPicker *CellPicker; int Mode; private: vtkCellCentersPointPlacer(const vtkCellCentersPointPlacer&) = delete; void operator=(const vtkCellCentersPointPlacer&) = delete; }; #endif
31.360759
84
0.656912
[ "render" ]
c59b336f0e24e3ccaed43d95ad501ba3fc180cd7
32,723
h
C
THijing/Hcommon.h
shahor02/AliRoot
37118c83effe7965a2a24b3b868bf9012727fb7e
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
THijing/Hcommon.h
shahor02/AliRoot
37118c83effe7965a2a24b3b868bf9012727fb7e
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
THijing/Hcommon.h
shahor02/AliRoot
37118c83effe7965a2a24b3b868bf9012727fb7e
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
#ifndef ROOT_HCommon #define ROOT_HCommon #ifndef __CFORTRAN_LOADED //*KEEP,cfortran. #include "cfortran.h" //*KEND. #endif extern "C" { /*=========================================================*/ /* COMMON/HIPARNT/HIPR1(100),IHPR2(50),HINT1(100),IHNT2(50)*/ /*---------------------------------------------------------*/ typedef struct { Float_t hipr1[100]; Int_t ihpr2[50]; Float_t hint1[100]; Int_t ihnt2[50]; } HiparntCommon; #define HIPARNT COMMON_BLOCK(HIPARNT,hiparnt) COMMON_BLOCK_DEF(HiparntCommon,HIPARNT); /**************************************************************************/ /* D E S C R I P T I O N : */ /*------------------------------------------------------------------------*/ /*COMMON/HIPARNT/HIPR1(100), IHPR2(50), HINT1(100), IHNT2(50) */ /*Purpose: contains input parameters (HIPR1, IHPR2) for event options */ /* and some extra information (HINT1, IHNT2) of current event. */ /*HIPR1(1): (D=1.5 GeV/$c^2$) minimum value for the invariant mass of */ /* the excited string system in a hadron-hadron interaction. */ /*HIPR1(2): (D=0.35 GeV) width of the Gaussian $P_T$ distribution of */ /* produced hadron in Lund string fragmentation */ /* (PARJ(21) in JETSET 7.2). */ /*HIPR1(3), HIPR1(4): (D=0.5, 0.9 GeV$^{-2}$) give the $a$ and $b$ */ /* parameters of the symmetric Lund fragmentation function */ /* (PARJ(41), PARJ(42) in JETSET 7.2). */ /*HIPR1(5): (D=2.0 GeV/$c^2$) invariant mass cut-off for the dipole */ /* radiation of a string system below which soft gluon */ /* radiations are terminated. */ /*HIPR1(6): (D=0.1) the depth of shadowing of structure functions */ /* at $x=0$:$\alpha_A=\mbox{HIPR1(6)}\times(A^{1/3}-1)$. */ /*HIPR1(7): not used */ /*HIPR1(8): (D=2.0 GeV/$c$) minimum $P_T$ transfer in hard or */ /* semihard scatterings. */ /*HIPR1(9): (D=$-1.0$ GeV/$c$) maximum $P_T$ transfer in hard or */ /* semihard scatterings. If negative, the limit is set */ /* by the colliding energy. */ /*HIPR1(10): (D=$-2.25$ GeV/$c$) specifies the value of $P_T$ for */ /* each triggered hard scattering generated per event */ /* (see Section \ref{sec:jet2}). If HIPR1(10) is negative, */ /* its absolute value gives the low limit of the */ /* $P_T$ of the triggered jets. */ /*HIPR1(11): (D=2.0 GeV/$c$) minimum $P_T$ of a jet which will interact */ /* with excited nuclear matter. When the $P_T$ of a jet */ /* is smaller than HIPR1(11) it will stop interacting further. */ /*HIPR1(12): (D=1.0 fm) transverse distance between a traversing jet */ /* and an excited nucleon (string system) below which they */ /* will interact and the jet will lose energy and momentum */ /* to that string system. */ /*HIPR1(13): (D=1.0 fm) the mean free path of a jet when it goes */ /* through the excited nuclear matter. */ /*HIPR1(14): (D=2.0 GeV/fm) the energy loss $dE/dz$ of a gluon */ /* jet inside the excited nuclear matter. The energy loss */ /* for a quark jet is half of the energy loss of a gluon. */ /*HIPR1(15): (D=0.2 GeV/$c$) the scale $\Lambda$ in the */ /* calculation of $\alpha_s$. */ /*HIPR1(16): (D=2.0 GeV/$c$) the initial scale $Q_0$ for the */ /* evolution of the structure functions. */ /*HIPR1(17): (D=2.0) $K$ factor for the differential jet cross */ /* sections in the lowest order pQCD calculation. */ /*HIPR1(18): not used */ /*HIPR1(19), HIPR1(20): (D=0.1, 1.4 GeV/$c$) parameters in the */ /* distribution for the $P_T$ kick from soft interactions , */ /* $1/[(\mbox{HIPR1(19)}^2+P_T^2)(\mbox{HIPR1(20)}^2+P_T^2)]$. */ /*HIPR1(21): (D=1.6 GeV/$c$) the maximum $P_T$ for soft interactions, */ /* beyond which a Gaussian distribution as specified by */ /* HIPR1(2) will be used. */ /*HIPR1(22): (D=2.0 GeV/$c$) the scale in the form factor to suppress */ /* the $P_T$ transfer to diquarks in hard scatterings, */ /*HIPR1(23)--HIPR1(28): not used. */ /*HIPR1(29): (D=0.4 fm) the minimum distance between two nucleons */ /* inside a nucleus when the coordinates of the nucleons */ /* inside a nucleus are initialized. */ /*HIPR1(30): (D=2$\times$HIPR1(31)=57.0 mb) the inclusive cross */ /* section $\sigma_{soft}$ for soft interactions. The default */ /* value $\sigma_{soft}=2\sigma_0$ is used to ensure the */ /* geometrical scaling of $pp$ interaction cross sections */ /* at low energies. */ /*HIPR1(31): (D=28.5 mb) the cross section $\sigma_0$ which */ /* characterizes the geometrical size of a nucleon */ /* ($\pi b_0^2=\sigma_0$, see Eq.~\ref{eq:over2}). */ /* The default value is only for high-energy */ /* limit ($\sqrt{s}>200$ GeV). At lower energies, a slight */ /* decrease which depends on energy is parametrized in the */ /* program. The default values of the two parameters */ /* HIPR1(30), HIPR1(31) are only for $NN$ type interactions. */ /* For other kinds of projectile or target hadrons, users */ /* should change these values so that correct inelastic */ /* and total cross sections (HINT1(12), HINT1(13)) are */ /* obtained by the program. */ /*HIPR1(32): (D=3.90) parameter $\mu_0$ in Eq.~\ref{eq:over2} for */ /* the scaled eikonal function. */ /*HIPR1(33): fractional cross section of single-diffractive */ /* interaction as parametrized in Ref.~\cite{goulianos}. */ /*HIPR1(34): maximum radial coordinate for projectile nucleons */ /* to be given by the initialization program HIJSET. */ /*HIPR1(35): maximum radial coordinate for target nucleons */ /* to be given by the initialization program HIJSET. */ /*HIPR1(36)-HIPR1(39): not used. */ /*HIPR1(40): (D=3.141592654) value of $\pi$. */ /*HIPR1(41)--HIPR1(42): not used. */ /*HIPR1(43): (D=0.01) fractional energy error relative to the */ /* colliding energy permitted per nucleon-nucleon collision. */ /*HIPR1(44), HIPR1(45), HIPR1(46): (D=1.5, 0.1 GeV, 0.25) parameters */ /* $\alpha$, $c$ and $\beta$ in the valence quark */ /* distributions for soft string excitation, */ /* $(1-x)^{\alpha}/(x^2+c^2/s)^{\beta}$ for baryons, */ /* $1/{(x^2+c^2/s)[(1-x)^2+c^2/s)]}^{\beta}$ for mesons. */ /*HIPR1(47), HIPR1(48): (D=0.0, 0.5) parameters $\alpha$ and $\beta$ */ /* in valence quark distribution, */ /* $(1-x)^{\alpha}/(x^2+c^2/s)^{\beta}$, for the */ /* disassociated excitation in a single diffractive collision. */ /*HIPR1(49)--HIPR1(100): not used. */ /*IHPR2(1): (D=1) switch for dipole-approximated QCD radiation */ /* of the string system in soft interactions. */ /*IHPR2(2): (D=3) option for initial and final state radiation in */ /* the hard scattering. */ /* =0: both initial and final radiation are off. */ /* =1: initial radiation on and final radiation off. */ /* =2: initial radiation off and final radiation on. */ /* =3: both initial and final radiation are on. */ /*IHPR2(3): (D=0) switch for triggered hard scattering with specified */ /* $P_T\geq$HIPR1(10). */ /* =0: no triggered jet production. */ /* =1: ordinary hard processes. */ /* =2: only direct photon production. */ /*IHPR2(4): (D=1) switch for jet quenching in the excited */ /* nuclear matter. */ /*IHPR2(5): (D=1) switch for the $P_T$ kick due to soft interactions. */ /*IHPR2(6): (D=1) switch for the nuclear effect on the parton */ /* distribution function such as shadowing. */ /*IHPR2(7): (D=1) selection of Duke-Owens set (1 or 2) of parametrization */ /* of nucleon structure functions. */ /*IHPR2(8): (D=10) maximum number of hard scatterings per */ /* nucleon-nucleon interaction. When IHPR2(8)=0, jet */ /* production will be turned off. When IHPR2(8)$<0$, the */ /* number of jet production will be fixed at its absolute */ /* value for each NN collision. */ /*IHPR2(9): (D=0) switch to guarantee at least one pair of minijets */ /* production per event ($pp$, $pA$ or $AB$). */ /*IHPR2(10): (D=0) option to print warning messages about errors that */ /* might happen. When a fatal error happens the current event */ /* will be abandoned and a new one is generated. */ /*IHPR2(11): (D=1) choice of baryon production model. */ /* =0: no baryon-antibaryon pair production, initial */ /* diquark treated as a unit. */ /* =1: diquark-antidiquark pair production allowed, */ /* initial diquark treated as a unit. */ /* =2: diquark-antidiquark pair production allowed, */ /* with the possibility for diquark to split */ /* according to the ``popcorn'' scheme (see the */ /* documentation of JETSET 7.2). */ /*IHPR2(12): (D=1) option to turn off the automatic decay of the */ /* following particles: */ /* $\pi^0$, $K^0_S$, $D^{\pm}$, $\Lambda$, $\Sigma^{\pm}$. */ /*IHPR2(13): (D=1) option to turn on single diffractive reactions. */ /*IHPR2(14): (D=1) option to turn on elastic scattering. */ /*IHPR2(15)--IHPR2(18): not used. */ /*IHPR2(19): (D=1) option to turn on initial state soft interaction. */ /*IHPR2(20): (D=1) switch for the final fragmentation. */ /*IHPR2(21): (D=0) option to keep the information of all particles */ /* including those which have decayed and the decay history */ /* in the common block HIMAIN2. The line number of the parent */ /* particle is KATT(I,3). The status of a partcile, */ /* whether it is a finally produced particle (KATT(I,4)=1) */ /* or a decayed particle (KATT(I,4)=11) is also kept. */ /*IHPR2(22)-IHPR2(50): not used. */ /*HINT1(1): (GeV) colliding energy in the c.m. frame of nucleon-nucleon */ /* collisions. */ /*HINT1(2): Lorentz transformation variable $\beta$ from laboratory */ /* to c.m. frame of nucleon nucleon collisions. */ /*HINT1(3): rapidity $y_{cm}$ of the c.m. frame */ /* $\beta=\tanh y_{cm}$. */ /*HINT1(4): rapidity of projectile nucleons (hadron) $y_{proj}$. */ /*HINT1(5): rapidity of target nucleons (hadron) $y_{targ}$. */ /*HINT1(6): (GeV) energy of the projectile nucleons (hadron) in the */ /* given frame. */ /*HINT1(7): (GeV) energy of the target nucleons (hadron) in the */ /* given frame. */ /*HINT1(8): (GeV) the rest mass of projectile particles. */ /*HINT1(9): (GeV) the rest mass of target particles. */ /*HINT1(10): (mb) the averaged cross section for jet production */ /* per nucleon-nucleon collisions, */ /* $\int d^2b\{1-\exp[-\sigma_{jet}T_N(b)]\}$. */ /*HINT1(11): (mb) the averaged inclusive cross section $\sigma_{jet}$ */ /* for jet production per nucleon-nucleon collisions. */ /*HINT1(12): (mb) the averaged inelastic cross section of */ /* nucleon-nucleon collisions. */ /*HINT1(13): (mb) the averaged total cross section of nucleon-nucleon */ /* collisions. */ /*HINT1(14): (mb) the jet production cross section without nuclear */ /* shadowing effect $\sigma_{jet}^0$ (see Eq.~\ref{eq:sjetab}). */ /*HINT1(15): (mb) the cross section $\sigma_{jet}^A$ to account for */ /* the projectile shadowing correction term in the jet cross */ /* section (see Eq.~\ref{eq:sjetab}). */ /*HINT1(16): (mb) the cross section $\sigma_{jet}^B$ to account for */ /* the target shadowing correction term in the jet cross */ /* section (see Eq.~\ref{eq:sjetab}). */ /*HINT1(17): (mb) the cross section $\sigma_{jet}^{AB}$ to account */ /* for the cross term of shadowing correction in the jet */ /* cross section. */ /*HINT1(18): (mb) the effective cross section */ /* $\sigma_{jet}^{eff}(r_A,r_B)$ for jet production */ /* of the latest nucleon-nucleon collision which depends */ /* on the transverse coordinates of the colliding */ /* nucleons. */ /*HINT1(19): (fm) the (absolute value of) impact parameter of the */ /* latest event. */ /*HINT1(20): (radians) the azimuthal angle $\phi$ of the impact */ /* parameter vector in the transverse plane of the latest */ /* event. */ /*HINT1(21)--HINT1(25): the four momentum and mass ($p_x,p_y,p_z,E,M$) */ /* (GeV/$c$, GeV, GeV/$c^2$) of the first scattered parton */ /* in the triggered hard scattering. This is before the final */ /* state radiation but after the initial state radiation. */ /*HINT1(26)--HINT1(30): not used. */ /*HINT1(31)--HINT1(35): the four momentum and mass ($p_x,p_y,p_z,E,M$) */ /* (GeV/$c$, GeV, GeV/$c^2$) of the second scattered parton */ /* in the triggered hard scattering. This is before the final */ /* state radiation but after the initial state radiation. */ /*HINT1(46)--HINT1(40): not used. */ /*HINT1(41)--HINT1(45): the four momentum and mass ($p_x,p_y,p_z,E,M$) */ /* (GeV/$c$, GeV, GeV/$c^2$) of the first scattered parton */ /* in the latest hard scattering of the latest event. */ /*HINT1(46): $P_T$ (GeV/$c$) of the first scattered parton in the */ /* latest hard scattering of the latest event. */ /*HINT1(47)--HINT1(50): not used. */ /*HINT1(51)--HINT1(55): the four momentum and mass ($p_x,p_y,p_z,E,M$) */ /* (GeV/$c$, GeV, GeV/$c^2$) of the second scattered parton */ /* in the latest hard scattering of the latest event. */ /*HINT1(56): $P_T$ (GeV/$c$) of the second scattered parton in the */ /* latest hard scattering of the latest event. */ /*HINT1(57)--HINT1(58): not used. */ /*HINT1(59): (mb) the averaged cross section of the */ /* triggered jet production (with $P_T$ specified by HIPR1(10) */ /* and with switch by IHPR2(3)) per nucleon-nucleon */ /* collision, */ /* $\int d^2b\{1-\exp[-\sigma_{jet}^{trig}T_N(b)]\}$ */ /*HINT1(60): (mb) the averaged inclusive cross section of the */ /* triggered jet production $\sigma_{jet}^{trig}$ */ /* (with $P_T$ specified by */ /* HIPR1(10) and with switch by IHPR2(3)) per */ /* nucleon-nucleon collision. */ /*HINT1(61): (mb) the triggered jet production cross section without */ /* nuclear shadowing effect (similar to HINT1(14)). */ /*HINT1(62): (mb) the cross section to account for the projectile */ /* shadowing correction term in the triggered jet cross */ /* section (similar to HINT1(15)). */ /*HINT1(63): (mb) the cross section to account for the target */ /* shadowing correction term in the triggered jet cross */ /* section (similar to HINT1(16)). */ /*HINT1(64): (mb) the cross section to account for the cross */ /* term of shadowing correction in the triggered jet */ /* cross section (similar to HINT1(17). */ /*HINT1(65): (mb) the inclusive cross section for latest triggered */ /* jet production which depends on the transverse coordinates */ /* of the colliding nucleons (similar to HINT1(18)). */ /*HINT1(67)--HINT1(71): not used. */ /*HINT1(72)--HINT1(75): three parameters for the Wood-Saxon */ /* projectile nuclear distribution and the normalization */ /* read from a table inside the program, */ /* $\rho(r)=C[1+W(r/R_A)^2]/\{1+\exp[(r-R_A)/D]\}$, */ /* $R_A$=HINT1(72), $D$=HINT1(73), $W$=HINT1(74), $C$=HINT1(75). */ /*HINT1(76)--HINT1(79): three parameters for the Wood-Saxon */ /* projectile nuclear distribution and the normalization */ /* read from a table inside the program, */ /* $\rho(r)=C[1+W(r/R_A)^2]/\{1+\exp[(r-R_A)/D]\}$, */ /* $R_A$=HINT1(76), $D$=HINT1(77), $W$=HINT1(78), $C$=HINT1(79). */ /*HINT1(80)--HINT1(100): the probability of $j=0-20$ number of hard */ /* scatterings per nucleon-nucleon collisions. */ /*IHNT2(1): the mass number of the projectile nucleus (1 for a hadron). */ /*IHNT2(2): the charge number of the projectile nucleus. If the */ /* projectile is a hadron, it gives the charge of the hadron. */ /*IHNT2(3): the mass number of the target nucleus (1 for a hadron). */ /*IHNT2(4): the charge number of the target nucleus. If the target */ /* is a hadron, it gives the charge of the hadron. */ /*IHNT2(5): the flavor code of the projectile hadron (0 for nucleus). */ /*IHNT2(6): the flavor code of the target hadron (0 for nucleus). */ /*IHNT2(7)--IHNT2(8): not used. */ /*IHNT2(9): the flavor code of the first scattered parton in the */ /* triggered hard scattering. */ /*IHNT2(10): the flavor code of the second scattered parton in the */ /* triggered hard scattering. */ /*IHNT2(11): the sequence number of the projectile nucleon in the */ /* latest nucleon-nucleon interaction of the latest event. */ /*IHNT2(12): the sequence number of the target nucleon in the latest */ /* nucleon-nucleon interaction of the latest event. */ /*IHNT2(13): status of the latest soft string excitation. */ /* =1: double diffractive. */ /* =2: single diffractive. */ /* =3: non-single diffractive. */ /*IHNT2(14): the flavor code of the first scattered parton in the */ /* latest hard scattering of the latest event. */ /*IHNT2(15): the flavor code of the second scattered parton in the */ /* latest hard scattering of the latest event. */ /*IHNT2(16)--IHNT2(50): not used. */ /*========================================================================*/ /*========================================================================*/ /* COMMON/HIMAIN1/ NATT,EATT,JATT,NT,NP,N0,N01,N10,N11,BB */ /*------------------------------------------------------------------------*/ typedef struct { Int_t natt; Float_t eatt; Int_t jatt; Int_t nt; Int_t np; Int_t n0; Int_t n01; Int_t n10; Int_t n11; Float_t bb; Int_t npart; Float_t phirp; } Himain1Common; #define HIMAIN1 COMMON_BLOCK(HIMAIN1,himain1) COMMON_BLOCK_DEF(Himain1Common,HIMAIN1); /*************************************************************************/ /* D E S C R I P T I O N : */ /*-----------------------------------------------------------------------*/ /*COMMON/HIMAIN1/NATT, EATT, JATT, NT, NP, N0, N01, N10, N11 */ /*Purpose: to give the overall information of the generated event. */ /*NATT: total number of produced stable and undecayed particles of */ /* the current event. */ /*EATT: the total energy of the produced particles in c.m. frame */ /* of the collision to check energy conservation. */ /*JATT: the total number of hard scatterings in the current event. */ /*NP, NT: the number of participant projectile and target nucleons */ /* in the current event. */ /*N0, N01, N10, N11: number of $N$-$N$, $N$-$N_{wounded}$, */ /* $N_{wounded}$-$N$, and */ /* $N_{wounded}$-$N_{wounded}$ collisions in */ /* the current event ($N$, $N_{wounded}$ stand */ /* for nucleon and wounded nucleon respectively). */ /*=======================================================================*/ /*========================================================*/ /* COMMON/HIMAIN2/KATT(200000,4),PATT(200000,4),VATT(200000,4)*/ /*--------------------------------------------------------*/ typedef struct { Int_t katt[4][200000]; Float_t patt[4][200000]; Float_t vatt[4][200000]; } Himain2Common; #define HIMAIN2 COMMON_BLOCK(HIMAIN2,himain2) COMMON_BLOCK_DEF(Himain2Common,HIMAIN2); /*************************************************************************/ /* D E S C R I P T I O N : */ /*-----------------------------------------------------------------------*/ /*Purpose: to give information of produced stable and undecayed */ /* particles. Parent particles which decayed are not included */ /* here. */ /*KATT(I, 1): (I=1,$\cdots$,NATT) flavor codes (see appendix) of */ /* the produced particles. */ /*KATT(I, 2): (I=1,$\cdots$,NATT) status codes to identify the */ /* sources from which the particles come. */ /* =0: projectile nucleon (or hadron) which has */ /* not interacted at all. */ /* =1: projectile nucleon (or hadron) which */ /* only suffers an elastic collision. */ /* =2: from a diffractive projectile nucleon (or hadron) */ /* in a single diffractive interaction. */ /* =3: from the fragmentation of a projectile string */ /* system (including gluon jets). */ /* =10 target nucleon (or hadron) which has not */ /* interacted at all. */ /* =11: target nucleon (or hadron) which only */ /* suffers an elastic collision. */ /* =12: from a diffractive target nucleon (or hadron) */ /* in a single diffractive interaction. */ /* =13: from the fragmentation of a target string */ /* system (including gluon jets). */ /* =20: from scattered partons which form string */ /* systems themselves. */ /* =40: from direct production in the hard processes */ /* ( currently, only direct photons are included). */ /*KATT(I,3): (I=1,$\cdots$,NATT) line number of the parent particle. */ /* For finally produced or directly produced (not from */ /* the decay of another particle) particles, it is set */ /* to 0 (The option to keep the information of all */ /* particles including the decayed ones is IHPR2(21)=1). */ /*KATT(I,4): (I=1,$\cdots$,NATT) status number of the particle. */ /* =1: finally or directly produced particles. */ /* =11: particles which has already decayed. */ /*PATT(I, 1-4): (I=1,$\cdots$,NATT) four-momentum ($p_x,p_y,p_z,E$) */ /* (GeV/$c$, GeV) of the produced particles. */ /* */ /*=======================================================================*/ /*=======================================================================*/ /* COMMON/HIJJET1/NPJ(300),KFPJ(300,500),PJPX(300,500),PJPY(300,500) */ /* & ,PJPZ(300,500),PJPE(300,500),PJPM(300,500) */ /* & ,NTJ(300),KFTJ(300,500),PJTX(300,500),PJTY(300,500) */ /* & ,PJTZ(300,500),PJTE(300,500),PJTM(300,500) */ /*-----------------------------------------------------------------------*/ typedef struct { Int_t npj[300]; Int_t kfpj[500][300]; Float_t pjpx[500][300]; Float_t pjpy[500][300]; Float_t pjpz[500][300]; Float_t pjpe[500][300]; Float_t pjpm[500][300]; Int_t ntj[300]; Int_t kftj[500][300]; Float_t pjtx[500][300]; Float_t pjty[500][300]; Float_t pjtz[500][300]; Float_t pjte[500][300]; Float_t pjtm[500][300]; } Hijjet1Common; #define HIJJET1 COMMON_BLOCK(HIJJET1,hijjet1) COMMON_BLOCK_DEF(Hijjet1Common,HIJJET1); /*************************************************************************/ /* D E S C R I P T I O N : */ /*-----------------------------------------------------------------------*/ /*Purpose: contains information about produced partons which are */ /* connected with the valence quarks and diquarks of */ /* projectile or target nucleons (or hadron) to form */ /* string systems for fragmentation. The momentum and */ /* energy of all produced partons are calculated in */ /* the c.m. frame of the collision. IAP, IAT are the */ /* numbers of nucleons in projectile and target nucleus */ /* respectively (IAP, IAT=1 for hadron projectile or target). */ /*NPJ(I): (I=1,$\cdots$,IAP) number of partons associated with projectile*/ /* nucleon I. */ /*KFPJ(I, J): (I=1,$\cdots$,IAP, J=1,$\cdots$,NPJ(I)) parton */ /* flavor code of the */ /* parton J associated with projectile nucleon I. */ /*PJPX(I, J), PJPY(I, J), PJPZ(I, J), PJPE(I, J), PJPM(I, J): the four */ /* momentum and mass ($p_x,p_y,p_z,E,M$) */ /* (GeV/$c$, GeV, GeV/$c^2$) of parton J associated with */ /* the projectile nucleon I. */ /*NTJ(I): (I=1,$\cdots$,IAT) number of partons associated with */ /* target nucleon I. */ /*KFTJ(I, J): (I=1,$\cdots$,IAT, J=1,$\cdots$,NTJ(I)): parton */ /* flavor code of the parton J associated with */ /* target nucleon I. */ /*PJTX(I, J), PJTY(I, J), PJTZ(I, J), PJTE(I, J), PJTM(I, J): the four */ /* momentum and mass ($p_x,p_y,p_z,E,M$) */ /* (GeV/$c$, GeV, GeV/$c^2$) of parton J associated with */ /* target nucleon I. */ /* */ /*=======================================================================*/ /*=======================================================================*/ /* COMMON/HIJJET2/NSG,NJSG(900),IASG(900,3),K1SG(900,100), */ /* & K2SG(900,100),PXSG(900,100),PYSG(900,100), */ /* & PZSG(900,100),PESG(900,100),PMSG(900,100) */ /*-----------------------------------------------------------------------*/ typedef struct { Int_t nsg; Int_t njsg[900]; Int_t iasg[3][900]; Int_t k1sg[100][900]; Int_t k2sg[100][900]; Float_t pxsg[100][900]; Float_t pysg[100][900]; Float_t pzsg[100][900]; Float_t pesg[100][900]; Float_t pmsg[100][900]; } Hijjet2Common; #define HIJJET2 COMMON_BLOCK(HIJJET2,hijjet2) COMMON_BLOCK_DEF(Hijjet2Common,HIJJET2); /*************************************************************************/ /* D E S C R I P T I O N : */ /*-----------------------------------------------------------------------*/ /*Purpose: contains information about the produced partons which */ /* will form string systems themselves without being */ /* connected to valence quarks and diquarks. */ /*NSG: the total number of such string systems. */ /*NJSG(I): (I=1,$\cdots$,NSG) number of partons in the string system I. */ /*IASG(I, 1), IASG(I, 2): to specify which projectile and target */ /* nucleons produce string system I. */ /*IASG(I, 3): to indicate whether the jets will be quenched (0) */ /* or will not be quenched (1). */ /*K1SG(I, J): (J=1,$\cdots$,NJSG(I)) color flow information of parton J */ /* in string system I (see JETSET 7.2 for detailed */ /* explanation). */ /*K2SG(I, J): (J=1,$\cdots$,NJSG(I)) flavor code of parton J in string */ /* system I. */ /*PXSG(I, J), PYSG(I, J), PZSG(I, J), PESG(I, J), PMSG(I, J): four */ /* momentum and mass ($p_x,p_y,p_z,E,M$) */ /* ( GeV/$c$, GeV, GeV/$c^2$) of parton J in string system I. */ /*=======================================================================*/ /*=======================================================================*/ /* COMMON/HISTRNG/NFP(300,15),PP(300,15),NFT(300,15),PT(300,15) */ /*-----------------------------------------------------------------------*/ typedef struct { Int_t nfp[15][300]; Float_t pp[15][300]; Int_t nft[15][300]; Float_t pt[15][300]; } HistrngCommon; #define HISTRNG COMMON_BLOCK(HISTRNG,histrng) COMMON_BLOCK_DEF(HistrngCommon,HISTRNG); /*************************************************************************/ /* D E S C R I P T I O N : */ /*-----------------------------------------------------------------------*/ /* The following common block is added to record the number of elastic*/ /* (NELT, NELP) and inelastic (NINT, NINP) participants */ /* */ /*=======================================================================*/ /* COMMON/HIJGLBR/NELT,NINT,NELP,NINP */ /* SAVE /HIJGLBR/ */ /*=======================================================================*/ typedef struct { Int_t nelt; Int_t nint; Int_t nelp; Int_t ninp; Int_t npspecp; Int_t nnspecp; Int_t npspect; Int_t nnspect; } HijglbrCommon; #define HIJGLBR COMMON_BLOCK(HIJGLBR,hijglbr) COMMON_BLOCK_DEF(HijglbrCommon,HIJGLBR); /*************************************************************************/ /* D E S C R I P T I O N : */ /*-----------------------------------------------------------------------*/ /*Purpose: contains information about the projectile and */ /* target nucleons (hadron) and the corresponding constituent */ /* quarks, diquarks. IAP, IAT are the numbers of nucleons in */ /* projectile and target nucleus respectively (IAP, IAT=1 */ /* for hadron projectile or target). */ /*NFP(I, 1): (I=1,$\cdots$,IAP) flavor code of the valence quark in */ /* projectile nucleon (hadron) I. */ /*NFP(I, 2): flavor code of diquark in projectile nucleon (anti-quark */ /* in projectile meson) I. */ /*NFP(I, 3): present flavor code of the projectile nucleon (hadron) I */ /* ( a nucleon or meson can be excited to its vector resonance). */ /*NFP(I, 4): original flavor code of projectile nucleon (hadron) I. */ /*NFP(I, 5): collision status of projectile nucleon (hadron) I. */ /* =0: suffered no collision. */ /* =1: suffered an elastic collision. */ /* =2: being the diffractive one in a single-diffractive */ /* collision. */ /* =3: became an excited string after an inelastic */ /* collision. */ /*NFP(I, 6): the total number of hard scatterings associated with */ /* projectile nucleon (hadron) I. If NFP(I,6)$<0$, it can not */ /* produce jets any more due to energy conservation. */ /*NFP(I, 10): to indicate whether the valence quarks or diquarks */ /* (anti-quarks) in projectile nucleon (hadron) I */ /* suffered a hard scattering, */ /* =0: has not suffered a hard scattering. */ /* =1: suffered one or more hard scatterings in */ /* current binary nucleon-nucleon collision. */ /* =-1: suffered one or more hard scatterings in */ /* previous binary nucleon-nucleon collisions. */ /*NFP(I, 11): total number of interactions projectile nucleon (hadron) */ /* I has suffered so far. */ /*PP(I, 1), PP(I, 2), PP(I, 3), PP(I, 4), PP(I, 5): four momentum and */ /* the invariant mass ($p_x,p_y,p_z,E,M$) */ /* (GeV/$c$, GeV, GeV/$c^2$) of projectile nucleon (hadron) I. */ /*PP(I, 6), PP(I, 7): transverse momentum ($p_x,p_y$) (GeV/$c$) of the */ /* valence quark in projectile nucleon (hadron) I. */ /*PP(I, 8), PP(I, 9): transverse momentum ($p_x,p_y$) (GeV/$c$) of the */ /* diquark (anti-quark) in projectile nucleon (hadron) I. */ /*PP(I, 10), PP(I, 11), PP(I, 12): three momentum ($p_x,p_y,p_z$) */ /* (GeV/$c$) transferred to the quark or diquark (anti-quark) */ /* in projectile nucleon (hadron) I from the last hard */ /* scattering. */ /*PP(I, 14): mass (GeV/$c^2$) of the quark in projectile nucleon */ /* (hadron) I. */ /*PP(I, 15): mass of the diquark (anti-quark) in projectile */ /* nucleon (hadron) I. */ /*NFT(I, 1--15), PT(I,1--15): give the same */ /* information for the target nucleons (hadron) and the */ /* corresponding quarks and diquarks (anti-quarks) as for */ /* the projectile nucleons. */ /* */ /*=======================================================================*/ // COMMON/LUDAT1_HIJING/MSTU(200),PARU(200),MSTJ(200),PARJ(200) // SAVE /LUDAT1_HIJING/ typedef struct { Int_t mstu[200]; Float_t paru[200]; Int_t mstj[200]; Float_t parj[200]; } Ludat1_HijingCommon; #define LUDAT1_HIJING COMMON_BLOCK(LUDAT1_HIJING,ludat1_hijing) COMMON_BLOCK_DEF(Ludat1_HijingCommon,LUDAT1_HIJING); } //COMMON/LUDAT3_HIJING/MDCY(500, 3),MDME(2000, 2),BRAT(2000),KFDP(2000, 5) typedef struct { Int_t mdcy[3][500]; Int_t mdme[2][2000]; Float_t brat[2000]; Float_t kfdp[5][2000]; } Ludat3_HijingCommon; #define LUDAT3_HIJING COMMON_BLOCK(LUDAT3_HIJING,ludat3_hijing) COMMON_BLOCK_DEF(Ludat3_HijingCommon,LUDAT3_HIJING); #endif
52.3568
76
0.551264
[ "vector", "model" ]
c59b9aaf06b1b6e06734e9dd62b062fd3a6ae580
5,188
c
C
src/RIOT/cpu/cc26xx_cc13xx/vectors.c
ARte-team/ARte
19f17f57522e1b18ba390718fc94be246451837b
[ "MIT" ]
2
2020-04-30T08:17:45.000Z
2020-05-23T08:46:54.000Z
src/RIOT/cpu/cc26xx_cc13xx/vectors.c
ARte-team/ARte
19f17f57522e1b18ba390718fc94be246451837b
[ "MIT" ]
null
null
null
src/RIOT/cpu/cc26xx_cc13xx/vectors.c
ARte-team/ARte
19f17f57522e1b18ba390718fc94be246451837b
[ "MIT" ]
null
null
null
/* * Copyright (C) 2016 Leon George * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. */ /** * @ingroup cpu_cc26xx_cc13xx * @{ * * @file * @brief Interrupt vector definitions * * @author Leon M. George <leon@georgemail.eu> * @author Anton Gerasimov <tossel@gmail.com> */ #include <stdint.h> #include "cpu.h" #include "board.h" #include "vectors_cortexm.h" /* define a local dummy handler as it needs to be in the same compilation unit * as the alias definition */ void dummy_handler(void) { dummy_handler_default(); } /* CC26xx_CC13xx specific interrupt vectors */ WEAK_DEFAULT void isr_edge(void); WEAK_DEFAULT void isr_i2c(void); WEAK_DEFAULT void isr_rfc_cpe1(void); WEAK_DEFAULT void isr_pka(void); WEAK_DEFAULT void isr_aon_rtc(void); WEAK_DEFAULT void isr_uart0(void); WEAK_DEFAULT void isr_aux0_aon(void); WEAK_DEFAULT void isr_ssi0(void); WEAK_DEFAULT void isr_ssi1(void); WEAK_DEFAULT void isr_rfc_cpe0(void); WEAK_DEFAULT void isr_rfc_hw(void); WEAK_DEFAULT void isr_rfc_cmd_ack(void); WEAK_DEFAULT void isr_i2s(void); WEAK_DEFAULT void isr_aux1_aon(void); WEAK_DEFAULT void isr_watchdog(void); WEAK_DEFAULT void isr_timer0_chan0(void); WEAK_DEFAULT void isr_timer0_chan1(void); WEAK_DEFAULT void isr_timer1_chan0(void); WEAK_DEFAULT void isr_timer1_chan1(void); WEAK_DEFAULT void isr_timer2_chan0(void); WEAK_DEFAULT void isr_timer2_chan1(void); WEAK_DEFAULT void isr_timer3_chan0(void); WEAK_DEFAULT void isr_timer3_chan1(void); WEAK_DEFAULT void isr_crypto_res(void); WEAK_DEFAULT void isr_dma(void); WEAK_DEFAULT void isr_dmaerr(void); WEAK_DEFAULT void isr_flash(void); WEAK_DEFAULT void isr_se0(void); WEAK_DEFAULT void isr_aux_ce(void); WEAK_DEFAULT void isr_aon_prog(void); WEAK_DEFAULT void isr_dyn_prog(void); WEAK_DEFAULT void isr_comp(void); WEAK_DEFAULT void isr_adc(void); WEAK_DEFAULT void isr_trng(void); #ifdef CPU_VARIANT_X2 WEAK_DEFAULT void isr_osc(void); WEAK_DEFAULT void isr_aux_timer2(void); WEAK_DEFAULT void isr_uart1(void); WEAK_DEFAULT void isr_batmon(void); #endif // CPU_VARIANT_X2 /* CPU specific interrupt vector table */ ISR_VECTOR(1) const isr_t vector_cpu[] = { isr_edge, /* 16 AON edge detect */ isr_i2c, /* 17 I2C */ isr_rfc_cpe1, /* 18 RF Command and Packet Engine 1 */ isr_pka, /* 19 PKA interrupt */ isr_aon_rtc, /* 20 AON RTC */ isr_uart0, /* 21 UART0 Rx and Tx */ isr_aux0_aon, /* 22 AUX event 0, through AON domain */ isr_ssi0, /* 23 SSI0 Rx and Tx */ isr_ssi1, /* 24 SSI1 Rx and Tx */ isr_rfc_cpe0, /* 25 RF Command and Packet Engine 0 */ isr_rfc_hw, /* 26 RF Core Hardware */ isr_rfc_cmd_ack, /* 27 RF Core Command Acknowledge */ isr_i2s, /* 28 I2S */ isr_aux1_aon, /* 29 AUX event 1, through AON domain */ isr_watchdog, /* 30 Watchdog timer */ isr_timer0_chan0, /* 31 Timer 0 subtimer A */ isr_timer0_chan1, /* 32 Timer 0 subtimer B */ isr_timer1_chan0, /* 33 Timer 1 subtimer A */ isr_timer1_chan1, /* 34 Timer 1 subtimer B */ isr_timer2_chan0, /* 35 Timer 2 subtimer A */ isr_timer2_chan1, /* 36 Timer 2 subtimer B */ isr_timer3_chan0, /* 37 Timer 3 subtimer A */ isr_timer3_chan1, /* 38 Timer 3 subtimer B */ isr_crypto_res, /* 39 Crypto Core Result available */ isr_dma, /* 40 uDMA Software */ isr_dmaerr, /* 41 uDMA Error */ isr_flash, /* 42 Flash controller */ isr_se0, /* 43 Software Event 0 */ isr_aux_ce, /* 44 AUX combined event, directly to MCU domain */ isr_aon_prog, /* 45 AON programmable 0 */ isr_dyn_prog, /* 46 Dynamic Programmable interrupt (default source: PRCM) */ isr_comp, /* 47 AUX Comparator A */ isr_adc, /* 48 AUX ADC IRQ */ isr_trng, /* 49 TRNG event */ #ifdef CPU_VARIANT_X2 isr_osc, /* 50 Combined event from oscillator control */ isr_aux_timer2, /* 51 AUX Timer 2 event 0 */ isr_uart1, /* 52 UART 1 RX and TX */ isr_batmon, /* 53 BATMON interrupt */ #endif // CPU_VARIANT_X2 }; /** @} */
43.966102
89
0.566692
[ "vector" ]
c59dba440fee6656e7433910184511b06addee41
3,220
h
C
wrappers/7.0.0/vtkKCoreLayoutWrap.h
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/7.0.0/vtkKCoreLayoutWrap.h
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/7.0.0/vtkKCoreLayoutWrap.h
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #ifndef NATIVE_EXTENSION_VTK_VTKKCORELAYOUTWRAP_H #define NATIVE_EXTENSION_VTK_VTKKCORELAYOUTWRAP_H #include <nan.h> #include <vtkSmartPointer.h> #include <vtkKCoreLayout.h> #include "vtkGraphAlgorithmWrap.h" #include "../../plus/plus.h" class VtkKCoreLayoutWrap : public VtkGraphAlgorithmWrap { public: using Nan::ObjectWrap::Wrap; static void Init(v8::Local<v8::Object> exports); static void InitPtpl(); static void ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info); VtkKCoreLayoutWrap(vtkSmartPointer<vtkKCoreLayout>); VtkKCoreLayoutWrap(); ~VtkKCoreLayoutWrap( ); static Nan::Persistent<v8::FunctionTemplate> ptpl; private: static void New(const Nan::FunctionCallbackInfo<v8::Value>& info); static void CartesianOff(const Nan::FunctionCallbackInfo<v8::Value>& info); static void CartesianOn(const Nan::FunctionCallbackInfo<v8::Value>& info); static void FillInputPortInformation(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetCartesian(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetCartesianCoordsXArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetCartesianCoordsYArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetEpsilon(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetPolar(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetPolarCoordsAngleArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetPolarCoordsRadiusArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetUnitRadius(const Nan::FunctionCallbackInfo<v8::Value>& info); static void IsA(const Nan::FunctionCallbackInfo<v8::Value>& info); static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info); static void PolarOff(const Nan::FunctionCallbackInfo<v8::Value>& info); static void PolarOn(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetCartesian(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetCartesianCoordsXArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetCartesianCoordsYArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetEpsilon(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetGraphConnection(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetKCoreLabelArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetPolar(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetPolarCoordsAngleArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetPolarCoordsRadiusArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetUnitRadius(const Nan::FunctionCallbackInfo<v8::Value>& info); #ifdef VTK_NODE_PLUS_VTKKCORELAYOUTWRAP_CLASSDEF VTK_NODE_PLUS_VTKKCORELAYOUTWRAP_CLASSDEF #endif }; #endif
48.059701
94
0.78913
[ "object" ]
c5a36ade47e43bcaa608acc614ee97d3abcb213d
6,389
h
C
services/err_events/al_err_events_pcie.h
delroth/alpine_hal
eb6b9f132c08eb3cd70a6a94586bcd689a244d0a
[ "Unlicense" ]
1
2022-02-03T01:04:47.000Z
2022-02-03T01:04:47.000Z
services/err_events/al_err_events_pcie.h
delroth/alpine_hal
eb6b9f132c08eb3cd70a6a94586bcd689a244d0a
[ "Unlicense" ]
null
null
null
services/err_events/al_err_events_pcie.h
delroth/alpine_hal
eb6b9f132c08eb3cd70a6a94586bcd689a244d0a
[ "Unlicense" ]
null
null
null
/* * Copyright 2017, Amazon.com, Inc. or its affiliates. All Rights Reserved */ #ifndef __AL_ERR_EVENTS_PCIE_H__ #define __AL_ERR_EVENTS_PCIE_H__ #include "al_err_events.h" #include "al_hal_pcie.h" /******************************************************************************* ** Error ID's ******************************************************************************/ /* * PCIe Application errors ID's */ enum al_err_events_pcie_app { AL_ERR_EVENTS_PCIE_APP_CORE_INTERNAL_DECOMPOSE_LOGIC_ERROR = 0, AL_ERR_EVENTS_PCIE_APP_PARITY_ERROR, AL_ERR_EVENTS_PCIE_APP_WRITE_OVERFLOW_ERROR, AL_ERR_EVENTS_PCIE_APP_INTERNAL_OVERFLOW_ERROR, AL_ERR_EVENTS_PCIE_APP_SYS_ERR_FUNC_0, AL_ERR_EVENTS_PCIE_APP_SYS_ERR_FUNC_1, AL_ERR_EVENTS_PCIE_APP_SYS_ERR_FUNC_2, AL_ERR_EVENTS_PCIE_APP_SYS_ERR_FUNC_3, AL_ERR_EVENTS_PCIE_APP_AER_ERR_INT_0, AL_ERR_EVENTS_PCIE_APP_AER_ERR_INT_1, AL_ERR_EVENTS_PCIE_APP_AER_ERR_INT_2, AL_ERR_EVENTS_PCIE_APP_AER_ERR_INT_3, AL_ERR_EVENTS_PCIE_APP_AER_ERR_MSI_0, AL_ERR_EVENTS_PCIE_APP_AER_ERR_MSI_1, AL_ERR_EVENTS_PCIE_APP_AER_ERR_MSI_2, AL_ERR_EVENTS_PCIE_APP_AER_ERR_MSI_3, AL_ERR_EVENTS_PCIE_APP_AP_CRCTBL_STAT_0, AL_ERR_EVENTS_PCIE_APP_AP_CRCTBL_STAT_1, AL_ERR_EVENTS_PCIE_APP_AP_CRCTBL_STAT_2, AL_ERR_EVENTS_PCIE_APP_AP_CRCTBL_STAT_3, AL_ERR_EVENTS_PCIE_APP_AP_UNCRCTBL_STAT_0, AL_ERR_EVENTS_PCIE_APP_AP_UNCRCTBL_STAT_1, AL_ERR_EVENTS_PCIE_APP_AP_UNCRCTBL_STAT_2, AL_ERR_EVENTS_PCIE_APP_AP_UNCRCTBL_STAT_3, AL_ERR_EVENTS_PCIE_APP_MAX_ERRORS, }; /* * PCIe AXI errors ID's */ enum al_err_events_pcie_axi { AL_ERR_EVENTS_PCIE_AXI_PARITY_ERROR = 0, AL_ERR_EVENTS_PCIE_AXI_CORE_INTERNAL_DECOMPOSE_LOGIC_ERROR, AL_ERR_EVENTS_PCIE_AXI_MASTER_READ_DATA_PARITY_ERROR, AL_ERR_EVENTS_PCIE_AXI_SLAVE_READ_ADDR_PARITY_ERROR, AL_ERR_EVENTS_PCIE_AXI_SLAVE_WRITE_ADDR_PARITY_ERROR, AL_ERR_EVENTS_PCIE_AXI_SLAVE_WRITE_DATA_PARITY_ERROR, AL_ERR_EVENTS_PCIE_AXI_READ_COMPLETION_ERROR, AL_ERR_EVENTS_PCIE_AXI_WRITE_COMPLETION_ERROR, AL_ERR_EVENTS_PCIE_AXI_READ_COMPLETION_TIMEOUT, AL_ERR_EVENTS_PCIE_AXI_WRITE_COMPLETION_TIMEOUT, AL_ERR_EVENTS_PCIE_AXI_POS_ERROR, AL_ERR_EVENTS_PCIE_AXI_WRITE_RESPONED_ERROR, AL_ERR_EVENTS_PCIE_AXI_MAX_ERRORS, }; /******************************************************************************* ** Init params ******************************************************************************/ struct al_err_events_pcie_init_params { /** Initialized PCie port object */ struct al_pcie_port *pcie_port; /** collection mode */ enum al_err_events_collect collect_mode; }; /******************************************************************************* ** Error Data structures ******************************************************************************/ struct al_err_pcie_axi_parity { unsigned int u5_ram2p; unsigned int u4_ram2p; unsigned int u3_ram2p; unsigned int u2_ram2p; unsigned int u12_ram2p; unsigned int u10_ram2p; }; struct al_err_pcie_app_parity_v1_v2 { unsigned int u_ram_1p_sotbuf; unsigned int u0_ram_radm_qbuffer; unsigned int u3_qbuffer_0; unsigned int u3_qbuffer_1; unsigned int u9_decomp; unsigned int u8_ram2p; unsigned int u7_ram2p; unsigned int u6_ram2p; unsigned int u11_ram2p; unsigned int u1_ram2p; unsigned int u0_ram2p; unsigned int u0_rbuf; unsigned int u3_qbuffer_2; }; struct al_err_pcie_app_parity_v3 { unsigned int ram_1p_rbuf; unsigned int ram_2p_sotbuf; unsigned int u0_ram_radm_qbuffer_hdr; unsigned int u3_ram_radm_qbuffer_data_0; unsigned int u3_ram_radm_qbuffer_data_1; unsigned int u10_ram2p_0; unsigned int u10_ram2p_1; unsigned int u8_ram2p; unsigned int u7_ram2p; unsigned int u6_ram; unsigned int u11_ram2p; unsigned int u1_ram2p; unsigned int u0_ram2p; }; struct al_err_events_pcie_app_data { /** PCie error event module */ struct al_err_events_module module; /** PCIe error events fields */ struct al_err_events_field fields[AL_ERR_EVENTS_PCIE_APP_MAX_ERRORS]; struct al_pcie_port *pcie_port; struct al_err_pcie_app_parity_v1_v2 app_v1_v2_parity; struct al_err_pcie_app_parity_v3 app_v3_parity; }; struct al_err_events_pcie_axi_data { /** PCie error event module */ struct al_err_events_module module; /** PCIe error events fields */ struct al_err_events_field fields[AL_ERR_EVENTS_PCIE_AXI_MAX_ERRORS]; struct al_pcie_port *pcie_port; /** AXI read data parity error latched address */ uint64_t axi_read_data_parity_address; /** AXI read completion error latched address */ uint64_t axi_read_completion_error_address; /** AXI write completion error latched address */ uint64_t axi_write_completion_error_address; /** AXI read completion timeout latched address */ uint64_t axi_read_compl_timeout_address; /** AXI write completion timeout error latched address */ uint64_t axi_write_cmpl_timeout_address; /** AXI POS error latched address */ uint64_t axi_pos_error_addr; struct al_err_pcie_axi_parity axi_parity; }; /******************************************************************************* ** API ******************************************************************************/ /* * Initialize PCIe Application error events * * @param handle Error events handle * @param data PCIe Application error events object * @param params PCIe initialization parameters * * @return 0 on success, errno otherwise */ int al_err_events_pcie_app_init(struct al_err_events_handle *handle, struct al_err_events_pcie_app_data *data, struct al_err_events_pcie_init_params *params); /* * Enable PCIe Application error interrupts * * @param data PCIe Application error events initialized object * * @return 0 on success, errno otherwise */ int al_err_events_pcie_app_int_enable(struct al_err_events_pcie_app_data *data); /* * Initialize PCIe AXI error events * * @param handle Error events handle * @param data PCIe AXI error events object * @param params PCIe AXI parameters * * @return 0 on success, errno otherwise */ int al_err_events_pcie_axi_init(struct al_err_events_handle *handle, struct al_err_events_pcie_axi_data *data, struct al_err_events_pcie_init_params *params); /* * Enable PCIe AXI error interrupts * * @param data PCIe AXI error events initialized object * * @return 0 on success, errno otherwise */ int al_err_events_pcie_axi_int_enable(struct al_err_events_pcie_axi_data *data); #endif /* __AL_ERR_EVENTS_PCIE_H__ */
30.279621
80
0.743465
[ "object" ]
c5a4f1f014e47ac49cfe4a81f1d97519c3b5c567
2,083
h
C
mem-axc-64/apps/macsim.r.d.b.s/macsim-mem-axc-64/include/context.h
vnaveen0/nachos
99933b0da5474bf43bd167d2540438375237b2d9
[ "MIT" ]
1
2018-02-28T10:00:00.000Z
2018-02-28T10:00:00.000Z
mem-axc-64/apps/macsim.r.d.b.s/macsim-mem-axc-64/include/context.h
vnaveen0/nachos
99933b0da5474bf43bd167d2540438375237b2d9
[ "MIT" ]
1
2020-04-06T22:30:00.000Z
2020-04-06T22:30:00.000Z
mem-axc-64/apps/macsim.r.d.b.s/macsim-mem-axc-64/include/context.h
vnaveen0/nachos
99933b0da5474bf43bd167d2540438375237b2d9
[ "MIT" ]
null
null
null
#ifndef CONTEXT_H #define CONTEXT_H #include <iostream> #include <vector> #include "thread.h" #include "alloc_thread_info.h" #include "assert.h" #include "cmath" int hash_func(int tid, int core_id); int get_tid_frm_hash_value(int hash_value); int get_core_id_frm_hash_value(int hash_value); //----------------------------- typedef int thread_id; //------------------------------ typedef struct context_s { //should contain current instruction pointer -- m_buffer_index contains the current instruction pointer from the struct "thread_s" //and register dependencies - map_c thread_s* thread_info; alloc_thread_info alloc_th_info; // alloc_thread_info* alloc_th_info; // context_s(thread_s* _th ,int tid, core_c* core); // ~context_s(); context_s(thread_s* _th, alloc_thread_info _a_th_info){ thread_info = _th; alloc_th_info = _a_th_info; } } context_s; //------------------------------ class co_switch_handler_c { public: co_switch_handler_c(); std::unordered_map<int,context_s* > m_ready_context_map; std::unordered_map<int,context_s* > m_mem_wait_context_map; std::unordered_map<int,context_s* > m_chunk_wait_context_map; std::array< unordered_map<int,context_s* >, 2> m_wait_context_map{ { m_chunk_wait_context_map,m_mem_wait_context_map } }; std::unordered_map<int,context_s* > m_context_map_pool; bool context_switch( thread_s * _th,alloc_thread_info _a_th_info, int core_id,int tid, bool is_mem);// current thread info and current instruction pointer bool is_present_mem_wait_context(int core_id, int tid, bool is_mem); bool mv_context_mem_wait_to_ready(int tid,int core_id, bool is_mem) ; void ready_context_flush() ; bool push_mem_wait_context_vec( context_s curr_context,int core_id); void print_mem_wait_context_vec(); void print_ready_context_vec(); context_s* is_ready_context_vec_empty(int core_id); context_s* rr_ready_context(int core_id); context_s fetch_ready_context(int core_id) ; ~co_switch_handler_c(); }; #endif
24.797619
160
0.716275
[ "vector" ]
c5a86d78ae45cb42c64d023ac8e222255d633dd8
5,153
h
C
src/monitor/include/HostMonitorManager.h
semiozbas/one
1793699a2996db631b298a1bc8972bae36c1e71e
[ "Apache-2.0" ]
null
null
null
src/monitor/include/HostMonitorManager.h
semiozbas/one
1793699a2996db631b298a1bc8972bae36c1e71e
[ "Apache-2.0" ]
null
null
null
src/monitor/include/HostMonitorManager.h
semiozbas/one
1793699a2996db631b298a1bc8972bae36c1e71e
[ "Apache-2.0" ]
null
null
null
/* -------------------------------------------------------------------------- */ /* Copyright 2002-2020, OpenNebula Project, OpenNebula Systems */ /* */ /* 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 HOST_MONITOR_MANAGER_H_ #define HOST_MONITOR_MANAGER_H_ #include "MonitorDriverMessages.h" #include "HostRPCPool.h" #include <vector> class Template; class VectorAttribute; template<typename E, typename D> class DriverManager; class VMRPCPool; class OneMonitorDriver; class UDPMonitorDriver; class TCPMonitorDriver; class MonitorDriver; class Monitor; /** * This class controls the monitor actions and logic of OpenNebula hosts * */ class HostMonitorManager { public: HostMonitorManager(HostRPCPool *hp, VMRPCPool *vmp, const std::string& addr, unsigned int port, unsigned int threads, const std::string& driver_path, int timer_period, int monitor_interval_host); ~HostMonitorManager(); OneMonitorDriver* get_oned_driver() const { return oned_driver; } //-------------------------------------------------------------------------- // Driver Interface //-------------------------------------------------------------------------- /** * */ int load_monitor_drivers(const std::vector<const VectorAttribute*>& config); /** * Start the monitor manager drivers to process events */ int start(std::string& error); //-------------------------------------------------------------------------- // Management / Monitor Interface //-------------------------------------------------------------------------- /** * Start the monitor agent/ or active monitor the host * @param oid the host id */ void start_host_monitor(int oid); /** * Stop the monitor agent/ or stop monitor the host * @param oid the host id */ void stop_host_monitor(int oid); /** * Updates the information of the given host. If it does not exist it is * added to the pool * @param oid host id * @param xml the XML representation of the host */ void update_host(int oid, const std::string &xml); /** * Updates the last monitoring for the host * @param oid host id */ void update_last_monitor(int oid); /** * Remove host from the pool * @param oid host id */ void delete_host(int oid); /** * Sets the monitor information of the host. It notifies oned if needed. * @param oid host id * @param tmpl monitoring template */ void monitor_host(int oid, bool result, const Template &tmpl); /** * Sets the monitor information of the VM. * @param oid VM id * @param result * @param tmpl monitoring template */ void monitor_vm(int oid, const std::string &deploy_id, const Template &tmpl); /** * Receive start monitor failure/success from driver * @param oid host id */ void start_monitor_failure(int oid); void start_monitor_success(int oid); /** * This function is executed periodically to update host monitor status */ void timer_action(); private: using driver_manager_t = DriverManager<MonitorDriverMessages, MonitorDriver>; driver_manager_t* driver_manager; OneMonitorDriver* oned_driver; UDPMonitorDriver* udp_driver; TCPMonitorDriver* tcp_driver; HostRPCPool* hpool; VMRPCPool* vmpool; unsigned int threads; /** * Timer period for timer_action loop */ int timer_period; /** * Host monitoring interval */ int monitor_interval_host; /** * Time in seconds to expire a monitoring action (5 minutes) */ static const time_t monitor_expire; /** * Default timeout to wait for monitor drivers */ static const int driver_timeout = 3; void start_host_monitor(const HostRPCPool::HostBaseLock& host); void stop_host_monitor(const HostRPCPool::HostBaseLock& host); }; #endif //HOST_MONITOR_MANAGER_H_
29.112994
81
0.543761
[ "vector" ]
c5aa014530c28808ea2b53a494673257731f24b0
46,005
c
C
src/kernel/src/sched/signal.c
GrieferAtWork/KOS
5376a813854b35e3a3532a6e3b8dbb168478b40f
[ "Zlib" ]
2
2017-02-24T17:14:19.000Z
2017-10-12T19:26:13.000Z
src/kernel/src/sched/signal.c
GrieferAtWork/KOS
5376a813854b35e3a3532a6e3b8dbb168478b40f
[ "Zlib" ]
1
2019-11-02T10:21:11.000Z
2019-11-02T10:21:11.000Z
src/kernel/src/sched/signal.c
GabrielRavier/KOSmk3
5376a813854b35e3a3532a6e3b8dbb168478b40f
[ "Zlib" ]
1
2019-11-02T10:20:19.000Z
2019-11-02T10:20:19.000Z
/* Copyright (c) 2018 Griefer@Work * * * * 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, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 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 GUARD_KERNEL_SRC_SCHED_SIGNAL_C #define GUARD_KERNEL_SRC_SCHED_SIGNAL_C 1 #define _KOS_SOURCE 1 #define _NOSERVE_SOURCE 1 #include <hybrid/compiler.h> #include <hybrid/atomic.h> #include <kos/types.h> #include <hybrid/section.h> #include <kernel/sections.h> #include <kernel/malloc.h> #include <kernel/vm.h> #include <dev/wall.h> #include <kernel/debug.h> #include <kernel/interrupt.h> #include <kernel/bind.h> #include <sched/signal.h> #include <sched/task.h> #include <sched/pertask-arith.h> #include <except.h> #include <assert.h> #include <string.h> DECL_BEGIN INTERN ATTR_PERTASK struct task_connections my_connections = { .tcs_siz = CONFIG_TASK_STATIC_CONNECTIONS }; LOCAL void KCALL relocate_connection(struct task_connection *__restrict dst, struct task_connection *__restrict src) { struct task_connection *primary; struct sig *signal; assert(src->tc_sig); signal = dst->tc_sig = src->tc_sig; signal = (struct sig *)((uintptr_t)signal & TASK_CONNECTION_SIG_FMASK); sig_get(signal); COMPILER_READ_BARRIER(); dst->tc_pself = src->tc_pself; /* Also sets `tc_last' */ if unlikely(!src->tc_pself) { /* Dead connection */ sig_put(signal); } else { primary = SIG_GETCON(signal); dst->tc_next = src->tc_next; if (dst->tc_next) { assert(src != primary->tc_last); assert(TASK_CONNECTION_GETSIG(dst->tc_next) == signal); assert(dst->tc_next->tc_pself == &src->tc_next); dst->tc_next->tc_pself = &dst->tc_next; if (src == primary) { /* Relocate the new primary connection. */ ATOMIC_WRITE(signal->s_ptr,(uintptr_t)dst); } else { *dst->tc_pself = dst; sig_put(signal); } } else { assert(src == primary->tc_last); if (src == primary) { /* Relocate the sole primary connection. */ dst->tc_last = dst; /* `dst' will be the new primary */ ATOMIC_WRITE(signal->s_ptr,(uintptr_t)dst); } else { /* Relocate the new primary connection. */ primary->tc_last = dst; *dst->tc_pself = dst; sig_put(signal); } } } } LOCAL void KCALL delete_connection(struct task_connection *__restrict con) { struct task_connection *primary; struct sig *signal = TASK_CONNECTION_GETSIG(con); assert(signal); sig_get(signal); if (!con->tc_pself) { /* Dead connection */ assert(con != SIG_GETCON(signal)); sig_put(signal); } else { primary = SIG_GETCON(signal); assert(TASK_CONNECTION_GETSIG(primary) == signal); if (con == primary) { /* Primary connection. */ if ((primary = con->tc_next) != NULL) assert(TASK_CONNECTION_GETSIG(primary) == signal), assert(primary->tc_pself == &con->tc_next), primary->tc_last = con->tc_last; ATOMIC_WRITE(signal->s_ptr,(uintptr_t)primary); } else { if ((*con->tc_pself = con->tc_next) == NULL) { /* Last connection. */ assert(con == primary->tc_last); primary->tc_last = COMPILER_CONTAINER_OF(con->tc_pself, struct task_connection, tc_next); } else { /* Secondary connection. */ assert(con != primary->tc_last); con->tc_next->tc_pself = con->tc_pself; } sig_put(signal); } } } DEFINE_PERTASK_INIT(connect_init); INTERN ATTR_NOTHROW void KCALL connect_init(struct task *__restrict thread) { unsigned int i; struct task_connections *con; /* Initialize the static connections vector. */ con = &FORTASK(thread,my_connections); con->tcs_tsk = thread; con->tcs_vec = con->tcs_sbuf; assert(con->tcs_siz == CONFIG_TASK_STATIC_CONNECTIONS); for (i = 0; i < CONFIG_TASK_STATIC_CONNECTIONS; ++i) { assert(con->tcs_sbuf[i].tc_sig == NULL); con->tcs_sbuf[i].tc_conn = con; } COMPILER_WRITE_BARRIER(); } DEFINE_PERTASK_FINI(connect_fini); INTERN ATTR_NOTHROW void KCALL connect_fini(struct task *__restrict thread) { struct task_connections *mycon; struct task_connection *vec; unsigned int i; mycon = &FORTASK(thread,my_connections); assert(mycon->tcs_tsk == thread); vec = mycon->tcs_vec; /* Disconnect remaining signals. (Prevents a race condition when a * thread is destroyed with signals when one of those signals is sent) */ for (i = 0; i < mycon->tcs_cnt; ++i) { assert(vec[i].tc_conn == mycon); delete_connection(&vec[i]); } /* Free a dynamic connections buffer. */ if (vec != mycon->tcs_sbuf) kfree(vec); } PRIVATE void *KCALL kmalloc_consafe(size_t n_bytes, gfp_t flags) { return TASK_EVAL_CONSAFE(kmalloc(n_bytes,flags)); } PRIVATE void *KCALL krealloc_consafe(void *ptr, size_t n_bytes, gfp_t flags) { return TASK_EVAL_CONSAFE(krealloc(ptr,n_bytes,flags)); } PRIVATE void KCALL kfree_consafe(void *ptr) { struct task_connections consave; task_push_connections(&consave); kfree(ptr); task_pop_connections(&consave); } #if !defined(NDEBUG) && 1 PRIVATE ATTR_PERTASK unsigned int connections_push_recursion = 0; PRIVATE ATTR_PERTASK struct task_connections *connections_push_stack[16]; #define DEBUG_PUSH_CONNECTIONS(safe) do_debug_push_connections(safe) #define DEBUG_POP_CONNECTIONS(safe) do_debug_pop_connections(safe) PRIVATE void KCALL do_debug_push_connections(struct task_connections *__restrict safe) { unsigned int i,index = PERTASK_GET(connections_push_recursion); assert(index != (unsigned int)-1); if (index < COMPILER_LENOF(connections_push_stack)) { PERTASK_SET(connections_push_stack[index],safe); for (i = 0; i < index; ++i) { assertf(safe < PERTASK_GET(connections_push_stack[i]) || safe >= PERTASK_GET(connections_push_stack[i])+1, "Overlapping connections restore descriptors:\n" "Task connections set %p overlaps with set at %p\n" "This is likely caused by a loop that doesn't " "properly restore the saved connections set", safe,PERTASK_GET(connections_push_stack[i])); } } PERTASK_INC(connections_push_recursion); } PRIVATE void KCALL do_debug_pop_connections(struct task_connections *__restrict safe) { unsigned int count; count = PERTASK_GET(connections_push_recursion); assertf(count != 0,"Connections weren't pushed"); if (count < COMPILER_LENOF(connections_push_stack)) { assertf(PERTASK_GET(connections_push_stack[count-1]) == safe, "Incorrect restore location (expected %p, but got %p)\n" "count = %u\n", PERTASK_GET(connections_push_stack[count-1]), safe,count); } PERTASK_DEC(connections_push_recursion); } #else #define DEBUG_PUSH_CONNECTIONS(safe) (void)0 #define DEBUG_POP_CONNECTIONS(safe) (void)0 #endif PUBLIC ATTR_NOTHROW void KCALL task_push_connections(struct task_connections *__restrict safe) { struct task_connections *mycon; unsigned int i; DEBUG_PUSH_CONNECTIONS(safe); mycon = &PERTASK(my_connections); assert(mycon->tcs_cnt <= mycon->tcs_siz); assert(mycon->tcs_tsk == THIS_TASK); /* Save the used and allocates connection size. */ safe->tcs_chn = mycon->tcs_chn; safe->tcs_cnt = mycon->tcs_cnt; if (!safe->tcs_cnt) return; /* No active connections. */ safe->tcs_siz = mycon->tcs_siz; safe->tcs_tsk = mycon->tcs_tsk; if likely(mycon->tcs_vec == mycon->tcs_sbuf) { /* The static buffer is being used. */ assert(mycon->tcs_siz == CONFIG_TASK_STATIC_CONNECTIONS); safe->tcs_vec = safe->tcs_sbuf; for (i = 0; i < safe->tcs_cnt; ++i) { struct task_connection *dst = &safe->tcs_sbuf[i]; struct task_connection *src = &mycon->tcs_sbuf[i]; assert(src->tc_conn == mycon); dst->tc_conn = safe; relocate_connection(dst,src); } COMPILER_BARRIER(); safe->tcs_sig = mycon->tcs_sig; } else { /* A dynamic buffer is being used. */ safe->tcs_vec = mycon->tcs_vec; for (i = 0; i < safe->tcs_cnt; ++i) { struct task_connection *con = &safe->tcs_vec[i]; struct sig *signal; signal = TASK_CONNECTION_GETSIG(con); assert(signal); assert(con->tc_conn == mycon); sig_get(signal); con->tc_conn = safe; sig_put(signal); } COMPILER_BARRIER(); safe->tcs_sig = mycon->tcs_sig; mycon->tcs_vec = mycon->tcs_sbuf; mycon->tcs_siz = CONFIG_TASK_STATIC_CONNECTIONS; } mycon->tcs_cnt = 0; mycon->tcs_sig = NULL; COMPILER_WRITE_BARRIER(); } PUBLIC ATTR_NOTHROW void KCALL task_pop_connections(struct task_connections *__restrict safe) { struct task_connections *mycon; unsigned int i; DEBUG_POP_CONNECTIONS(safe); task_disconnect(); mycon = &PERTASK(my_connections); mycon->tcs_chn = safe->tcs_chn; if (!safe->tcs_cnt) return; assert(!mycon->tcs_sig); assert(!mycon->tcs_cnt); assert(safe->tcs_tsk == THIS_TASK); assert(mycon->tcs_tsk == THIS_TASK); mycon->tcs_cnt = safe->tcs_cnt; if likely(safe->tcs_vec == safe->tcs_sbuf) { if (mycon->tcs_vec != mycon->tcs_sbuf) { kfree(mycon->tcs_vec); mycon->tcs_vec = mycon->tcs_sbuf; mycon->tcs_siz = CONFIG_TASK_STATIC_CONNECTIONS; } /* Relocate the static buffer. */ assert(safe->tcs_siz == CONFIG_TASK_STATIC_CONNECTIONS); assert(mycon->tcs_siz == CONFIG_TASK_STATIC_CONNECTIONS); for (i = 0; i < safe->tcs_cnt; ++i) { struct task_connection *dst = &mycon->tcs_sbuf[i]; struct task_connection *src = &safe->tcs_sbuf[i]; assert(src->tc_conn == safe); assert(dst->tc_conn == mycon); relocate_connection(dst,src); } } else { if (mycon->tcs_vec != mycon->tcs_sbuf) kfree(mycon->tcs_vec); /* A dynamic buffer is being used. */ mycon->tcs_vec = safe->tcs_vec; mycon->tcs_siz = safe->tcs_siz; for (i = 0; i < safe->tcs_cnt; ++i) { struct task_connection *con = &mycon->tcs_vec[i]; struct sig *signal; signal = TASK_CONNECTION_GETSIG(con); assert(signal); assert(con->tc_conn == safe); sig_get(signal); con->tc_conn = mycon; sig_put(signal); } } COMPILER_BARRIER(); assert(mycon->tcs_cnt <= mycon->tcs_siz); /* If a signal was send to the saved connections set, inherit it. */ ATOMIC_CMPXCH(mycon->tcs_sig,NULL,safe->tcs_sig); } PUBLIC ATTR_HOTTEXT void KCALL task_connect(struct sig *__restrict signal) { struct task_connections *mycon; struct task_connection *con; struct task_connection *primary; mycon = &PERTASK(my_connections); if (mycon->tcs_sig) return; /* A signal was already send. */ assert(mycon->tcs_cnt <= mycon->tcs_siz); assert(mycon->tcs_siz != 0); assert(mycon->tcs_tsk == THIS_TASK); con = mycon->tcs_vec; /* Most likely case: first connection. */ if likely(!mycon->tcs_cnt) goto fill_con; if unlikely(mycon->tcs_cnt == mycon->tcs_siz) { unsigned int i; size_t new_siz = mycon->tcs_siz; TRY { if (con == mycon->tcs_sbuf) { assert(mycon->tcs_siz == CONFIG_TASK_STATIC_CONNECTIONS); /* The static buffer was being used. */ con = (struct task_connection *)kmalloc_consafe(new_siz*sizeof(struct task_connection), GFP_SHARED); for (i = 0; i < CONFIG_TASK_STATIC_CONNECTIONS; +i) { con[i].tc_conn = mycon; relocate_connection(&con[i],&mycon->tcs_sbuf[i]); } mycon->tcs_vec = con; } else { /* Try to inplace-extend the vector of existing * connections, so we don't have to relocate it. */ if (!krealloc_consafe(con,new_siz*sizeof(struct task_connection), GFP_SHARED|GFP_NOMOVE)) { struct task_connection *new_con; /* Didn't work. -> Must allocate a new vector and relocate into it. */ new_con = (struct task_connection *)kmalloc_consafe(new_siz*sizeof(struct task_connection), GFP_SHARED); /* Relocate connections into the new buffer. */ for (i = 0; i < mycon->tcs_siz; ++i) { new_con[i].tc_conn = mycon; relocate_connection(&new_con[i],&con[i]); } kfree_consafe(mycon->tcs_vec); mycon->tcs_vec = con = new_con; } /* Setup connection set pointers for newly allocated connections. */ for (i = mycon->tcs_siz; i < new_siz; ++i) con[i].tc_conn = mycon; } } EXCEPT (EXCEPT_EXECUTE_HANDLER) { /* Disconnect all signals that were already * connected if we've failed to allocate more slots. */ task_disconnect(); error_rethrow(); } mycon->tcs_siz = new_siz; } /* Append a new connection at the end of the vector. */ con += mycon->tcs_cnt; fill_con: assert(con->tc_conn == mycon); con->tc_sig = signal; con->tc_next = NULL; ++mycon->tcs_cnt; #ifndef NDEBUG assert((u32)signal->s_ptr != 0xdeadbeef); #endif sig_get(signal); primary = SIG_GETCON(signal); if likely(primary == NULL) { /* Primary connection. */ con->tc_last = con; ATOMIC_WRITE(signal->s_ptr,(uintptr_t)con); /* Write + unlock. */ } else { struct task_connection *last; /* Secondary connection. */ #ifndef NDEBUG last = primary; while (last->tc_next) last = last->tc_next; assertf(last == primary->tc_last, "Broken last: %p != %p", last,primary->tc_last); #else last = primary->tc_last; #endif assert(last); con->tc_pself = &last->tc_next; last->tc_next = con; primary->tc_last = con; sig_put(signal); } } PUBLIC void KCALL task_connect_ghost(struct sig *__restrict signal) { struct task_connections *mycon; struct task_connection *con; struct task_connection *primary; mycon = &PERTASK(my_connections); if (mycon->tcs_sig) return; /* A signal was already send. */ assert(mycon->tcs_cnt <= mycon->tcs_siz); assert(mycon->tcs_siz != 0); assert(mycon->tcs_tsk == THIS_TASK); con = mycon->tcs_vec; /* Most likely case: first connection. */ if likely(!mycon->tcs_cnt) goto fill_con; if unlikely(mycon->tcs_cnt == mycon->tcs_siz) { unsigned int i; size_t new_siz = mycon->tcs_siz; TRY { if (con == mycon->tcs_sbuf) { assert(mycon->tcs_siz == CONFIG_TASK_STATIC_CONNECTIONS); /* The static buffer was being used. */ con = (struct task_connection *)kmalloc_consafe(new_siz*sizeof(struct task_connection), GFP_SHARED); for (i = 0; i < CONFIG_TASK_STATIC_CONNECTIONS; +i) { con[i].tc_conn = mycon; relocate_connection(&con[i],&mycon->tcs_sbuf[i]); } mycon->tcs_vec = con; } else { /* Try to inplace-extend the vector of existing * connections, so we don't have to relocate it. */ if (!krealloc_consafe(con,new_siz*sizeof(struct task_connection), GFP_SHARED|GFP_NOMOVE)) { struct task_connection *new_con; /* Didn't work. -> Must allocate a new vector and relocate into it. */ new_con = (struct task_connection *)kmalloc_consafe(new_siz*sizeof(struct task_connection), GFP_SHARED); /* Relocate connections into the new buffer. */ for (i = 0; i < mycon->tcs_siz; ++i) { new_con[i].tc_conn = mycon; relocate_connection(&new_con[i],&con[i]); } kfree_consafe(mycon->tcs_vec); mycon->tcs_vec = con = new_con; } /* Setup connection set pointers for newly allocated connections. */ for (i = mycon->tcs_siz; i < new_siz; ++i) con[i].tc_conn = mycon; } } EXCEPT (EXCEPT_EXECUTE_HANDLER) { /* Disconnect all signals that were already * connected if we've failed to allocate more slots. */ task_disconnect(); error_rethrow(); } mycon->tcs_siz = new_siz; } /* Append a new connection at the end of the vector. */ con += mycon->tcs_cnt; fill_con: assert(con->tc_conn == mycon); con->tc_sig = (struct sig *)((uintptr_t)signal | TASK_CONNECTION_SIG_FGHOST); con->tc_next = NULL; ++mycon->tcs_cnt; #ifndef NDEBUG assert((u32)signal->s_ptr != 0xdeadbeef); #endif sig_get(signal); primary = SIG_GETCON(signal); if likely(primary == NULL) { /* Primary connection. */ con->tc_last = con; ATOMIC_WRITE(signal->s_ptr,(uintptr_t)con); /* Write + unlock. */ } else { struct task_connection *last; /* Secondary connection. */ #ifndef NDEBUG last = primary; while (last->tc_next) last = last->tc_next; assertf(last == primary->tc_last, "Broken last: %p != %p", last,primary->tc_last); #else last = primary->tc_last; #endif assert(last); con->tc_pself = &last->tc_next; last->tc_next = con; primary->tc_last = con; sig_put(signal); } } PUBLIC ATTR_HOTTEXT ATTR_NOTHROW struct sig *KCALL task_disconnect(void) { struct sig *result; struct task_connections *mycon; struct task_connection *vec; unsigned int i; mycon = &PERTASK(my_connections); if (!mycon->tcs_cnt) { assert(!mycon->tcs_sig); return NULL; } vec = mycon->tcs_vec; for (i = 0; i < mycon->tcs_cnt; ++i) { assert(vec[i].tc_conn == mycon); delete_connection(&vec[i]); } COMPILER_BARRIER(); mycon->tcs_cnt = 0; result = mycon->tcs_sig; mycon->tcs_sig = NULL; COMPILER_BARRIER(); return result; } PUBLIC ATTR_NOTHROW bool KCALL task_isconnected(void) { return PERTASK_TEST(my_connections.tcs_cnt); } PUBLIC ATTR_NOTHROW size_t KCALL task_numconnected(void) { return PERTASK_GET(my_connections.tcs_cnt); } PUBLIC ATTR_NOTHROW bool KCALL task_connected(struct sig *__restrict signal) { unsigned int i; struct task_connections *mycon; mycon = &PERTASK(my_connections); /* Check if the given `signal' appears in any connection slot. */ for (i = 0; i < mycon->tcs_cnt; ++i) { if (TASK_CONNECTION_GETSIG(&mycon->tcs_vec[i]) == signal) return true; } return false; } PUBLIC ATTR_NOTHROW bool KCALL task_setsignaled(struct sig *__restrict signal) { assertf(task_connected(signal), "The calling thread is not connected to a signal at %p", signal); return ATOMIC_CMPXCH(PERTASK(my_connections.tcs_sig),NULL,signal); } PUBLIC ATTR_HOTTEXT struct sig * KCALL __os_task_waitfor(jtime_t abs_timeout) { struct task_connections *mycon; struct sig *COMPILER_IGNORE_UNINITIALIZED(result); bool sleep_ok; mycon = &PERTASK(my_connections); TRY { /* We require that the caller have preemption enable. */ if (!PREEMPTION_ENABLED()) error_throw(E_WOULDBLOCK); for (;;) { /* Disable preemption to ensure that no task * for the current CPU could send the signal. * Additionally, no other CPU will be able to * interrupt us while we check for signals, meaning * that any task_wake IPIs will only be received once * `task_sleep()' gets around to re-enable interrupts. */ PREEMPTION_DISABLE(); result = ATOMIC_READ(mycon->tcs_sig); if (result) { PREEMPTION_ENABLE(); break; } /* Serve RPC functions. */ if (task_serve()) continue; /* Sleep for a bit, or until we're interrupted. */ sleep_ok = task_sleep(abs_timeout); result = ATOMIC_READ(mycon->tcs_sig); /* A signal was received in the mean time. */ if (result) break; if (!sleep_ok) break; /* Timeout */ /* Continue spinning */ } } FINALLY { /* Always disconnect all connected signals, * thus resetting the connections list. */ if (FINALLY_WILL_RETHROW) asm("nop"); task_disconnect(); } return result; } PUBLIC ATTR_HOTTEXT struct sig * KCALL task_qwaitfor(qtime_t abs_timeout) { struct task_connections *mycon; struct sig *COMPILER_IGNORE_UNINITIALIZED(result); bool sleep_ok; mycon = &PERTASK(my_connections); TRY { /* We require that the caller have preemption enable. */ if (!PREEMPTION_ENABLED()) error_throw(E_WOULDBLOCK); for (;;) { /* Disable preemption to ensure that no task * for the current CPU could send the signal. * Additionally, no other CPU will be able to * interrupt us while we check for signals, meaning * that any task_wake IPIs will only be received once * `task_sleep()' gets around to re-enable interrupts. */ PREEMPTION_DISABLE(); result = ATOMIC_READ(mycon->tcs_sig); if (result) { PREEMPTION_ENABLE(); break; } /* Serve RPC functions. */ if (task_serve()) continue; /* Sleep for a bit, or until we're interrupted. */ sleep_ok = task_qsleep(abs_timeout); result = ATOMIC_READ(mycon->tcs_sig); /* A signal was received in the mean time. */ if (result) break; if (!sleep_ok) break; /* Timeout */ /* Continue spinning */ } } FINALLY { /* Always disconnect all connected signals, * thus resetting the connections list. */ task_disconnect(); } return result; } PUBLIC ATTR_NOTHROW struct sig *KCALL task_trywait(void) { struct sig *result; result = PERTASK_GET(my_connections.tcs_sig); COMPILER_READ_BARRIER(); if (result) task_disconnect(); return result; } PUBLIC ATTR_HOTTEXT ATTR_RETNONNULL struct sig *KCALL task_wait(void) { return __os_task_waitfor(JTIME_INFINITE); } PUBLIC ATTR_HOTTEXT struct sig * KCALL __os_task_waitfor_noserve(jtime_t abs_timeout) { struct task_connections *mycon; struct sig *COMPILER_IGNORE_UNINITIALIZED(result); bool sleep_ok; mycon = &PERTASK(my_connections); TRY { /* We require that the caller have preemption enable. */ if (!PREEMPTION_ENABLED()) error_throw(E_WOULDBLOCK); for (;;) { /* Disable preemption to ensure that no task * for the current CPU could send the signal. * Additionally, no other CPU will be able to * interrupt us while we check for signals, meaning * that any task_wake IPIs will only be received once * `task_sleep()' gets around to re-enable interrupts. */ PREEMPTION_DISABLE(); result = ATOMIC_READ(mycon->tcs_sig); if (result) { PREEMPTION_ENABLE(); break; } /* Sleep for a bit, or until we're interrupted. */ sleep_ok = task_sleep(abs_timeout); result = ATOMIC_READ(mycon->tcs_sig); /* A signal was received in the mean time. */ if (result) break; if (!sleep_ok) break; /* Timeout */ /* Continue spinning */ } } FINALLY { /* Always disconnect all connected signals, * thus resetting the connections list. */ task_disconnect(); } return result; } PUBLIC ATTR_HOTTEXT struct sig * KCALL task_qwaitfor_noserve(qtime_t abs_timeout) { struct task_connections *mycon; struct sig *COMPILER_IGNORE_UNINITIALIZED(result); bool sleep_ok; mycon = &PERTASK(my_connections); TRY { /* We require that the caller have preemption enable. */ if (!PREEMPTION_ENABLED()) error_throw(E_WOULDBLOCK); for (;;) { /* Disable preemption to ensure that no task * for the current CPU could send the signal. * Additionally, no other CPU will be able to * interrupt us while we check for signals, meaning * that any task_wake IPIs will only be received once * `task_sleep()' gets around to re-enable interrupts. */ PREEMPTION_DISABLE(); result = ATOMIC_READ(mycon->tcs_sig); if (result) { PREEMPTION_ENABLE(); break; } /* Sleep for a bit, or until we're interrupted. */ sleep_ok = task_qsleep(abs_timeout); result = ATOMIC_READ(mycon->tcs_sig); /* A signal was received in the mean time. */ if (result) break; if (!sleep_ok) break; /* Timeout */ /* Continue spinning */ } } FINALLY { /* Always disconnect all connected signals, * thus resetting the connections list. */ task_disconnect(); } return result; } PUBLIC ATTR_HOTTEXT ATTR_RETNONNULL struct sig *KCALL task_wait_noserve(void) { return __os_task_waitfor_noserve(JTIME_INFINITE); } PRIVATE ATTR_HOTTEXT ATTR_NOTHROW bool KCALL sig_sendone_locked(struct sig *__restrict self, bool unlock) { struct task_connection *primary,*next_con,*last_con; struct task_connections *cons; bool wake_ok = false; assert(sig_holding(self)); again: primary = SIG_GETCON(self); if (!primary) { if (unlock) sig_put(self); return false; } cons = primary->tc_conn; #if 0 /* Not necessarily the case while relocating... */ assertf(primary >= cons->tcs_vec && primary <= cons->tcs_vec+cons->tcs_cnt, "primary = %p\n" "cons->tcs_tsk = %p\n" "cons = %p\n" "&FORTASK(cons->tcs_tsk,my_connections) = %p\n" "cons->tcs_vec = %p\n" "cons->tcs_vec+cons->tcs_cnt = %p\n" "cons->tcs_cnt = %p\n" ,primary ,cons->tcs_tsk ,cons ,&FORTASK(cons->tcs_tsk,my_connections) ,cons->tcs_vec ,cons->tcs_vec+cons->tcs_cnt ,cons->tcs_cnt); #endif /* Try to set this signal as the one that will be received by the task. */ if likely(ATOMIC_CMPXCH(cons->tcs_sig,NULL,self)) { /* If the signal got delivered to the main connection set, wake the task. */ if likely(cons == &FORTASK(cons->tcs_tsk,my_connections)) { wake_ok = task_wake(cons->tcs_tsk); if (wake_ok) /* Ghost connections don't count as active receivers. */ wake_ok = !((uintptr_t)primary->tc_sig & TASK_CONNECTION_SIG_FGHOST); } else { #if 1 /* Even though we can guaranty that the target thread will eventually * receive this signal, we have no way of ensuring that it will actually * act on it. * Because of this (and the fact that we didn't actually wake it), we must * assume the worst and act as though the thread will never receive it: * >> struct sig s = SIG_INIT; * >> * >> thread: * >> struct task_connections cons; * >> task_connect(&s); * >> * >> // This code is basically what is executed during #PF handling * >> // But since something might go wrong during that, despite the * >> // fact that the thread will actually restore its old connections * >> // properly, there is no way of predicting if it will actually * >> // act on them. * >> // If the caller only wants us to wake ~1~ task, they should be * >> // able to assume that at least ~1~ task was woken (not at most) * >> // Otherwise, what would be the point of it when a mutex could * >> // be sure that at least one waiter was woken unless it woke all * >> // of them whenever the lock gets released. * >> task_push_connections(&cons); * >> TRY { * >> if (!try_some_stuff()) * >> error_throw(E_BADALLOC); * >> } FINALLY { * >> task_pop_connections(&cons); * >> } * >> * >> // Wait for the signal * >> task_wait(); * >> */ wake_ok = false; #else /* This still counts as an OK wake, as the thread will * eventually notice what we've done when its saved * connection set is restored. */ wake_ok = true; #endif } } /* Remove this connection. */ assert(TASK_CONNECTION_GETSIG(primary) == self); next_con = primary->tc_next; last_con = primary->tc_last; COMPILER_READ_BARRIER(); primary->tc_pself = NULL; /* Indicate that a signal was send to this slot */ assert(TASK_CONNECTION_GETSIG(primary) == self); COMPILER_WRITE_BARRIER(); assertf((last_con == primary) == (next_con == NULL), "last_con = %p\n" "con = %p\n" "next_con = %p\n", last_con,primary,next_con); if (!next_con) { ATOMIC_WRITE(self->s_ptr,unlock ? 0 : SIG_FLOCKBIT); } else { /* Load the next connection. */ assert(TASK_CONNECTION_GETSIG(next_con) == self); assert(next_con->tc_pself == &primary->tc_next); /* Update the last-pointer of the next connection. */ next_con->tc_last = last_con; COMPILER_WRITE_BARRIER(); /* Save a pointer to the next connection in the signal. */ if (!unlock) *(uintptr_t *)&next_con |= SIG_FLOCKBIT; ATOMIC_WRITE(self->s_ptr,(uintptr_t)next_con); } /* If we didn't manage the wake any thread, start again. * The caller is either expecting us to wake everyone (in which * case they'll re-run us no matter what), or they expect us * to wake up to a certain number of tasks (in which case us * failing to wake some task shouldn't count to the number of * supposedly woken tasks) * Consider a mutex for example: * - During an unlock, only a single task is woken, * considering the fact that only a single task * can even hold the mutex at the same time. * - If that wake fails, the caller will think * that there are no tasks connected to the signal * and will continue, assuming that noone needed * to be woken. * - This in turn could lead to a deadlock a mutex * UP operation wouldn't actually wake any tasks, * despite the fact that there are tasks waiting. */ if unlikely(!wake_ok) { if (unlock) sig_get(self); goto again; } return true; } PUBLIC ATTR_HOTTEXT ATTR_NOTHROW size_t KCALL sig_send(struct sig *__restrict self, size_t max_threads) { size_t result = 0; /* Optimization: If there are no threads * waiting for this signal, stop immediately. */ if (!ATOMIC_READ(self->s_ptr)) goto done; while (result < max_threads) { bool send_ok; /* Temporarily acquire a lock, then send the signal. */ sig_get(self); send_ok = sig_sendone_locked(self,true); if (!send_ok) break; ++result; } done: return result; } PUBLIC ATTR_HOTTEXT ATTR_NOTHROW size_t KCALL sig_broadcast(struct sig *__restrict self) { size_t result = 0; /* Optimization: If there are no threads * waiting for this signal, stop immediately. */ if (!ATOMIC_READ(self->s_ptr)) goto done; for (;;) { bool send_ok; /* Temporarily acquire a lock, then send the signal. */ sig_get(self); send_ok = sig_sendone_locked(self,true); if (!send_ok) break; ++result; } done: return result; } PUBLIC ATTR_HOTTEXT ATTR_NOTHROW size_t KCALL sig_send_locked(struct sig *__restrict self, size_t max_threads) { size_t result = 0; while (result < max_threads && sig_sendone_locked(self,false)) ++result; return result; } PUBLIC ATTR_HOTTEXT ATTR_NOTHROW size_t KCALL sig_broadcast_locked(struct sig *__restrict self) { size_t result = 0; while (sig_sendone_locked(self,false)) ++result; return result; } /* Channel-based signal delivery. */ PRIVATE ATTR_NOTHROW bool KCALL sig_sendone_channel_locked(struct sig *__restrict self, uintptr_t signal_mask, bool unlock) { struct task_connection *primary,*target; struct task_connection *next_con,*last_con; struct task_connections *cons; bool wake_ok = false; assert(sig_holding(self)); again: primary = SIG_GETCON(self); if (!primary) { stop_sending: if (unlock) sig_put(self); return false; } target = primary; /* Find the first target listening for the given channel mask. */ for (;;) { assert(TASK_CONNECTION_GETSIG(target) == self); cons = target->tc_conn; if ((cons->tcs_chn & signal_mask) != 0) break; target = target->tc_next; if (!target) goto stop_sending; } /* Try to set this signal as the one that will be received by the task. */ if likely(ATOMIC_CMPXCH(cons->tcs_sig,NULL,self)) { /* If the signal got delivered to the main connection set, wake the task. */ if likely(cons == &FORTASK(cons->tcs_tsk,my_connections)) { wake_ok = task_wake(cons->tcs_tsk); if (wake_ok) /* Ghost connections don't count as active receivers. */ wake_ok = !((uintptr_t)primary->tc_sig & TASK_CONNECTION_SIG_FGHOST); } else { wake_ok = false; } } /* Remove this connection. */ assert(TASK_CONNECTION_GETSIG(target) == self); if (target == primary) { next_con = primary->tc_next; last_con = primary->tc_last; COMPILER_READ_BARRIER(); primary->tc_pself = NULL; /* Indicate that a signal was send to this slot */ assert(TASK_CONNECTION_GETSIG(primary) == self); COMPILER_WRITE_BARRIER(); assertf((last_con == primary) == (next_con == NULL), "last_con = %p\n" "con = %p\n" "next_con = %p\n", last_con,primary,next_con); if (!next_con) { ATOMIC_WRITE(self->s_ptr,unlock ? 0 : SIG_FLOCKBIT); } else { /* Load the next connection. */ assert(TASK_CONNECTION_GETSIG(next_con) == self); assert(next_con->tc_pself == &primary->tc_next); /* Update the last-pointer of the next connection. */ next_con->tc_last = last_con; COMPILER_WRITE_BARRIER(); /* Save a pointer to the next connection in the signal. */ if (!unlock) *(uintptr_t *)&next_con |= SIG_FLOCKBIT; ATOMIC_WRITE(self->s_ptr,(uintptr_t)next_con); } } else { if ((*target->tc_pself = target->tc_next) != NULL) { assert(primary->tc_last != target); assert(target->tc_next->tc_pself == &target->tc_next); target->tc_next->tc_pself = target->tc_pself; } else { assert(primary->tc_last == target); /* Update the new last connection pointer. */ primary->tc_last = COMPILER_CONTAINER_OF(target->tc_pself, struct task_connection, tc_next); } COMPILER_WRITE_BARRIER(); target->tc_pself = NULL; /* Indicate that a signal was send to this slot */ COMPILER_WRITE_BARRIER(); if (unlock) sig_put(self); } if unlikely(!wake_ok) { if (unlock) sig_get(self); goto again; } return true; } PUBLIC ATTR_NOTHROW size_t KCALL sig_send_channel(struct sig *__restrict self, uintptr_t signal_mask, size_t max_threads) { size_t result = 0; /* Optimization: If there are no threads * waiting for this signal, stop immediately. */ if (!ATOMIC_READ(self->s_ptr)) goto done; while (result < max_threads) { bool send_ok; /* Temporarily acquire a lock, then send the signal. */ sig_get(self); send_ok = sig_sendone_channel_locked(self,signal_mask,true); if (!send_ok) break; ++result; } done: return result; } PUBLIC ATTR_NOTHROW size_t KCALL sig_broadcast_channel(struct sig *__restrict self, uintptr_t signal_mask) { size_t result = 0; /* Optimization: If there are no threads * waiting for this signal, stop immediately. */ if (!ATOMIC_READ(self->s_ptr)) goto done; for (;;) { bool send_ok; /* Temporarily acquire a lock, then send the signal. */ sig_get(self); send_ok = sig_sendone_channel_locked(self,signal_mask,true); if (!send_ok) break; ++result; } done: return result; } PUBLIC ATTR_NOTHROW size_t KCALL sig_send_channel_locked(struct sig *__restrict self, uintptr_t signal_mask, size_t max_threads) { size_t result = 0; while (result < max_threads && sig_sendone_channel_locked(self,signal_mask,false)) ++result; return result; } PUBLIC ATTR_NOTHROW size_t KCALL sig_broadcast_channel_locked(struct sig *__restrict self, uintptr_t signal_mask) { size_t result = 0; while (sig_sendone_channel_locked(self,signal_mask,false)) ++result; return result; } /* Alternate signal sender functions. * Although they easily could be, these are not used to * implement their regular counterparts, so-as to ensure * that those functions operate as efficiently as possible. */ PRIVATE ATTR_NOTHROW bool KCALL sig_altsendone_locked(struct sig *__restrict self, struct sig *sender, bool unlock) { struct task_connection *primary,*next_con,*last_con; struct task_connections *cons; bool wake_ok = false; assert(sender != NULL); assert(sig_holding(self)); again: primary = SIG_GETCON(self); if (!primary) { if (unlock) sig_put(self); return false; } cons = primary->tc_conn; if likely(ATOMIC_CMPXCH(cons->tcs_sig,NULL,sender)) { if likely(cons == &FORTASK(cons->tcs_tsk,my_connections)) { wake_ok = task_wake(cons->tcs_tsk); if (wake_ok) wake_ok = !((uintptr_t)primary->tc_sig & TASK_CONNECTION_SIG_FGHOST); } else { wake_ok = false; } } assert(TASK_CONNECTION_GETSIG(primary) == self); next_con = primary->tc_next; last_con = primary->tc_last; COMPILER_READ_BARRIER(); primary->tc_pself = NULL; assert(TASK_CONNECTION_GETSIG(primary) == self); COMPILER_WRITE_BARRIER(); assertf((last_con == primary) == (next_con == NULL), "last_con = %p\n" "con = %p\n" "next_con = %p\n", last_con,primary,next_con); if (!next_con) { ATOMIC_WRITE(self->s_ptr,unlock ? 0 : SIG_FLOCKBIT); } else { assert(TASK_CONNECTION_GETSIG(next_con) == self); assert(next_con->tc_pself == &primary->tc_next); next_con->tc_last = last_con; COMPILER_WRITE_BARRIER(); if (!unlock) *(uintptr_t *)&next_con |= SIG_FLOCKBIT; ATOMIC_WRITE(self->s_ptr,(uintptr_t)next_con); } if unlikely(!wake_ok) { if (unlock) sig_get(self); goto again; } return true; } PUBLIC ATTR_NOTHROW size_t KCALL sig_altsend(struct sig *__restrict self, struct sig *sender, size_t max_threads) { size_t result = 0; if (!ATOMIC_READ(self->s_ptr)) goto done; while (result < max_threads) { bool altsend_ok; sig_get(self); altsend_ok = sig_altsendone_locked(self,sender,true); if (!altsend_ok) break; ++result; } done: return result; } PUBLIC ATTR_NOTHROW size_t KCALL sig_altbroadcast(struct sig *__restrict self, struct sig *sender) { size_t result = 0; if (!ATOMIC_READ(self->s_ptr)) goto done; for (;;) { bool altsend_ok; sig_get(self); altsend_ok = sig_altsendone_locked(self,sender,true); if (!altsend_ok) break; ++result; } done: return result; } PUBLIC ATTR_NOTHROW size_t KCALL sig_altsend_locked(struct sig *__restrict self, struct sig *sender, size_t max_threads) { size_t result = 0; while (result < max_threads && sig_altsendone_locked(self,sender,false)) ++result; return result; } PUBLIC ATTR_NOTHROW size_t KCALL sig_altbroadcast_locked(struct sig *__restrict self, struct sig *sender) { size_t result = 0; while (sig_altsendone_locked(self,sender,false)) ++result; return result; } /* Channel-based signal delivery. */ PRIVATE ATTR_NOTHROW bool KCALL sig_altsendone_channel_locked(struct sig *__restrict self, struct sig *sender, uintptr_t signal_mask, bool unlock) { struct task_connection *primary,*target; struct task_connection *next_con,*last_con; struct task_connections *cons; bool wake_ok = false; assert(sig_holding(self)); again: primary = SIG_GETCON(self); if (!primary) { stop_altsending: if (unlock) sig_put(self); return false; } target = primary; for (;;) { assert(TASK_CONNECTION_GETSIG(target) == self); cons = target->tc_conn; if ((cons->tcs_chn & signal_mask) != 0) break; target = target->tc_next; if (!target) goto stop_altsending; } if likely(ATOMIC_CMPXCH(cons->tcs_sig,NULL,sender)) { if likely(cons == &FORTASK(cons->tcs_tsk,my_connections)) { wake_ok = task_wake(cons->tcs_tsk); if (wake_ok) wake_ok = !((uintptr_t)primary->tc_sig & TASK_CONNECTION_SIG_FGHOST); } else { wake_ok = false; } } assert(TASK_CONNECTION_GETSIG(target) == self); if (target == primary) { next_con = primary->tc_next; last_con = primary->tc_last; COMPILER_READ_BARRIER(); primary->tc_pself = NULL; assert(TASK_CONNECTION_GETSIG(primary) == self); COMPILER_WRITE_BARRIER(); assertf((last_con == primary) == (next_con == NULL), "last_con = %p\n" "con = %p\n" "next_con = %p\n", last_con,primary,next_con); if (!next_con) { ATOMIC_WRITE(self->s_ptr,unlock ? 0 : SIG_FLOCKBIT); } else { assert(TASK_CONNECTION_GETSIG(next_con) == self); assert(next_con->tc_pself == &primary->tc_next); next_con->tc_last = last_con; COMPILER_WRITE_BARRIER(); if (!unlock) *(uintptr_t *)&next_con |= SIG_FLOCKBIT; ATOMIC_WRITE(self->s_ptr,(uintptr_t)next_con); } } else { if ((*target->tc_pself = target->tc_next) != NULL) { assert(primary->tc_last != target); assert(target->tc_next->tc_pself == &target->tc_next); target->tc_next->tc_pself = target->tc_pself; } else { assert(primary->tc_last == target); primary->tc_last = COMPILER_CONTAINER_OF(target->tc_pself, struct task_connection, tc_next); } COMPILER_WRITE_BARRIER(); target->tc_pself = NULL; COMPILER_WRITE_BARRIER(); if (unlock) sig_put(self); } if unlikely(!wake_ok) { if (unlock) sig_get(self); goto again; } return true; } PUBLIC ATTR_NOTHROW size_t KCALL sig_altsend_channel(struct sig *__restrict self, struct sig *sender, uintptr_t signal_mask, size_t max_threads) { size_t result = 0; if (!ATOMIC_READ(self->s_ptr)) goto done; while (result < max_threads) { bool altsend_ok; sig_get(self); altsend_ok = sig_altsendone_channel_locked(self,sender,signal_mask,true); if (!altsend_ok) break; ++result; } done: return result; } PUBLIC ATTR_NOTHROW size_t KCALL sig_altbroadcast_channel(struct sig *__restrict self, struct sig *sender, uintptr_t signal_mask) { size_t result = 0; if (!ATOMIC_READ(self->s_ptr)) goto done; for (;;) { bool altsend_ok; sig_get(self); altsend_ok = sig_altsendone_channel_locked(self,sender,signal_mask,true); if (!altsend_ok) break; ++result; } done: return result; } PUBLIC ATTR_NOTHROW size_t KCALL sig_altsend_channel_locked(struct sig *__restrict self, struct sig *sender, uintptr_t signal_mask, size_t max_threads) { size_t result = 0; while (result < max_threads && sig_altsendone_channel_locked(self,sender,signal_mask,false)) ++result; return result; } PUBLIC ATTR_NOTHROW size_t KCALL sig_altbroadcast_channel_locked(struct sig *__restrict self, struct sig *sender, uintptr_t signal_mask) { size_t result = 0; while (sig_altsendone_channel_locked(self,sender,signal_mask,false)) ++result; return result; } PUBLIC ATTR_NOTHROW uintptr_t KCALL task_channelmask(uintptr_t mask) { /* Simply set the channel mask. */ assertf(!PERTASK_GET(my_connections.tcs_cnt) || PERTASK_GET(my_connections.tcs_chn) == mask, "You may not change the channel mask after already being connected"); return ATOMIC_XCH(PERTASK(my_connections.tcs_chn),mask); } PUBLIC ATTR_NOTHROW uintptr_t KCALL task_openchannel(uintptr_t mask) { /* Simply open more channels. */ return ATOMIC_FETCHOR(PERTASK(my_connections.tcs_chn),mask); } /* TODO: Implement these for real (Using `task_wake_p()') */ DEFINE_PUBLIC_ALIAS(sig_send_p,sig_send); DEFINE_PUBLIC_ALIAS(sig_broadcast_p,sig_broadcast); DEFINE_PUBLIC_ALIAS(sig_send_locked_p,sig_send_locked); DEFINE_PUBLIC_ALIAS(sig_broadcast_locked_p,sig_broadcast_locked); DEFINE_PUBLIC_ALIAS(sig_send_channel_p,sig_send_channel); DEFINE_PUBLIC_ALIAS(sig_broadcast_channel_p,sig_broadcast_channel); DEFINE_PUBLIC_ALIAS(sig_send_channel_locked_p,sig_send_channel_locked); DEFINE_PUBLIC_ALIAS(sig_broadcast_channel_locked_p,sig_broadcast_channel_locked); DEFINE_PUBLIC_ALIAS(sig_altsend_p,sig_altsend); DEFINE_PUBLIC_ALIAS(sig_altbroadcast_p,sig_altbroadcast); DEFINE_PUBLIC_ALIAS(sig_altsend_locked_p,sig_altsend_locked); DEFINE_PUBLIC_ALIAS(sig_altbroadcast_locked_p,sig_altbroadcast_locked); DEFINE_PUBLIC_ALIAS(sig_altsend_channel_p,sig_altsend_channel); DEFINE_PUBLIC_ALIAS(sig_altbroadcast_channel_p,sig_altbroadcast_channel); DEFINE_PUBLIC_ALIAS(sig_altsend_channel_locked_p,sig_altsend_channel_locked); DEFINE_PUBLIC_ALIAS(sig_altbroadcast_channel_locked_p,sig_altbroadcast_channel_locked); PUBLIC struct sig *KCALL task_waitfor_tmrel(USER CHECKED struct timespec const *rel_timeout) { qtime_t qtimeout,abs_timeout; /* Figure out the relative timeout as a quantum time. */ qtimeout.qt_jiffies = jiffies_from_timespec(*rel_timeout); qtimeout.qt_qoffset = rel_timeout->tv_nsec % (1000000000ul / JIFFIES_PER_SECOND); qtimeout.qt_qlength = 1000000000ul / JIFFIES_PER_SECOND; /* Add the current quantum time to the timeout. */ abs_timeout = qtime_now(); abs_timeout.qt_jiffies += qtimeout.qt_jiffies; abs_timeout.qt_qoffset += (u32)((((u64)qtimeout.qt_qoffset * abs_timeout.qt_qlength) + ((u64)qtimeout.qt_qlength / 2)) / qtimeout.qt_qlength); while (abs_timeout.qt_qoffset > abs_timeout.qt_qlength) { ++abs_timeout.qt_jiffies; abs_timeout.qt_qoffset -= abs_timeout.qt_qlength; } return task_qwaitfor(abs_timeout); } PUBLIC struct sig *KCALL task_waitfor_tmabs(USER CHECKED struct timespec const *abs_timeout) { struct timespec diff = *abs_timeout; struct timespec wall = wall_gettime(&wall_kernel); if (TIMESPEC_LOWER(diff,wall)) return task_disconnect(); TIMESPEC_SUB(diff,wall); return task_waitfor_tmrel(&diff); } DECL_END #endif /* !GUARD_KERNEL_SRC_SCHED_SIGNAL_C */
32.059233
96
0.671753
[ "vector" ]
c5b143fe97109e22bf415708d2551403d6afb9ee
1,157
h
C
src/System/Networking.h
GPikra/python-smpc-wrapper-importer
43a8945e63f7c8996da699dae0a9f9240084214f
[ "BSD-2-Clause" ]
3
2019-08-10T10:03:15.000Z
2020-05-20T03:53:40.000Z
src/System/Networking.h
GPikra/python-smpc-wrapper-importer
43a8945e63f7c8996da699dae0a9f9240084214f
[ "BSD-2-Clause" ]
6
2019-06-10T13:20:34.000Z
2019-07-10T17:28:52.000Z
src/System/Networking.h
athenarc/SCALE-MAMBA
18fa886d820bec7e441448357b8f09e2be0e7c9e
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) 2017, The University of Bristol, Senate House, Tyndall Avenue, Bristol, BS8 1TH, United Kingdom. Copyright (c) 2018, COSIC-KU Leuven, Kasteelpark Arenberg 10, bus 2452, B-3001 Leuven-Heverlee, Belgium. All rights reserved */ #ifndef _Networking #define _Networking #include "SystemData.h" /* Create the server socket and intialize the socket address structure * max is the max number of connections to expect */ int OpenListener(int port, int max= 1); /* Connect for the client */ int OpenConnection(const string &hostname, int port); /* This gets nthreads connections between SD.n players * Returns the *connection* socket information in csocket[thread][player][connection] * The variable ssocket contains the server socket number. * The server portnum for each player is in the vector portnum */ void Get_Connections(int &ssocket, vector<vector<vector<int>>> &csocket, const vector<unsigned int> &portnum, unsigned int me, const SystemData &SD, int verbose); void Close_Connections(int ssocket, vector<vector<vector<int>>> &csocket, unsigned int me); #endif
35.060606
110
0.72083
[ "vector" ]
c5b1a461275efb14c228c9cb73b3f3bb889203a3
6,766
h
C
geo3d/include/CGAL/Minkowski_sum_2/AABB_traits_2.h
vipuserr/vipuserr-Geological-hazard
2b29c03cdac6f5e1ceac4cd2f15b594040ef909c
[ "MIT" ]
187
2019-01-23T04:07:11.000Z
2022-03-27T03:44:58.000Z
ext/libigl/external/cgal/src/CGAL_Project/include/CGAL/Minkowski_sum_2/AABB_traits_2.h
xiaoxie5002/OptCuts
1f4168fc867f47face85fcfa3a572be98232786f
[ "MIT" ]
8
2019-03-22T13:27:38.000Z
2020-06-18T13:23:23.000Z
ext/libigl/external/cgal/src/CGAL_Project/include/CGAL/Minkowski_sum_2/AABB_traits_2.h
xiaoxie5002/OptCuts
1f4168fc867f47face85fcfa3a572be98232786f
[ "MIT" ]
34
2019-02-13T01:11:12.000Z
2022-02-28T03:29:40.000Z
// Copyright (c) 2015 Tel-Aviv University (Israel). // All rights reserved. // // This file is part of CGAL (www.cgal.org). // You can redistribute it and/or modify it under the terms of the GNU // General Public License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. // // Licensees holding a valid commercial license may use this file in // accordance with the commercial license agreement provided with the software. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // // Author(s): Sebastian Morr <sebastian@morr.cc> #ifndef CGAL_AABB_TRAITS_2_H #define CGAL_AABB_TRAITS_2_H #include <CGAL/license/Minkowski_sum_2.h> namespace CGAL { template<typename GeomTraits, typename AABB_primitive_> class AABB_traits_2 { public: typedef AABB_primitive_ Primitive; typedef typename Primitive::Id Id; typedef typename Primitive::Datum Datum; typedef typename Primitive::Container Container; typedef typename GeomTraits::Point_2 Point; typedef typename GeomTraits::Vector_2 Vector_2; typedef typename CGAL::Bbox_2 Bounding_box; typedef typename std::pair<Object, Id> Object_and_primitive_id; typedef typename std::pair<Point, Id> Point_and_primitive_id; // Types for AABB_tree typedef typename GeomTraits::FT FT; typedef typename GeomTraits::Point_2 Point_3; typedef typename GeomTraits::Circle_2 Sphere_3; typedef typename GeomTraits::Iso_rectangle_2 Iso_cuboid_3; typedef typename GeomTraits::Construct_center_2 Construct_center_3; typedef typename GeomTraits::Construct_iso_rectangle_2 Construct_iso_cuboid_3; typedef typename GeomTraits::Construct_min_vertex_2 Construct_min_vertex_3; typedef typename GeomTraits::Construct_max_vertex_2 Construct_max_vertex_3; typedef typename GeomTraits::Compute_squared_radius_2 Compute_squared_radius_3; typedef typename GeomTraits::Cartesian_const_iterator_2 Cartesian_const_iterator_3; typedef typename GeomTraits::Construct_cartesian_const_iterator_2 Construct_cartesian_const_iterator_3; AABB_traits_2(const Point &translation_point): m_translation_point( translation_point) { m_interval_x = Interval_nt<true>(to_interval(translation_point.x())); m_interval_y = Interval_nt<true>(to_interval(translation_point.y())); }; AABB_traits_2() { m_translation_point = Point(0, 0); m_interval_x = Interval_nt<true>(0); m_interval_y = Interval_nt<true>(0); }; Interval_nt<true> get_interval_x() const { return m_interval_x; } Interval_nt<true> get_interval_y() const { return m_interval_y; } Point get_translation_point() const { return m_translation_point; } // Put the n/2 smallest primitives in the front, the n/2 largest primitives // in the back. They are compared along the bbox' longest axis. class Sort_primitives { public: template<typename PrimitiveIterator> void operator()(PrimitiveIterator first, PrimitiveIterator beyond, const Bounding_box &bbox) const { PrimitiveIterator middle = first + (beyond - first) / 2; if (bbox.xmax()-bbox.xmin() >= bbox.ymax()-bbox.ymin()) { std::nth_element(first, middle, beyond, less_x); // sort along x } else { std::nth_element(first, middle, beyond, less_y); // sort along y } } }; Sort_primitives sort_primitives_object() const { return Sort_primitives(); } // Computes the bounding box of a set of primitives class Compute_bbox { public: template<typename ConstPrimitiveIterator> Bounding_box operator()(ConstPrimitiveIterator first, ConstPrimitiveIterator beyond) const { Bounding_box bbox = first->datum().bbox(); for (++first; first != beyond; ++first) { bbox = bbox + first->datum().bbox(); } return bbox; } }; Compute_bbox compute_bbox_object() const { return Compute_bbox(); } class Do_intersect { private: AABB_traits_2 *m_traits; public: Do_intersect(AABB_traits_2 *_traits): m_traits(_traits) {} bool operator()(const Bounding_box &q, const Bounding_box &bbox) const { Interval_nt<true> x1 = Interval_nt<true>(q.xmin(), q.xmax()); Interval_nt<true> y1 = Interval_nt<true>(q.ymin(), q.ymax()); Interval_nt<true> x2 = Interval_nt<true>(bbox.xmin(), bbox.xmax()) + m_traits->get_interval_x(); Interval_nt<true> y2 = Interval_nt<true>(bbox.ymin(), bbox.ymax()) + m_traits->get_interval_y(); return x1.do_overlap(x2) && y1.do_overlap(y2); } bool operator()(const Primitive &q, const Bounding_box &bbox) const { Interval_nt<true> x1 = Interval_nt<true>(q.datum().bbox().xmin(), q.datum().bbox().xmax()); Interval_nt<true> y1 = Interval_nt<true>(q.datum().bbox().ymin(), q.datum().bbox().ymax()); Interval_nt<true> x2 = Interval_nt<true>(bbox.xmin(), bbox.xmax()) + m_traits->get_interval_x(); Interval_nt<true> y2 = Interval_nt<true>(bbox.ymin(), bbox.ymax()) + m_traits->get_interval_y(); return x1.do_overlap(x2) && y1.do_overlap(y2); } bool operator()(const Bounding_box &q, const Primitive &pr) const { Datum tr_pr = pr.datum().transform(typename GeomTraits::Aff_transformation_2( Translation(), Vector_2(ORIGIN, m_traits->get_translation_point()))); return do_overlap(q, tr_pr.bbox()); } bool operator()(const Primitive &q, const Primitive &pr) const { Datum tr_pr = pr.datum().transform(typename GeomTraits::Aff_transformation_2( Translation(), Vector_2(ORIGIN, m_traits->get_translation_point()))); if (!do_overlap(q.datum().bbox(), tr_pr.bbox())) { return false; } return do_intersect(q.datum(), tr_pr); } }; Do_intersect do_intersect_object() { return Do_intersect(this); } private: Point m_translation_point; Interval_nt<true> m_interval_x; Interval_nt<true> m_interval_y; // Comparison functions static bool less_x(const Primitive &pr1, const Primitive &pr2) { return pr1.reference_point().x() < pr2.reference_point().x(); } static bool less_y(const Primitive &pr1, const Primitive &pr2) { return pr1.reference_point().y() < pr2.reference_point().y(); } }; } // namespace CGAL #endif
30.071111
110
0.672184
[ "object", "transform" ]
c5b1f16956b989ac02797b720f26c9c2ed6b2ad5
80,783
c
C
Source/WinObjEx64/kldbg.c
ALEHACKsp/WinObjEx64
05988cf65d178f6b8845b58fdc2ae203bd2a8767
[ "BSD-2-Clause" ]
null
null
null
Source/WinObjEx64/kldbg.c
ALEHACKsp/WinObjEx64
05988cf65d178f6b8845b58fdc2ae203bd2a8767
[ "BSD-2-Clause" ]
null
null
null
Source/WinObjEx64/kldbg.c
ALEHACKsp/WinObjEx64
05988cf65d178f6b8845b58fdc2ae203bd2a8767
[ "BSD-2-Clause" ]
1
2019-12-25T17:04:57.000Z
2019-12-25T17:04:57.000Z
/******************************************************************************* * * (C) COPYRIGHT AUTHORS, 2015 - 2019 * * TITLE: KLDBG.C, based on KDSubmarine by Evilcry * * VERSION: 1.82 * * DATE: 24 Nov 2019 * * MINIMUM SUPPORTED OS WINDOWS 7 * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF * ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A * PARTICULAR PURPOSE. * *******************************************************************************/ #include "global.h" #include "hde\hde64.h" #include "kldbg_patterns.h" // // Global variables, declared as extern in kldbg.h // //Context KLDBGCONTEXT g_kdctx; //Build number ULONG g_NtBuildNumber; //Callbacks NOTIFICATION_CALLBACKS g_SystemCallbacks; #define MM_SYSTEM_RANGE_START_7 0xFFFF080000000000 #define MM_SYSTEM_RANGE_START_8 0xFFFF800000000000 #define TEXT_SECTION ".text" #define TEXT_SECTION_LEGNTH sizeof(TEXT_SECTION) #define PAGE_SECTION "PAGE" #define PAGE_SECTION_LEGNTH sizeof(PAGE_SECTION) UCHAR ObpInfoMaskToOffset[0x100]; /* * ObpInitInfoBlockOffsets * * Purpose: * * Initialize block offfsets table for working with OBJECT_HEADER data. * * Note: * * ObpInfoMaskToOffset size depends on Windows version (Win7 = 64, Win10 = 256) * * 9200 (Windows 8 Blue) * OBJECT_HEADER_AUDIT_INFO added * * 10586 (Windows 10 TH2) * OBJECT_HEADER_HANDLE_REVOCATION_INFO added (size in ObpInitInfoBlockOffsets = 32) * * 14393 (Windows 10 RS1) * OBJECT_HEADER_EXTENDED_INFO added and replaced OBJECT_HEADER_HANDLE_REVOCATION_INFO in ObpInitInfoBlockOffsets * size = 16 * * HANDLE_REVOCATION_INFO moved to OBJECT_FOOTER which is a part of OBJECT_HEADER_EXTENDED_INFO as pointer. * */ VOID ObpInitInfoBlockOffsets() { UCHAR *p = ObpInfoMaskToOffset; UINT i; UCHAR c; i = 0; do { c = 0; if (i & 1) c += sizeof(OBJECT_HEADER_CREATOR_INFO); if (i & 2) c += sizeof(OBJECT_HEADER_NAME_INFO); if (i & 4) c += sizeof(OBJECT_HEADER_HANDLE_INFO); if (i & 8) c += sizeof(OBJECT_HEADER_QUOTA_INFO); if (i & 0x10) c += sizeof(OBJECT_HEADER_PROCESS_INFO); if (i & 0x20) { // Padding? if (g_NtBuildNumber < 9200) { c += sizeof(OBJECT_HEADER_PADDING_INFO); } else { c += sizeof(OBJECT_HEADER_AUDIT_INFO); } } //OBJECT_HEADER_EXTENDED_INFO (OBJECT_HEADER_HANDLE_REVOCATION_INFO in 10586) if (i & 0x40) { if (g_NtBuildNumber == 10586) c += sizeof(OBJECT_HEADER_HANDLE_REVOCATION_INFO); else c += sizeof(OBJECT_HEADER_EXTENDED_INFO); } if (i & 0x80) c += sizeof(OBJECT_HEADER_PADDING_INFO); p[i] = c; i++; } while (i < 256); return; } /* * ObGetObjectHeaderOffsetEx * * Purpose: * * Query requested structure offset for the given mask * */ BYTE ObGetObjectHeaderOffsetEx( _In_ BYTE InfoMask, _In_ BYTE DesiredHeaderBit ) { return ObpInfoMaskToOffset[InfoMask & (DesiredHeaderBit | (DesiredHeaderBit - 1))]; } /* * ObHeaderToNameInfoAddressEx * * Purpose: * * Calculate address of name structure from object header flags and object address using ObpInfoMaskToOffset. * */ BOOL ObHeaderToNameInfoAddressEx( _In_ UCHAR ObjectInfoMask, _In_ ULONG_PTR ObjectAddress, _Inout_ PULONG_PTR HeaderAddress, _In_ BYTE DesiredHeaderBit ) { BYTE HeaderOffset; ULONG_PTR Address; if (HeaderAddress == NULL) return FALSE; if (ObjectAddress < g_kdctx.SystemRangeStart) return FALSE; HeaderOffset = ObGetObjectHeaderOffsetEx(ObjectInfoMask, DesiredHeaderBit); if (HeaderOffset == 0) return FALSE; Address = ObjectAddress - HeaderOffset; if (Address < g_kdctx.SystemRangeStart) return FALSE; *HeaderAddress = Address; return TRUE; } /* * ObGetObjectHeaderOffset * * Purpose: * * Query requested structure offset for the given mask * * * Object In Memory Disposition (Obsolete, see ObpInitInfoBlockOffsets comments) * * POOL_HEADER * OBJECT_HEADER_PROCESS_INFO * OBJECT_HEADER_QUOTA_INFO * OBJECT_HEADER_HANDLE_INFO * OBJECT_HEADER_NAME_INFO * OBJECT_HEADER_CREATOR_INFO * OBJECT_HEADER * */ BYTE ObGetObjectHeaderOffset( _In_ BYTE InfoMask, _In_ OBJ_HEADER_INFO_FLAG Flag ) { BYTE OffsetMask, HeaderOffset = 0; if ((InfoMask & Flag) == 0) return 0; OffsetMask = InfoMask & (Flag | (Flag - 1)); if ((OffsetMask & HeaderCreatorInfoFlag) != 0) HeaderOffset += (BYTE)sizeof(OBJECT_HEADER_CREATOR_INFO); if ((OffsetMask & HeaderNameInfoFlag) != 0) HeaderOffset += (BYTE)sizeof(OBJECT_HEADER_NAME_INFO); if ((OffsetMask & HeaderHandleInfoFlag) != 0) HeaderOffset += (BYTE)sizeof(OBJECT_HEADER_HANDLE_INFO); if ((OffsetMask & HeaderQuotaInfoFlag) != 0) HeaderOffset += (BYTE)sizeof(OBJECT_HEADER_QUOTA_INFO); if ((OffsetMask & HeaderProcessInfoFlag) != 0) HeaderOffset += (BYTE)sizeof(OBJECT_HEADER_PROCESS_INFO); return HeaderOffset; } /* * ObHeaderToNameInfoAddress * * Purpose: * * Calculate address of name structure from object header flags and object address * */ BOOL ObHeaderToNameInfoAddress( _In_ UCHAR ObjectInfoMask, _In_ ULONG_PTR ObjectAddress, _Inout_ PULONG_PTR HeaderAddress, _In_ OBJ_HEADER_INFO_FLAG InfoFlag ) { BYTE HeaderOffset; ULONG_PTR Address; if (HeaderAddress == NULL) return FALSE; if (ObjectAddress < g_kdctx.SystemRangeStart) return FALSE; HeaderOffset = ObGetObjectHeaderOffset(ObjectInfoMask, InfoFlag); if (HeaderOffset == 0) return FALSE; Address = ObjectAddress - HeaderOffset; if (Address < g_kdctx.SystemRangeStart) return FALSE; *HeaderAddress = Address; return TRUE; } /* * ObCopyBoundaryDescriptor * * Purpose: * * Copy boundary descriptor from kernel to user. * Use supHeapFree to free allocated buffer. * */ NTSTATUS ObCopyBoundaryDescriptor( _In_ OBJECT_NAMESPACE_ENTRY *NamespaceLookupEntry, _Out_ POBJECT_BOUNDARY_DESCRIPTOR *BoundaryDescriptor, _Out_opt_ PULONG BoundaryDescriptorSize ) { ULONG TotalSize; ULONG_PTR BoundaryDescriptorAddress; OBJECT_BOUNDARY_DESCRIPTOR BoundaryDescriptorHeader, *CopyDescriptor; *BoundaryDescriptor = NULL; BoundaryDescriptorAddress = (ULONG_PTR)RtlOffsetToPointer( NamespaceLookupEntry, sizeof(OBJECT_NAMESPACE_ENTRY)); if (BoundaryDescriptorAddress < g_kdctx.SystemRangeStart) return STATUS_INVALID_PARAMETER; RtlSecureZeroMemory(&BoundaryDescriptorHeader, sizeof(BoundaryDescriptorHeader)); // // Read header. // if (!kdReadSystemMemoryEx(BoundaryDescriptorAddress, &BoundaryDescriptorHeader, sizeof(OBJECT_BOUNDARY_DESCRIPTOR), NULL)) { return STATUS_DEVICE_NOT_READY; } if (BoundaryDescriptorSize) *BoundaryDescriptorSize = 0; // // Validate header data. // TotalSize = BoundaryDescriptorHeader.TotalSize; if (TotalSize < sizeof(OBJECT_BOUNDARY_DESCRIPTOR)) return STATUS_INVALID_PARAMETER; if (BoundaryDescriptorHeader.Version != 1) return STATUS_UNKNOWN_REVISION; if ((BoundaryDescriptorAddress + TotalSize) < BoundaryDescriptorAddress) return STATUS_INVALID_PARAMETER; // // Dump entire boundary descriptor. // CopyDescriptor = (OBJECT_BOUNDARY_DESCRIPTOR*)supHeapAlloc(TotalSize); if (CopyDescriptor == NULL) return STATUS_MEMORY_NOT_ALLOCATED; if (kdReadSystemMemoryEx(BoundaryDescriptorAddress, CopyDescriptor, TotalSize, NULL)) { *BoundaryDescriptor = CopyDescriptor; if (BoundaryDescriptorSize) *BoundaryDescriptorSize = TotalSize; } else { supHeapFree(CopyDescriptor); return STATUS_DEVICE_NOT_READY; } return STATUS_SUCCESS; } /* * ObpValidateSidBuffer * * Purpose: * * Check if given SID is valid. * */ BOOLEAN ObpValidateSidBuffer( PSID Sid, SIZE_T BufferSize ) { PUCHAR Count; if (BufferSize < RtlLengthRequiredSid(0)) return FALSE; Count = RtlSubAuthorityCountSid(Sid); if (BufferSize < RtlLengthRequiredSid(*Count)) return FALSE; return RtlValidSid(Sid); } /* * ObEnumerateBoundaryDescriptorEntries * * Purpose: * * Walk each boundary descriptor entry, validate it and run optional callback. * */ NTSTATUS ObEnumerateBoundaryDescriptorEntries( _In_ OBJECT_BOUNDARY_DESCRIPTOR *BoundaryDescriptor, _In_opt_ PENUMERATE_BOUNDARY_DESCRIPTOR_CALLBACK Callback, _In_opt_ PVOID Context ) { ULONG EntrySize, TotalItems = 0, NameEntries = 0, IntegrityLabelEntries = 0; ULONG BoundaryDescriptorItems = 0; ULONG_PTR DataEnd; OBJECT_BOUNDARY_ENTRY *CurrentEntry, *NextEntry; __try { if (BoundaryDescriptor->TotalSize < sizeof(OBJECT_BOUNDARY_DESCRIPTOR)) return STATUS_INVALID_PARAMETER; if (BoundaryDescriptor->Version != 1) return STATUS_INVALID_PARAMETER; DataEnd = (ULONG_PTR)RtlOffsetToPointer(BoundaryDescriptor, BoundaryDescriptor->TotalSize); if (DataEnd < (ULONG_PTR)BoundaryDescriptor) return STATUS_INVALID_PARAMETER; CurrentEntry = (OBJECT_BOUNDARY_ENTRY*)RtlOffsetToPointer(BoundaryDescriptor, sizeof(OBJECT_BOUNDARY_DESCRIPTOR)); BoundaryDescriptorItems = BoundaryDescriptor->Items; } __except (EXCEPTION_EXECUTE_HANDLER) { return GetExceptionCode(); } do { __try { EntrySize = CurrentEntry->EntrySize; if (EntrySize < sizeof(OBJECT_BOUNDARY_ENTRY)) return STATUS_INVALID_PARAMETER; TotalItems++; NextEntry = (OBJECT_BOUNDARY_ENTRY*)ALIGN_UP(((PBYTE)CurrentEntry + EntrySize), ULONG_PTR); if ((NextEntry < CurrentEntry) || ((ULONG_PTR)NextEntry > DataEnd)) return STATUS_INVALID_PARAMETER; if (CurrentEntry->EntryType == OBNS_Name) { if (++NameEntries > 1) return STATUS_DUPLICATE_NAME; } else if (CurrentEntry->EntryType == OBNS_SID) { if (!ObpValidateSidBuffer( (PSID)((PBYTE)CurrentEntry + sizeof(OBJECT_BOUNDARY_ENTRY)), EntrySize - sizeof(OBJECT_BOUNDARY_ENTRY))) { return STATUS_INVALID_PARAMETER; } } else if (CurrentEntry->EntryType == OBNS_IntegrityLabel) { if (++IntegrityLabelEntries > 1) return STATUS_DUPLICATE_OBJECTID; } } __except (EXCEPTION_EXECUTE_HANDLER) { return GetExceptionCode(); } if (Callback) { if (Callback(CurrentEntry, Context)) return STATUS_SUCCESS; } CurrentEntry = NextEntry; } while ((ULONG_PTR)CurrentEntry < (ULONG_PTR)DataEnd); return (TotalItems != BoundaryDescriptorItems) ? STATUS_INVALID_PARAMETER : STATUS_SUCCESS; } /* * ObpDumpObjectWithSpecifiedSize * * Purpose: * * Return dumped object version aware. * * Use supVirtualFree to free returned buffer. * */ _Success_(return != NULL) PVOID ObpDumpObjectWithSpecifiedSize( _In_ ULONG_PTR ObjectAddress, _In_ ULONG ObjectSize, _In_ ULONG ObjectVersion, _Out_ PULONG ReadSize, _Out_ PULONG ReadVersion ) { PVOID ObjectBuffer = NULL; ULONG BufferSize = ALIGN_UP_BY(ObjectSize, PAGE_SIZE); ObjectBuffer = supVirtualAlloc(BufferSize); if (ObjectBuffer == NULL) { return NULL; } if (!kdReadSystemMemory( ObjectAddress, ObjectBuffer, (ULONG)ObjectSize)) { supVirtualFree(ObjectBuffer); return NULL; } if (ReadSize) *ReadSize = ObjectSize; if (ReadVersion) *ReadVersion = ObjectVersion; return ObjectBuffer; } /* * ObDumpObjectTypeVersionAware * * Purpose: * * Return dumped OBJECT_TYPE object version aware. * * Use supVirtualFree to free returned buffer. * */ PVOID ObDumpObjectTypeVersionAware( _In_ ULONG_PTR ObjectAddress, _Out_ PULONG Size, _Out_ PULONG Version ) { ULONG ObjectSize = 0; ULONG ObjectVersion = 0; //assume failure if (Size) *Size = 0; if (Version) *Version = 0; switch (g_NtBuildNumber) { case 7600: case 7601: ObjectSize = sizeof(OBJECT_TYPE_7); ObjectVersion = 1; break; case 9200: case 9600: case 10240: case 10586: ObjectSize = sizeof(OBJECT_TYPE_8); ObjectVersion = 2; break; case 14393: ObjectSize = sizeof(OBJECT_TYPE_RS1); ObjectVersion = 3; break; default: ObjectSize = sizeof(OBJECT_TYPE_RS2); ObjectVersion = 4; break; } return ObpDumpObjectWithSpecifiedSize(ObjectAddress, ObjectSize, ObjectVersion, Size, Version); } /* * ObDumpAlpcPortObjectVersionAware * * Purpose: * * Return dumped ALPC_PORT object version aware. * * Use supVirtualFree to free returned buffer. * */ PVOID ObDumpAlpcPortObjectVersionAware( _In_ ULONG_PTR ObjectAddress, _Out_ PULONG Size, _Out_ PULONG Version ) { ULONG ObjectSize = 0; ULONG ObjectVersion = 0; //assume failure if (Size) *Size = 0; if (Version) *Version = 0; switch (g_NtBuildNumber) { case 7600: case 7601: ObjectSize = sizeof(ALPC_PORT_7600); ObjectVersion = 1; break; case 9200: ObjectSize = sizeof(ALPC_PORT_9200); ObjectVersion = 2; break; case 9600: ObjectSize = sizeof(ALPC_PORT_9600); ObjectVersion = 3; break; default: ObjectSize = sizeof(ALPC_PORT_10240); ObjectVersion = 4; break; } return ObpDumpObjectWithSpecifiedSize(ObjectAddress, ObjectSize, ObjectVersion, Size, Version); } /* * ObxDumpDirectoryObjectVersionAware * * Purpose: * * Return dumped OBJECT_DIRECTORY object version aware. * * Use supVirtualFree to free returned buffer. * * Note: Currently unused. * */ PVOID ObxDumpDirectoryObjectVersionAware( _In_ ULONG_PTR ObjectAddress, _Out_ PULONG Size, _Out_ PULONG Version ) { ULONG ObjectVersion; ULONG ObjectSize = 0; //assume failure if (Size) *Size = 0; if (Version) *Version = 0; switch (g_NtBuildNumber) { case 7600: case 7601: case 9200: case 9600: ObjectVersion = 1; ObjectSize = sizeof(OBJECT_DIRECTORY); break; case 10240: case 10586: case 14393: ObjectVersion = 2; ObjectSize = sizeof(OBJECT_DIRECTORY_V2); break; default: ObjectVersion = 3; ObjectSize = sizeof(OBJECT_DIRECTORY_V3); break; } return ObpDumpObjectWithSpecifiedSize(ObjectAddress, ObjectSize, ObjectVersion, Size, Version); } /* * ObDumpSymbolicLinkObjectVersionAware * * Purpose: * * Return dumped OBJEC_SYMBOLIC_LINK object version aware. * * Use supVirtualFree to free returned buffer. * */ PVOID ObDumpSymbolicLinkObjectVersionAware( _In_ ULONG_PTR ObjectAddress, _Out_ PULONG Size, _Out_ PULONG Version ) { ULONG ObjectSize = 0; ULONG ObjectVersion = 0; //assume failure if (Size) *Size = 0; if (Version) *Version = 0; switch (g_NtBuildNumber) { case 7600: case 7601: case 9200: case 9600: ObjectSize = sizeof(OBJECT_SYMBOLIC_LINK_V1); ObjectVersion = 1; break; case 10240: case 10586: ObjectSize = sizeof(OBJECT_SYMBOLIC_LINK_V2); ObjectVersion = 2; break; case 14393: ObjectSize = sizeof(OBJECT_SYMBOLIC_LINK_V3); ObjectVersion = 3; break; default: ObjectSize = sizeof(OBJECT_SYMBOLIC_LINK_V4); ObjectVersion = 4; break; } return ObpDumpObjectWithSpecifiedSize(ObjectAddress, ObjectSize, ObjectVersion, Size, Version); } /* * ObDecodeTypeIndex * * Purpose: * * Decode object TypeIndex, encoding introduced in win10 * * Limitation: * * Only for Win10+ use * */ UCHAR ObDecodeTypeIndex( _In_ PVOID Object, _In_ UCHAR EncodedTypeIndex ) { UCHAR TypeIndex; POBJECT_HEADER ObjectHeader; if (g_kdctx.ObHeaderCookie == 0) { return EncodedTypeIndex; } ObjectHeader = OBJECT_TO_OBJECT_HEADER(Object); TypeIndex = (EncodedTypeIndex ^ (UCHAR)((ULONG_PTR)ObjectHeader >> OBJECT_SHIFT) ^ g_kdctx.ObHeaderCookie); return TypeIndex; } /* * ObpFindHeaderCookie * * Purpose: * * Parse ObGetObjectType and extract object header cookie variable address * * Limitation: * * Only for Win10+ use * */ UCHAR ObpFindHeaderCookie( _In_ PKLDBGCONTEXT Context ) { UCHAR ObHeaderCookie = 0; PBYTE ptrCode; ULONG Index; ULONG_PTR Address; LONG Rel = 0; hde64s hs; ULONG_PTR NtOsBase; HMODULE hNtOs; __try { NtOsBase = (ULONG_PTR)Context->NtOsBase; hNtOs = (HMODULE)Context->NtOsImageMap; do { ptrCode = (PBYTE)GetProcAddress(hNtOs, "ObGetObjectType"); if (ptrCode == NULL) { break; } Index = 0; do { hde64_disasm((void*)(ptrCode + Index), &hs); if (hs.flags & F_ERROR) break; if (hs.len == 7) { // // movzx ecx, byte ptr cs:ObHeaderCookie <- // if ((ptrCode[Index] == 0x0F) && (ptrCode[Index + 1] == 0xB6) && (ptrCode[Index + 2] == 0x0D)) { Rel = *(PLONG)(ptrCode + Index + 3); break; } } Index += hs.len; } while (Index < 256); if (Rel == 0) break; Address = (ULONG_PTR)ptrCode + Index + hs.len + Rel; Address = NtOsBase + Address - (ULONG_PTR)hNtOs; if (!kdAddressInNtOsImage((PVOID)Address)) break; if (!kdReadSystemMemoryEx( Address, &ObHeaderCookie, sizeof(ObHeaderCookie), NULL)) { break; } } while (FALSE); } __except (exceptFilter(GetExceptionCode(), GetExceptionInformation())) { return 0; } return ObHeaderCookie; } /* * ObFindPrivateNamespaceLookupTable2 * * Purpose: * * Locate and return address of namespace table. * * Limitation: * * OS dependent, Windows 10 (RS1 - 19H1). * */ PVOID ObFindPrivateNamespaceLookupTable2( _In_ PKLDBGCONTEXT Context ) { ULONG_PTR Address = 0; PVOID SectionBase; ULONG SectionSize; PBYTE Signature; ULONG SignatureSize, Index; LONG Rel = 0; PBYTE ptrCode = NULL, MatchingPattern = NULL; hde64s hs; ESERVERSILO_GLOBALS PspHostSiloGlobals; ULONG_PTR NtOsBase = (ULONG_PTR)Context->NtOsBase; HMODULE hNtOs = (HMODULE)Context->NtOsImageMap; do { // // Locate .text image section. // SectionBase = supLookupImageSectionByName( TEXT_SECTION, TEXT_SECTION_LEGNTH, (PVOID)hNtOs, &SectionSize); if ((SectionBase == 0) || (SectionSize == 0)) break; // // Default code scan pattern. // MatchingPattern = LeaPattern_PNS; // // Locate starting point for search -> // PsGetServerSiloServiceSessionId for RS4+ and PsGetServerSiloGlobals for RS1-RS3. // if (g_NtBuildNumber >= 17134) { ptrCode = (PBYTE)GetProcAddress(hNtOs, "PsGetServerSiloServiceSessionId"); } else { switch (g_NtBuildNumber) { case 14393: SignatureSize = sizeof(PsGetServerSiloGlobalsPattern_14393); Signature = PsGetServerSiloGlobalsPattern_14393; break; case 15063: case 16299: SignatureSize = sizeof(PsGetServerSiloGlobalsPattern_15064_16299); Signature = PsGetServerSiloGlobalsPattern_15064_16299; break; default: SignatureSize = 0; Signature = 0; break; } if ((SignatureSize) && (Signature)) { ptrCode = (PBYTE)supFindPattern( (PBYTE)SectionBase, SectionSize, Signature, SignatureSize); } } if (ptrCode == NULL) break; Index = 0; // // Find reference to PspHostSiloGlobals in code. // do { hde64_disasm((void*)(ptrCode + Index), &hs); if (hs.flags & F_ERROR) break; if (hs.len == 7) { //lea rax, PspHostSiloGlobals if ((ptrCode[Index] == MatchingPattern[0]) && (ptrCode[Index + 1] == MatchingPattern[1]) && (ptrCode[Index + 2] == MatchingPattern[2])) { Rel = *(PLONG)(ptrCode + Index + 3); break; } } Index += hs.len; } while (Index < 64); if (Rel == 0) break; Address = (ULONG_PTR)ptrCode + Index + hs.len + Rel; Address = NtOsBase + Address - (ULONG_PTR)hNtOs; if (!kdAddressInNtOsImage((PVOID)Address)) break; // // Dump PspHostSiloGlobals. // RtlSecureZeroMemory( &PspHostSiloGlobals, sizeof(PspHostSiloGlobals)); if (!kdReadSystemMemoryEx(Address, &PspHostSiloGlobals, sizeof(PspHostSiloGlobals), NULL)) { break; } // // Return adjusted address of PrivateNamespaceLookupTable. // Address += FIELD_OFFSET(OBP_SILODRIVERSTATE, PrivateNamespaceLookupTable); } while (FALSE); return (PVOID)Address; } /* * ObFindPrivateNamespaceLookupTable * * Purpose: * * Locate and return address of private namespace table. * */ PVOID ObFindPrivateNamespaceLookupTable( _In_ PKLDBGCONTEXT Context ) { ULONG Index; PBYTE Signature, MatchingPattern; ULONG SignatureSize; LONG Rel = 0; hde64s hs; ULONG_PTR Address = 0; PBYTE ptrCode = NULL; PVOID SectionBase; ULONG SectionSize; ULONG_PTR NtOsBase = (ULONG_PTR)Context->NtOsBase; HMODULE hNtOs = (HMODULE)Context->NtOsImageMap; if (g_NtBuildNumber > 10586) return ObFindPrivateNamespaceLookupTable2(Context); do { // // Locate PAGE image section. // SectionBase = supLookupImageSectionByName( PAGE_SECTION, PAGE_SECTION_LEGNTH, (PVOID)hNtOs, &SectionSize); if ((SectionBase == 0) || (SectionSize == 0)) break; switch (g_NtBuildNumber) { case 9200: Signature = NamespacePattern8; SignatureSize = sizeof(NamespacePattern8); break; default: Signature = NamespacePattern; SignatureSize = sizeof(NamespacePattern); break; } ptrCode = (PBYTE)supFindPattern( (PBYTE)SectionBase, SectionSize, Signature, SignatureSize); if (ptrCode == NULL) break; // // Lookup exact value from found pattern result. // Index = 0; // // Default code scan pattern. // MatchingPattern = LeaPattern_PNS; do { hde64_disasm((void*)(ptrCode + Index), &hs); if (hs.flags & F_ERROR) break; if (hs.len == 7) { if ((ptrCode[Index] == MatchingPattern[0]) && (ptrCode[Index + 1] == MatchingPattern[1]) && (ptrCode[Index + 2] == MatchingPattern[2])) { Rel = *(PLONG)(ptrCode + Index + 3); break; } } Index += hs.len; } while (Index < 128); if (Rel == 0) break; Address = (ULONG_PTR)ptrCode + Index + hs.len + Rel; Address = NtOsBase + Address - (ULONG_PTR)hNtOs; if (!kdAddressInNtOsImage((PVOID)Address)) break; } while (FALSE); return (PVOID)Address; } /* * ObGetCallbackBlockRoutine * * Purpose: * * Read callback block routine from kernel and return function pointer. * */ PVOID ObGetCallbackBlockRoutine( _In_ PVOID CallbackBlock ) { EX_CALLBACK_ROUTINE_BLOCK readBlock; readBlock.Function = NULL; if (!kdReadSystemMemoryEx((ULONG_PTR)CallbackBlock, &readBlock, sizeof(EX_CALLBACK_ROUTINE_BLOCK), NULL)) { return NULL; } else { return readBlock.Function; } } /* * kdFindServiceTables * * Purpose: * * Find system service table pointers from ntoskrnl image. * */ _Success_(return == TRUE) BOOL kdFindKiServiceTables( _In_ ULONG_PTR MappedImageBase, _In_ ULONG_PTR KernelImageBase, _Out_opt_ ULONG_PTR *KiServiceTablePtr, _Out_opt_ ULONG *KiServiceLimit, _Out_opt_ ULONG_PTR *W32pServiceTable, _Out_opt_ ULONG *W32pServiceLimit ) { BOOL bResult = FALSE, bS1, bS2; ULONG Index, SignatureSize; LONG Rel = 0; ULONG SectionSize; PBYTE ptrCode; ULONG_PTR LookupAddress = 0, Address = 0, SectionBase = 0; hde64s hs; PBYTE MatchingPattern; KSERVICE_TABLE_DESCRIPTOR ServiceTableDescriptor[2]; __try { do { // // If KeServiceDescriptorTableShadow is not extracted then extract it. // if (g_kdctx.KeServiceDescriptorTableShadow == 0) { // // Locate .text image section. // SectionBase = (ULONG_PTR)supLookupImageSectionByName( TEXT_SECTION, TEXT_SECTION_LEGNTH, (PVOID)MappedImageBase, &SectionSize); if ((SectionBase == 0) || (SectionSize == 0)) break; SignatureSize = sizeof(KiSystemServiceStartPattern); if (SignatureSize > SectionSize) break; // // Find KiSystemServiceStart signature. // LookupAddress = (ULONG_PTR)supFindPattern( (PBYTE)SectionBase, SectionSize, (PBYTE)KiSystemServiceStartPattern, SignatureSize); if (LookupAddress == 0) break; LookupAddress += SignatureSize; // // Find KeServiceDescriptorTableShadow. // ptrCode = (PBYTE)LookupAddress; Index = 0; Rel = 0; MatchingPattern = LeaPattern_KeServiceDescriptorTableShadow; do { hde64_disasm((void*)(ptrCode + Index), &hs); if (hs.flags & F_ERROR) break; if (hs.len == 7) { //look for lea if ((ptrCode[Index] == MatchingPattern[0]) && (ptrCode[Index + 1] == MatchingPattern[1]) && (ptrCode[Index + 2] == MatchingPattern[2])) { Rel = *(PLONG)(ptrCode + Index + 3); break; } } Index += hs.len; } while (Index < 128); if (Rel == 0) break; // // Dump ntos syscall table info. // Address = (ULONG_PTR)ptrCode + Index + hs.len + Rel; Address = KernelImageBase + Address - MappedImageBase; g_kdctx.KeServiceDescriptorTableShadow = Address; } else { Address = g_kdctx.KeServiceDescriptorTableShadow; } if (!kdAddressInNtOsImage((PVOID)Address)) break; RtlSecureZeroMemory(&ServiceTableDescriptor, sizeof(ServiceTableDescriptor)); if (!kdReadSystemMemoryEx( Address, &ServiceTableDescriptor, sizeof(ServiceTableDescriptor), NULL)) { break; } if (KiServiceLimit) *KiServiceLimit = ServiceTableDescriptor[0].Limit; if (KiServiceTablePtr) *KiServiceTablePtr = ServiceTableDescriptor[0].Base; if ((KiServiceLimit != NULL) && (KiServiceTablePtr != NULL)) { bS1 = ((ServiceTableDescriptor[0].Base != 0) && (ServiceTableDescriptor[0].Limit)); } else { bS1 = TRUE; } if (W32pServiceLimit) *W32pServiceLimit = ServiceTableDescriptor[1].Limit; if (W32pServiceTable) *W32pServiceTable = ServiceTableDescriptor[1].Base; if ((W32pServiceLimit != NULL) && (W32pServiceTable != NULL)) { bS2 = ((ServiceTableDescriptor[1].Base != 0) && (ServiceTableDescriptor[1].Limit)); } else { bS2 = TRUE; } bResult = (bS1) && (bS2); } while (FALSE); } __except (exceptFilter(GetExceptionCode(), GetExceptionInformation())) { return FALSE; } return bResult; } /* * ObGetDirectoryObjectAddress * * Purpose: * * Obtain directory object kernel address by opening directory by name * and quering resulted handle in NtQuerySystemInformation(SystemExtendedHandleInformation) handle dump * */ BOOL ObGetDirectoryObjectAddress( _In_opt_ LPWSTR lpDirectory, _Inout_ PULONG_PTR lpRootAddress, _Inout_opt_ PUSHORT lpTypeIndex ) { BOOL bFound = FALSE; HANDLE hDirectory = NULL; NTSTATUS status; LPWSTR lpTarget; OBJECT_ATTRIBUTES objattr; UNICODE_STRING objname; if (lpRootAddress == NULL) return bFound; if (lpDirectory == NULL) { lpTarget = KM_OBJECTS_ROOT_DIRECTORY; } else { lpTarget = lpDirectory; } RtlInitUnicodeString(&objname, lpTarget); InitializeObjectAttributes(&objattr, &objname, OBJ_CASE_INSENSITIVE, NULL, NULL); status = NtOpenDirectoryObject( &hDirectory, DIRECTORY_QUERY, &objattr); if (NT_SUCCESS(status)) { bFound = supQueryObjectFromHandle( hDirectory, lpRootAddress, lpTypeIndex); NtClose(hDirectory); } return bFound; } /* * ObQueryNameString * * Purpose: * * Reads object name from kernel memory, returned buffer must be freed with supHeapFree * */ LPWSTR ObQueryNameString( _In_ ULONG_PTR NameInfoAddress, _Out_opt_ PSIZE_T ReturnLength ) { ULONG fLen; LPWSTR lpObjectName = NULL; OBJECT_HEADER_NAME_INFO NameInfo; if (ReturnLength) *ReturnLength = 0; RtlSecureZeroMemory(&NameInfo, sizeof(OBJECT_HEADER_NAME_INFO)); if (kdReadSystemMemoryEx( NameInfoAddress, &NameInfo, sizeof(OBJECT_HEADER_NAME_INFO), NULL)) { if (NameInfo.Name.Length) { fLen = NameInfo.Name.Length + sizeof(UNICODE_NULL); lpObjectName = (LPWSTR)supHeapAlloc(fLen); if (lpObjectName != NULL) { NameInfoAddress = (ULONG_PTR)NameInfo.Name.Buffer; if (kdReadSystemMemoryEx( NameInfoAddress, lpObjectName, NameInfo.Name.Length, NULL)) { if (ReturnLength) *ReturnLength = fLen; } else { supHeapFree(lpObjectName); lpObjectName = NULL; } } } } return lpObjectName; } /* * ObpCopyObjectBasicInfo * * Purpose: * * Read object related data from kernel to local user copy. * Returned object must be freed wtih supHeapFree when no longer needed. * * Parameters: * * ObjectAddress - kernel address of object specified type (e.g. DRIVER_OBJECT). * ObjectHeaderAddress - OBJECT_HEADER structure kernel address. * ObjectHeaderAddressValid - if set then ObjectHeaderAddress in already converted form. * DumpedObjectHeader - pointer to OBJECT_HEADER structure previously dumped. * * Return Value: * * Pointer to OBJINFO structure allocated from WinObjEx heap and filled with kernel data. * */ POBJINFO ObpCopyObjectBasicInfo( _In_ ULONG_PTR ObjectAddress, _In_ ULONG_PTR ObjectHeaderAddress, _In_ BOOL ObjectHeaderAddressValid, _In_opt_ POBJECT_HEADER DumpedObjectHeader ) { ULONG_PTR HeaderAddress = 0, InfoHeaderAddress = 0; POBJINFO lpData = NULL; OBJECT_HEADER ObjectHeader, *pObjectHeader; // // Convert object address to object header address. // if (ObjectHeaderAddressValid) { HeaderAddress = ObjectHeaderAddress; } else { HeaderAddress = (ULONG_PTR)OBJECT_TO_OBJECT_HEADER(ObjectAddress); } // // ObjectHeader already dumped, copy it. // if (DumpedObjectHeader) { pObjectHeader = DumpedObjectHeader; } else { // // ObjectHeader wasn't dumped, validate it address and do dump. // if (HeaderAddress < g_kdctx.SystemRangeStart) return NULL; // // Read OBJECT_HEADER. // RtlSecureZeroMemory(&ObjectHeader, sizeof(OBJECT_HEADER)); if (!kdReadSystemMemoryEx( HeaderAddress, &ObjectHeader, sizeof(OBJECT_HEADER), NULL)) { #ifdef _DEBUG DbgPrint("%s kdReadSystemMemoryEx(ObjectHeaderAddress) failed\r\n", __FUNCTION__); #endif return NULL; } pObjectHeader = &ObjectHeader; } // // Allocate OBJINFO structure, exit on fail. // lpData = (POBJINFO)supHeapAlloc(sizeof(OBJINFO)); if (lpData == NULL) return NULL; lpData->ObjectAddress = ObjectAddress; lpData->HeaderAddress = HeaderAddress; // // Copy object header. // supCopyMemory( &lpData->ObjectHeader, sizeof(OBJECT_HEADER), pObjectHeader, sizeof(OBJECT_HEADER)); // // Query and copy quota info if exist. // InfoHeaderAddress = 0; if (ObHeaderToNameInfoAddress( pObjectHeader->InfoMask, HeaderAddress, &InfoHeaderAddress, HeaderQuotaInfoFlag)) { kdReadSystemMemoryEx( HeaderAddress, &lpData->ObjectQuotaHeader, sizeof(OBJECT_HEADER_QUOTA_INFO), NULL); } return lpData; } /* * ObpWalkDirectory * * Purpose: * * Walks given directory and looks for specified object inside * Returned object must be freed wtih supHeapFree when no longer needed. * * Note: * * OBJECT_DIRECTORY definition changed in Windows 10, however this doesn't require * this routine change as we rely here only on HashBuckets which is on same offset. * */ POBJINFO ObpWalkDirectory( _In_ LPWSTR lpObjectToFind, _In_ ULONG_PTR DirectoryAddress ) { BOOL bFound; INT c; SIZE_T retSize; LPWSTR lpObjectName; ULONG_PTR ObjectHeaderAddress, item0, item1, InfoHeaderAddress; OBJECT_HEADER ObjectHeader; OBJECT_DIRECTORY DirObject; OBJECT_DIRECTORY_ENTRY Entry; __try { if (lpObjectToFind == NULL) return NULL; // // Read object directory at address. // RtlSecureZeroMemory(&DirObject, sizeof(OBJECT_DIRECTORY)); if (!kdReadSystemMemoryEx( DirectoryAddress, &DirObject, sizeof(OBJECT_DIRECTORY), NULL)) { #ifdef _DEBUG DbgPrint("%s kdReadSystemMemoryEx(DirectoryAddress) failed\r\n", __FUNCTION__); #endif return NULL; } lpObjectName = NULL; retSize = 0; bFound = FALSE; // // Check if root special case. // if (_strcmpi(lpObjectToFind, KM_OBJECTS_ROOT_DIRECTORY) == 0) { return ObpCopyObjectBasicInfo( DirectoryAddress, 0, FALSE, NULL); } // // Not a root directory, scan given object directory. // for (c = 0; c < NUMBER_HASH_BUCKETS; c++) { item0 = (ULONG_PTR)DirObject.HashBuckets[c]; if (item0 != 0) { item1 = item0; do { // // Read object directory entry, exit on fail. // RtlSecureZeroMemory(&Entry, sizeof(OBJECT_DIRECTORY_ENTRY)); if (!kdReadSystemMemoryEx( item1, &Entry, sizeof(OBJECT_DIRECTORY_ENTRY), NULL)) { #ifdef _DEBUG DbgPrint("%s kdReadSystemMemoryEx(OBJECT_DIRECTORY_ENTRY(HashEntry)) failed\r\n", __FUNCTION__); #endif break; } // // Read object header, skip entry on fail. // RtlSecureZeroMemory(&ObjectHeader, sizeof(OBJECT_HEADER)); ObjectHeaderAddress = (ULONG_PTR)OBJECT_TO_OBJECT_HEADER(Entry.Object); if (!kdReadSystemMemoryEx( ObjectHeaderAddress, &ObjectHeader, sizeof(OBJECT_HEADER), NULL)) { #ifdef _DEBUG DbgPrint("%s kdReadSystemMemoryEx(ObjectHeaderAddress(Entry.Object)) failed\r\n", __FUNCTION__); #endif goto NextItem; } // // Check if object has name, skip entry on fail. // InfoHeaderAddress = 0; retSize = 0; if (!ObHeaderToNameInfoAddress( ObjectHeader.InfoMask, ObjectHeaderAddress, &InfoHeaderAddress, HeaderNameInfoFlag)) { goto NextItem; } // // If object has name, query it. // lpObjectName = ObQueryNameString(InfoHeaderAddress, &retSize); if ((lpObjectName != NULL) && (retSize != 0)) { // // Compare full object names. // bFound = (_strcmpi(lpObjectName, lpObjectToFind) == 0); supHeapFree(lpObjectName); // // if they're identical, allocate item info and copy it. // if (bFound) { return ObpCopyObjectBasicInfo( (ULONG_PTR)Entry.Object, ObjectHeaderAddress, TRUE, &ObjectHeader); } } //ObQueryName NextItem: item1 = (ULONG_PTR)Entry.ChainLink; } while (item1 != 0); } } } __except (exceptFilter(GetExceptionCode(), GetExceptionInformation())) { return NULL; } return NULL; } /* * ObQueryObjectByAddress * * Purpose: * * Look for object at specified address. * Returned object memory must be released with supHeapFree when object is no longer needed. * */ POBJINFO ObQueryObjectByAddress( _In_ ULONG_PTR ObjectAddress ) { ULONG_PTR ObjectHeaderAddress; OBJECT_HEADER ObjectHeader; if (ObjectAddress < g_kdctx.SystemRangeStart) return NULL; if (!kdConnectDriver()) return NULL; // // Read object header, fail is critical. // RtlSecureZeroMemory(&ObjectHeader, sizeof(OBJECT_HEADER)); ObjectHeaderAddress = (ULONG_PTR)OBJECT_TO_OBJECT_HEADER(ObjectAddress); if (!kdReadSystemMemoryEx( ObjectHeaderAddress, &ObjectHeader, sizeof(OBJECT_HEADER), NULL)) { #ifdef _DEBUG DbgPrint("%s kdReadSystemMemoryEx(ObjectHeaderAddress(ObjectAddress)) failed\r\n", __FUNCTION__); #endif return NULL; } return ObpCopyObjectBasicInfo( (ULONG_PTR)ObjectAddress, ObjectHeaderAddress, TRUE, &ObjectHeader); } /* * ObQueryObject * * Purpose: * * Look for object inside specified directory. * If object is directory look for it in upper directory. * Returned object memory must be released with supHeapFree when object is no longer needed. * */ POBJINFO ObQueryObject( _In_ LPWSTR lpDirectory, _In_ LPWSTR lpObjectName ) { BOOL needFree = FALSE; ULONG_PTR DirectoryAddress; SIZE_T i, l, rdirLen, ldirSz; LPWSTR SingleDirName, LookupDirName; if (!kdConnectDriver()) return NULL; __try { LookupDirName = lpDirectory; // // 1) Check if object is directory self // Extract directory name and compare (case insensitive) with object name // Else go to 3 // l = 0; rdirLen = _strlen(lpDirectory); for (i = 0; i < rdirLen; i++) { if (lpDirectory[i] == '\\') l = i + 1; } SingleDirName = &lpDirectory[l]; if (_strcmpi(SingleDirName, lpObjectName) == 0) { // // 2) If we are looking for directory itself, move search directory up // e.g. lpDirectory = \ObjectTypes, lpObjectName = ObjectTypes then lpDirectory = \ // ldirSz = rdirLen * sizeof(WCHAR) + sizeof(UNICODE_NULL); LookupDirName = (LPWSTR)supHeapAlloc(ldirSz); if (LookupDirName == NULL) return NULL; needFree = TRUE; //special case for root if (l == 1) l++; supCopyMemory(LookupDirName, ldirSz, lpDirectory, (l - 1) * sizeof(WCHAR)); } // // 3) Get Directory address where we will look for object // DirectoryAddress = 0; if (ObGetDirectoryObjectAddress(LookupDirName, &DirectoryAddress, NULL)) { if (needFree) supHeapFree(LookupDirName); // // 4) Find object in directory by name (case insensitive) // return ObpWalkDirectory(lpObjectName, DirectoryAddress); } } __except (exceptFilter(GetExceptionCode(), GetExceptionInformation())) { return NULL; } return NULL; } /* * ObDumpTypeInfo * * Purpose: * * Dumps Type header including initializer. * */ BOOL ObDumpTypeInfo( _In_ ULONG_PTR ObjectAddress, _Inout_ POBJECT_TYPE_COMPATIBLE ObjectTypeInfo ) { return kdReadSystemMemoryEx( ObjectAddress, ObjectTypeInfo, sizeof(OBJECT_TYPE_COMPATIBLE), NULL); } /* * ObpWalkDirectoryRecursive * * Purpose: * * Recursively dump Object Manager directories. * * Note: * * OBJECT_DIRECTORY definition changed in Windows 10, however this doesn't require * this routine change as we rely here only on HashBuckets which is on same offset. * */ VOID ObpWalkDirectoryRecursive( _In_ BOOL fIsRoot, _In_ PLIST_ENTRY ListHead, _In_ HANDLE ListHeap, _In_opt_ LPWSTR lpRootDirectory, _In_ ULONG_PTR DirectoryAddress, _In_ USHORT DirectoryTypeIndex ) { UCHAR ObjectTypeIndex; INT c; SIZE_T dirLen, fLen, rdirLen, retSize; ULONG_PTR ObjectHeaderAddress, item0, item1, InfoHeaderAddress; POBJREF ObjectEntry; LPWSTR lpObjectName, lpDirectoryName; OBJECT_HEADER ObjectHeader; OBJECT_DIRECTORY DirObject; OBJECT_DIRECTORY_ENTRY Entry; RtlSecureZeroMemory(&DirObject, sizeof(OBJECT_DIRECTORY)); if (!kdReadSystemMemoryEx( DirectoryAddress, &DirObject, sizeof(OBJECT_DIRECTORY), NULL)) { #ifdef _DEBUG DbgPrint("%s kdReadSystemMemoryEx(DirectoryAddress) failed\r\n", __FUNCTION__); #endif return; } if (lpRootDirectory != NULL) { rdirLen = (1 + _strlen(lpRootDirectory)) * sizeof(WCHAR); } else { rdirLen = 0; } lpObjectName = NULL; retSize = 0; ObjectTypeIndex = 0; for (c = 0; c < NUMBER_HASH_BUCKETS; c++) { item0 = (ULONG_PTR)DirObject.HashBuckets[c]; if (item0 != 0) { item1 = item0; do { // // Read object directory entry. // RtlSecureZeroMemory(&Entry, sizeof(OBJECT_DIRECTORY_ENTRY)); if (kdReadSystemMemoryEx( item1, &Entry, sizeof(OBJECT_DIRECTORY_ENTRY), NULL)) { // // Read object. // First read header from directory entry object. // RtlSecureZeroMemory(&ObjectHeader, sizeof(OBJECT_HEADER)); ObjectHeaderAddress = (ULONG_PTR)OBJECT_TO_OBJECT_HEADER(Entry.Object); if (kdReadSystemMemoryEx( ObjectHeaderAddress, &ObjectHeader, sizeof(OBJECT_HEADER), NULL)) { // // Second read object data. // Query object name. // InfoHeaderAddress = 0; retSize = 0; if (ObHeaderToNameInfoAddress( ObjectHeader.InfoMask, ObjectHeaderAddress, &InfoHeaderAddress, HeaderNameInfoFlag)) { lpObjectName = ObQueryNameString( InfoHeaderAddress, &retSize); } // // Allocate object entry. // ObjectEntry = (POBJREF)RtlAllocateHeap( ListHeap, HEAP_ZERO_MEMORY, sizeof(OBJREF)); if (ObjectEntry) { // // Save object address. // ObjectEntry->ObjectAddress = (ULONG_PTR)Entry.Object; ObjectEntry->HeaderAddress = ObjectHeaderAddress; ObjectEntry->TypeIndex = ObjectHeader.TypeIndex; // // Copy dir + name. // if (lpObjectName) { fLen = (_strlen(lpObjectName) * sizeof(WCHAR)) + (2 * sizeof(WCHAR)) + rdirLen + sizeof(UNICODE_NULL); ObjectEntry->ObjectName = (LPWSTR)RtlAllocateHeap( ListHeap, HEAP_ZERO_MEMORY, fLen); if (ObjectEntry->ObjectName) { _strcpy(ObjectEntry->ObjectName, lpRootDirectory); if (fIsRoot == FALSE) { _strcat(ObjectEntry->ObjectName, L"\\"); } _strcat(ObjectEntry->ObjectName, lpObjectName); } } InsertHeadList(ListHead, &ObjectEntry->ListEntry); } // // Check if current object is a directory. // ObjectTypeIndex = ObDecodeTypeIndex(Entry.Object, ObjectHeader.TypeIndex); if (ObjectTypeIndex == DirectoryTypeIndex) { // // Build new directory string (old directory + \ + current). // fLen = 0; if (lpObjectName) { fLen = retSize; } dirLen = fLen + rdirLen + (2 * sizeof(WCHAR)) + sizeof(UNICODE_NULL); lpDirectoryName = (LPWSTR)supHeapAlloc(dirLen); if (lpDirectoryName) { _strcpy(lpDirectoryName, lpRootDirectory); if (fIsRoot == FALSE) { _strcat(lpDirectoryName, L"\\"); } if (lpObjectName) { _strcat(lpDirectoryName, lpObjectName); } } // // Walk subdirectory. // ObpWalkDirectoryRecursive( FALSE, ListHead, ListHeap, lpDirectoryName, (ULONG_PTR)Entry.Object, DirectoryTypeIndex); if (lpDirectoryName) { supHeapFree(lpDirectoryName); lpDirectoryName = NULL; } } if (lpObjectName) { supHeapFree(lpObjectName); lpObjectName = NULL; } } //if (kdReadSystemMemoryEx(OBJECT_HEADER) item1 = (ULONG_PTR)Entry.ChainLink; } //if (kdReadSystemMemoryEx(OBJECT_DIRECTORY_ENTRY) else { item1 = 0; } } while (item1 != 0); } } } /* * ObpWalkPrivateNamespaceTable * * Purpose: * * Dump Object Manager private namespace objects. * * Note: * * OBJECT_DIRECTORY definition changed in Windows 10, however this doesn't require * this routine change as we rely here only on HashBuckets which is on same offset. * */ BOOL ObpWalkPrivateNamespaceTable( _In_ PLIST_ENTRY ListHead, _In_ HANDLE ListHeap, _In_ ULONG_PTR TableAddress ) { ULONG i, j, c = 0; SIZE_T retSize = 0; ULONG_PTR ObjectHeaderAddress, item0, item1, InfoHeaderAddress; PLIST_ENTRY Next, Head; LIST_ENTRY ListEntry; POBJREF ObjectEntry; LPWSTR lpObjectName = NULL; OBJECT_HEADER ObjectHeader; OBJECT_DIRECTORY DirObject; OBJECT_DIRECTORY_ENTRY Entry; OBJECT_NAMESPACE_LOOKUPTABLE LookupTable; OBJECT_NAMESPACE_ENTRY LookupEntry; if ( (ListHead == NULL) || (TableAddress == 0) ) { return FALSE; } // // Dump namespace lookup table. // RtlSecureZeroMemory(&LookupTable, sizeof(OBJECT_NAMESPACE_LOOKUPTABLE)); if (!kdReadSystemMemoryEx( TableAddress, &LookupTable, sizeof(OBJECT_NAMESPACE_LOOKUPTABLE), NULL)) { return FALSE; } for (i = 0; i < NUMBER_HASH_BUCKETS; i++) { ListEntry = LookupTable.HashBuckets[i]; Head = (PLIST_ENTRY)(TableAddress + (i * sizeof(LIST_ENTRY))); Next = ListEntry.Flink; while (Next != Head) { RtlSecureZeroMemory(&LookupEntry, sizeof(OBJECT_NAMESPACE_ENTRY)); if (!kdReadSystemMemoryEx( (ULONG_PTR)Next, &LookupEntry, sizeof(OBJECT_NAMESPACE_ENTRY), NULL)) { break; } ListEntry = LookupEntry.ListEntry; RtlSecureZeroMemory(&DirObject, sizeof(OBJECT_DIRECTORY)); if (!kdReadSystemMemoryEx( (ULONG_PTR)LookupEntry.NamespaceRootDirectory, &DirObject, sizeof(OBJECT_DIRECTORY), NULL)) { break; } for (j = 0; j < NUMBER_HASH_BUCKETS; j++) { item0 = (ULONG_PTR)DirObject.HashBuckets[j]; if (item0 != 0) { item1 = item0; do { RtlSecureZeroMemory(&Entry, sizeof(OBJECT_DIRECTORY_ENTRY)); if (kdReadSystemMemoryEx( item1, &Entry, sizeof(OBJECT_DIRECTORY_ENTRY), NULL)) { RtlSecureZeroMemory(&ObjectHeader, sizeof(OBJECT_HEADER)); ObjectHeaderAddress = (ULONG_PTR)OBJECT_TO_OBJECT_HEADER(Entry.Object); if (kdReadSystemMemoryEx( ObjectHeaderAddress, &ObjectHeader, sizeof(OBJECT_HEADER), NULL)) { // // Allocate object entry // ObjectEntry = (POBJREF)RtlAllocateHeap( ListHeap, HEAP_ZERO_MEMORY, sizeof(OBJREF)); if (ObjectEntry) { // // Save object address, header and type index. // ObjectEntry->ObjectAddress = (ULONG_PTR)Entry.Object; ObjectEntry->HeaderAddress = ObjectHeaderAddress; ObjectEntry->TypeIndex = ObjectHeader.TypeIndex; //save index as is (decoded if needed later) // // Save object namespace/lookup entry address. // ObjectEntry->PrivateNamespace.NamespaceDirectoryAddress = (ULONG_PTR)LookupEntry.NamespaceRootDirectory; ObjectEntry->PrivateNamespace.NamespaceLookupEntry = (ULONG_PTR)Next; ObjectEntry->PrivateNamespace.SizeOfBoundaryInformation = LookupEntry.SizeOfBoundaryInformation; // // Query object name. // InfoHeaderAddress = 0; retSize = 0; if (ObHeaderToNameInfoAddress( ObjectHeader.InfoMask, ObjectHeaderAddress, &InfoHeaderAddress, HeaderNameInfoFlag)) { lpObjectName = ObQueryNameString(InfoHeaderAddress, &retSize); } // // Copy object name. // if (lpObjectName) { ObjectEntry->ObjectName = (LPWSTR)RtlAllocateHeap( ListHeap, HEAP_ZERO_MEMORY, retSize); if (ObjectEntry->ObjectName) { _strcpy(ObjectEntry->ObjectName, lpObjectName); } // // Free memory allocated for object name. // supHeapFree(lpObjectName); lpObjectName = NULL; } c++; InsertHeadList(ListHead, &ObjectEntry->ListEntry); } //if (ObjectEntry) } item1 = (ULONG_PTR)Entry.ChainLink; } else { item1 = 0; } } while (item1 != 0); } } Next = ListEntry.Flink; } } return (c > 0); } /* * ObCollectionCreate * * Purpose: * * Create collection of object directory dumped info * * Collection must be destroyed with ObCollectionDestroy after use. * * If specified will dump private namespace objects. * */ BOOL ObCollectionCreate( _In_ POBJECT_COLLECTION Collection, _In_ BOOL fNamespace, _In_ BOOL Locked ) { BOOL bResult = FALSE; if (Collection == NULL) { return bResult; } if (!kdConnectDriver()) return bResult; if (!Locked) { RtlEnterCriticalSection(&g_kdctx.ListLock); } Collection->Heap = RtlCreateHeap(HEAP_GROWABLE, NULL, 0, 0, NULL, NULL); if (Collection->Heap == NULL) goto _FailWeLeave; RtlSetHeapInformation(Collection->Heap, HeapEnableTerminationOnCorruption, NULL, 0); __try { InitializeListHead(&Collection->ListHead); if (fNamespace == FALSE) { if ( (g_kdctx.DirectoryRootAddress == 0) || (g_kdctx.DirectoryTypeIndex == 0) ) { if (!ObGetDirectoryObjectAddress( NULL, &g_kdctx.DirectoryRootAddress, &g_kdctx.DirectoryTypeIndex)) { SetLastError(ERROR_INTERNAL_ERROR); goto _FailWeLeave; } } if ( (g_kdctx.DirectoryRootAddress != 0) && (g_kdctx.DirectoryTypeIndex != 0) ) { ObpWalkDirectoryRecursive( TRUE, &Collection->ListHead, Collection->Heap, KM_OBJECTS_ROOT_DIRECTORY, g_kdctx.DirectoryRootAddress, g_kdctx.DirectoryTypeIndex); bResult = TRUE; } } else { if (g_kdctx.PrivateNamespaceLookupTable == NULL) g_kdctx.PrivateNamespaceLookupTable = ObFindPrivateNamespaceLookupTable(&g_kdctx); if (g_kdctx.PrivateNamespaceLookupTable != NULL) { bResult = ObpWalkPrivateNamespaceTable( &Collection->ListHead, Collection->Heap, (ULONG_PTR)g_kdctx.PrivateNamespaceLookupTable); } else { SetLastError(ERROR_INTERNAL_ERROR); } } } __except (exceptFilter(GetExceptionCode(), GetExceptionInformation())) { bResult = FALSE; } _FailWeLeave: if (!Locked) { RtlLeaveCriticalSection(&g_kdctx.ListLock); } return bResult; } /* * ObCollectionDestroy * * Purpose: * * Destroy collection with object directory dumped info * */ VOID ObCollectionDestroy( _In_ POBJECT_COLLECTION Collection ) { if (Collection == NULL) return; RtlEnterCriticalSection(&g_kdctx.ListLock); if (Collection->Heap) { RtlDestroyHeap(Collection->Heap); Collection->Heap = NULL; } InitializeListHead(&Collection->ListHead); RtlLeaveCriticalSection(&g_kdctx.ListLock); } /* * ObCollectionEnumerate * * Purpose: * * Enumerate object collection and callback on each element. * */ BOOL ObCollectionEnumerate( _In_ POBJECT_COLLECTION Collection, _In_ PENUMERATE_COLLECTION_CALLBACK Callback, _In_opt_ PVOID Context ) { BOOL bCancelled = FALSE; POBJREF ObjectEntry = NULL; PLIST_ENTRY Head, Next; if ((Collection == NULL) || (Callback == NULL)) return FALSE; RtlEnterCriticalSection(&g_kdctx.ListLock); if (!IsListEmpty(&Collection->ListHead)) { Head = &Collection->ListHead; Next = Head->Flink; while ((Next != NULL) && (Next != Head)) { ObjectEntry = CONTAINING_RECORD(Next, OBJREF, ListEntry); bCancelled = Callback(ObjectEntry, Context); if (bCancelled) break; Next = Next->Flink; } } RtlLeaveCriticalSection(&g_kdctx.ListLock); return (bCancelled == FALSE); } /* * ObCollectionFindByAddress * * Purpose: * * Find object by address in object directory dump collection. * Do not free returned buffer, it is released in ObCollectionDestroy. * */ POBJREF ObCollectionFindByAddress( _In_ POBJECT_COLLECTION Collection, _In_ ULONG_PTR ObjectAddress, _In_ BOOLEAN fNamespace ) { BOOL bFound = FALSE, bCollectionPresent = FALSE; POBJREF ObjectEntry = NULL; PLIST_ENTRY Head, Next; if (Collection == NULL) return NULL; RtlEnterCriticalSection(&g_kdctx.ListLock); if (IsListEmpty(&Collection->ListHead)) { bCollectionPresent = ObCollectionCreate(Collection, fNamespace, TRUE); } else { bCollectionPresent = TRUE; } if (bCollectionPresent) { Head = &Collection->ListHead; Next = Head->Flink; while ((Next != NULL) && (Next != Head)) { ObjectEntry = CONTAINING_RECORD(Next, OBJREF, ListEntry); if (ObjectEntry->ObjectAddress == ObjectAddress) { bFound = TRUE; break; } Next = Next->Flink; } } RtlLeaveCriticalSection(&g_kdctx.ListLock); return (bFound) ? ObjectEntry : NULL; } /* * kdConnectDriver * * Purpose: * * Acquire handle of helper driver device if possible. * * N.B. * * If device handle is already present function immediately return TRUE. * If current token is not elevated admin token function immediately return FALSE. * SE_DEBUG_PRIVILEGE is required, if it cannot be assigned function return FALSE. * */ BOOLEAN kdConnectDriver( VOID) { NTSTATUS status; HANDLE deviceHandle = NULL; UNICODE_STRING usDevice; OBJECT_ATTRIBUTES obja; IO_STATUS_BLOCK iost; WCHAR szDeviceName[100]; if (g_kdctx.hDevice != NULL) return TRUE; if (g_kdctx.IsFullAdmin == FALSE) return FALSE; if (supEnablePrivilege(SE_DEBUG_PRIVILEGE, TRUE)) { _strcpy(szDeviceName, TEXT("\\Device\\")); _strcat(szDeviceName, KLDBGDRV); RtlInitUnicodeString(&usDevice, szDeviceName); InitializeObjectAttributes(&obja, &usDevice, OBJ_CASE_INSENSITIVE, NULL, NULL); status = NtCreateFile( &deviceHandle, GENERIC_READ | GENERIC_WRITE, &obja, &iost, NULL, 0, 0, FILE_OPEN, 0, NULL, 0); if (NT_SUCCESS(status)) { g_kdctx.hDevice = deviceHandle; g_kdctx.drvOpenLoadStatus = ERROR_SUCCESS; return TRUE; } else { supEnablePrivilege(SE_DEBUG_PRIVILEGE, FALSE); g_kdctx.drvOpenLoadStatus = ERROR_NOT_CAPABLE; } } return FALSE; } /* * kdQueryIopInvalidDeviceRequest * * Purpose: * * Find IopInvalidDeviceRequest assuming Windows assigned it to WinDBG driver. * * Kldbgdrv only defined: * IRP_MJ_CREATE * IRP_MJ_CLOSE * IRP_MJ_DEVICE_CONTROL */ PVOID kdQueryIopInvalidDeviceRequest( VOID ) { PVOID pHandler; POBJINFO pSelfObj; ULONG_PTR drvObjectAddress; DRIVER_OBJECT drvObject; pHandler = NULL; pSelfObj = ObQueryObject(L"\\Driver", KLDBGDRV); if (pSelfObj) { drvObjectAddress = pSelfObj->ObjectAddress; RtlSecureZeroMemory(&drvObject, sizeof(drvObject)); if (kdReadSystemMemoryEx( drvObjectAddress, &drvObject, sizeof(drvObject), NULL)) { pHandler = drvObject.MajorFunction[IRP_MJ_CREATE_MAILSLOT]; // // IopInvalidDeviceRequest is a routine inside ntoskrnl. // if (!kdAddressInNtOsImage(pHandler)) pHandler = NULL; } supHeapFree(pSelfObj); } return pHandler; } /* * kdIsDebugBoot * * Purpose: * * Perform check is the current OS booted with DEBUG flag. * */ BOOL kdIsDebugBoot( VOID ) { ULONG rl = 0; SYSTEM_KERNEL_DEBUGGER_INFORMATION kdInfo; RtlSecureZeroMemory(&kdInfo, sizeof(kdInfo)); if (NT_SUCCESS(NtQuerySystemInformation(SystemKernelDebuggerInformation, &kdInfo, sizeof(kdInfo), &rl))) { return kdInfo.KernelDebuggerEnabled; } return FALSE; } /* * kdShowError * * Purpose: * * Display details about failed driver call. * */ VOID kdShowError( _In_ ULONG InputBufferLength, _In_ NTSTATUS Status, _In_ PIO_STATUS_BLOCK Iosb ) { WCHAR szBuffer[512]; _strcpy(szBuffer, TEXT("NtDeviceIoControlFile = 0x")); ultohex(Status, _strend(szBuffer)); _strcat(szBuffer, TEXT("\r\nIoStatusBlock.Status = 0x")); ultohex(Iosb->Status, _strend(szBuffer)); _strcat(szBuffer, TEXT("\r\nIoStatusBlock.Information = 0x")); u64tohex(Iosb->Information, _strend(szBuffer)); _strcat(szBuffer, TEXT("\r\n\nInputBufferLength = 0x")); ultohex(InputBufferLength, _strend(szBuffer)); MessageBox(GetDesktopWindow(), szBuffer, NULL, MB_TOPMOST | MB_ICONERROR); } /* * kdReadSystemMemoryEx * * Purpose: * * Wrapper around SysDbgReadVirtual request to the KLDBGDRV * */ BOOL kdReadSystemMemoryEx( _In_ ULONG_PTR Address, _Inout_ PVOID Buffer, _In_ ULONG BufferSize, _Out_opt_ PULONG NumberOfBytesRead ) { NTSTATUS status; KLDBG kldbg; IO_STATUS_BLOCK iost; SYSDBG_VIRTUAL dbgRequest; if (NumberOfBytesRead) *NumberOfBytesRead = 0; if ((Buffer == NULL) || (BufferSize == 0)) return FALSE; if (Address < g_kdctx.SystemRangeStart) return FALSE; if (!kdConnectDriver()) return FALSE; // // Fill parameters for KdSystemDebugControl. // dbgRequest.Address = (PVOID)Address; dbgRequest.Buffer = Buffer; dbgRequest.Request = BufferSize; // // Fill parameters for kldbgdrv ioctl. // kldbg.SysDbgRequest = SysDbgReadVirtual; kldbg.Buffer = &dbgRequest; kldbg.BufferSize = sizeof(SYSDBG_VIRTUAL); iost.Information = 0; iost.Status = 0; status = NtDeviceIoControlFile( g_kdctx.hDevice, NULL, NULL, NULL, &iost, IOCTL_KD_PASS_THROUGH, &kldbg, sizeof(kldbg), &dbgRequest, sizeof(dbgRequest)); if (status == STATUS_PENDING) { status = NtWaitForSingleObject( g_kdctx.hDevice, FALSE, NULL); if (NT_SUCCESS(status)) status = iost.Status; } if (NT_SUCCESS(status)) { if (NumberOfBytesRead) *NumberOfBytesRead = (ULONG)iost.Information; return TRUE; } else { // // We don't need this information in case of error. // if (!NT_ERROR(status)) { if (NumberOfBytesRead) *NumberOfBytesRead = (ULONG)iost.Information; } if (g_kdctx.ShowKdError) kdShowError(BufferSize, status, &iost); else SetLastError(RtlNtStatusToDosError(status)); return FALSE; } } /* * kdInit * * Purpose: * * Extract KLDBGDRV from application resource * */ BOOL kdExtractDriver( _In_ LPCWSTR lpExtractTo, _In_ LPCWSTR lpName, _In_ LPCWSTR lpType ) { HRSRC hResInfo = NULL; HGLOBAL hResData = NULL; PVOID pData; BOOL bResult = FALSE; DWORD dwSize = 0; HANDLE hFile = INVALID_HANDLE_VALUE; hResInfo = FindResource(g_WinObj.hInstance, lpName, lpType); if (hResInfo == NULL) return bResult; dwSize = SizeofResource(g_WinObj.hInstance, hResInfo); if (dwSize == 0) return bResult; hResData = LoadResource(g_WinObj.hInstance, hResInfo); if (hResData == NULL) return bResult; pData = LockResource(hResData); if (pData) { hFile = CreateFile( lpExtractTo, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); if (hFile != INVALID_HANDLE_VALUE) { bResult = WriteFile(hFile, pData, dwSize, &dwSize, NULL); CloseHandle(hFile); } } return bResult; } /* * kdQuerySystemInformation * * Purpose: * * Query required system information and offsets. * */ DWORD WINAPI kdQuerySystemInformation( _In_ PVOID lpParameter ) { BOOL bResult = FALSE; PKLDBGCONTEXT Context = (PKLDBGCONTEXT)lpParameter; PVOID MappedKernel = NULL; PRTL_PROCESS_MODULES miSpace = NULL; WCHAR NtOskrnlFullPathName[MAX_PATH * 2]; do { miSpace = (PRTL_PROCESS_MODULES)supGetSystemInfo(SystemModuleInformation, NULL); if (miSpace == NULL) break; if (miSpace->NumberOfModules == 0) break; Context->NtOsBase = miSpace->Modules[0].ImageBase; //loaded kernel base Context->NtOsSize = miSpace->Modules[0].ImageSize; //loaded kernel size _strcpy(NtOskrnlFullPathName, g_WinObj.szSystemDirectory); _strcat(NtOskrnlFullPathName, TEXT("\\")); MultiByteToWideChar( CP_ACP, 0, (LPCSTR)&miSpace->Modules[0].FullPathName[miSpace->Modules[0].OffsetToFileName], -1, _strend(NtOskrnlFullPathName), MAX_PATH); supHeapFree(miSpace); miSpace = NULL; MappedKernel = LoadLibraryEx( NtOskrnlFullPathName, NULL, DONT_RESOLVE_DLL_REFERENCES); if (MappedKernel == NULL) break; Context->NtOsImageMap = MappedKernel; // // Locate and remember ObHeaderCookie. // if (g_WinObj.osver.dwMajorVersion >= 10) { Context->ObHeaderCookie = ObpFindHeaderCookie(Context); } bResult = TRUE; } while (FALSE); if (miSpace != NULL) { supHeapFree(miSpace); } return bResult; } /* * kdAddressInNtOsImage * * Purpose: * * Test if given address in range of ntoskrnl. * */ BOOL __forceinline kdAddressInNtOsImage( _In_ PVOID Address ) { return IN_REGION(Address, g_kdctx.NtOsBase, g_kdctx.NtOsSize); } /* * kdInit * * Purpose: * * Enable Debug Privilege and open/load KLDBGDRV driver * */ VOID kdInit( _In_ BOOL IsFullAdmin ) { WCHAR szDrvPath[MAX_PATH * 2]; RtlSecureZeroMemory(&g_kdctx, sizeof(g_kdctx)); RtlSecureZeroMemory(&g_SystemCallbacks, sizeof(g_SystemCallbacks)); g_kdctx.ShowKdError = TRUE; g_kdctx.IsFullAdmin = IsFullAdmin; // // Default driver load status. // g_kdctx.drvOpenLoadStatus = ERROR_NOT_CAPABLE; InitializeListHead(&g_kdctx.ObCollection.ListHead); RtlInitializeCriticalSection(&g_kdctx.ListLock); // // Minimum supported client is windows 7 // Query system range start value and if version below Win7 - leave // if ( (g_WinObj.osver.dwMajorVersion < 6) || //any lower other vista ((g_WinObj.osver.dwMajorVersion == 6) && (g_WinObj.osver.dwMinorVersion == 0))//vista ) { return; } // // Query "\\" directory address and remember directory object type index. // ObGetDirectoryObjectAddress( NULL, &g_kdctx.DirectoryRootAddress, &g_kdctx.DirectoryTypeIndex); // // Remember system range start value. // g_kdctx.SystemRangeStart = supQuerySystemRangeStart(); if (g_kdctx.SystemRangeStart == 0) { if (g_NtBuildNumber < 9200) { g_kdctx.SystemRangeStart = MM_SYSTEM_RANGE_START_7; } else { g_kdctx.SystemRangeStart = MM_SYSTEM_RANGE_START_8; } } // // No admin rights, leave. // if (IsFullAdmin == FALSE) return; // // wodbgdrv does not need DEBUG mode. // #ifndef _USE_OWN_DRIVER // // Check if system booted in the debug mode. // if (kdIsDebugBoot() == FALSE) return; #endif // // Test privilege assigned and continue to load/open kldbg driver. // if (supEnablePrivilege(SE_DEBUG_PRIVILEGE, TRUE)) { // // Try to open existing device. // if (scmOpenDevice(KLDBGDRV, &g_kdctx.hDevice, &g_kdctx.drvOpenLoadStatus) == FALSE) { // // No such device exist, construct filepath and check if driver already present. // RtlSecureZeroMemory(szDrvPath, sizeof(szDrvPath)); _strcpy(szDrvPath, g_WinObj.szSystemDirectory); _strcat(szDrvPath, KLDBGDRVSYS); // // If no file exists, extract it to the drivers directory. // if (!PathFileExists(szDrvPath)) { kdExtractDriver(szDrvPath, MAKEINTRESOURCE(IDR_KDBGDRV), L"SYS"); } // // Load service driver and open handle for it. // g_kdctx.drvOpenLoadStatus = ERROR_SUCCESS; g_kdctx.IsOurLoad = scmLoadDeviceDriver(KLDBGDRV, szDrvPath, &g_kdctx.hDevice, &g_kdctx.drvOpenLoadStatus); } } // // Query global variables. // if (g_kdctx.hDevice != NULL) { ObpInitInfoBlockOffsets(); kdQuerySystemInformation(&g_kdctx); } } /* * kdGetInstructionLength * * Purpose: * * Wrapper for hde64_disasm. * */ UCHAR kdGetInstructionLength( _In_ PVOID ptrCode, _Out_ PULONG ptrFlags) { hde64s hs; __try { hde64_disasm((void*)ptrCode, &hs); if (hs.flags & F_ERROR) { *ptrFlags = hs.flags; return 0; } *ptrFlags = hs.flags; return hs.len; } __except (EXCEPTION_EXECUTE_HANDLER) { DbgPrint("GetInstructionLength exception %lx", GetExceptionCode()); return 0; } } /* * kdQueryWin32kApiSetTable * * Purpose: * * Locate address of win32k!Win32kApiSetTable structure. * * N.B. * It would be much easier if MS will export this symbol. * */ ULONG_PTR kdQueryWin32kApiSetTable( _In_ HMODULE hWin32k ) { PBYTE ptrCode = (PBYTE)hWin32k; PVOID SectionBase, SearchPattern; ULONG SectionSize = 0, Index, SearchPatternSize = 0; ULONG_PTR Address = 0; LONG Rel = 0; hde64s hs; __try { // // Locate .text image section as required variable is always in .text. // SectionBase = supLookupImageSectionByName( TEXT_SECTION, TEXT_SECTION_LEGNTH, (PVOID)hWin32k, &SectionSize); if ((SectionBase == 0) || (SectionSize == 0)) return 0; Index = 0; ptrCode = (PBYTE)SectionBase; do { hde64_disasm((void*)(ptrCode + Index), &hs); if (hs.flags & F_ERROR) break; SearchPatternSize = sizeof(Win32kApiSetTableMovPattern); SearchPattern = Win32kApiSetTableMovPattern; // // Locate MOV pattern. // if (hs.len == 3) { SearchPatternSize = sizeof(Win32kApiSetTableMovPattern); SearchPattern = Win32kApiSetTableMovPattern; if (SearchPatternSize == RtlCompareMemory(&ptrCode[Index], SearchPattern, SearchPatternSize)) { Index += hs.len; hde64_disasm((void*)(ptrCode + Index), &hs); if (hs.flags & F_ERROR) break; // // lea reg, Win32kApiSetTable // if (hs.len == 7) { SearchPatternSize = sizeof(Win32kApiSetTableLeaPattern); SearchPattern = Win32kApiSetTableLeaPattern; if (SearchPatternSize == RtlCompareMemory(&ptrCode[Index], SearchPattern, SearchPatternSize)) { Rel = *(PLONG)(ptrCode + Index + (hs.len - 4)); break; } } } } Index += hs.len; } while (Index < SectionSize - 10); if (Rel == 0) return 0; Address = (ULONG_PTR)ptrCode + Index + hs.len + Rel; } __except (EXCEPTION_EXECUTE_HANDLER) { DbgPrint("kdQueryWin32kApiSetTable ex %lx", GetExceptionCode()); } return Address; } /* * kdShutdown * * Purpose: * * Close handle to the driver and unload it if it was loaded by our program, * destroy object list, delete list lock. * This routine called once, during program shutdown. * */ VOID kdShutdown( VOID ) { WCHAR szDrvPath[MAX_PATH * 2]; if (g_kdctx.hDevice == NULL) return; CloseHandle(g_kdctx.hDevice); g_kdctx.hDevice = NULL; ObCollectionDestroy(&g_kdctx.ObCollection); RtlDeleteCriticalSection(&g_kdctx.ListLock); // // Driver was loaded, unload it. // Windbg recreates service and drops file everytime when kernel debug starts. // if (g_kdctx.IsOurLoad) { scmUnloadDeviceDriver(KLDBGDRV, NULL); // // Driver file is no longer needed. // RtlSecureZeroMemory(&szDrvPath, sizeof(szDrvPath)); _strcpy(szDrvPath, g_WinObj.szSystemDirectory); _strcat(szDrvPath, KLDBGDRVSYS); DeleteFile(szDrvPath); } if (g_kdctx.NtOsImageMap) FreeLibrary((HMODULE)g_kdctx.NtOsImageMap); }
25.702514
140
0.54868
[ "object" ]
c5b92c2ce04578aefc83c7afcdae90df4f1be872
38,141
h
C
analytical_engine/core/fragment/arrow_projected_fragment.h
LI-Mingyu/GraphScope-MY
942060983d3f7f8d3a3377467386e27aba285b33
[ "Apache-2.0" ]
2
2021-04-07T07:57:13.000Z
2021-11-19T09:44:01.000Z
analytical_engine/core/fragment/arrow_projected_fragment.h
LI-Mingyu/GraphScope-MY
942060983d3f7f8d3a3377467386e27aba285b33
[ "Apache-2.0" ]
16
2021-12-22T09:19:25.000Z
2022-03-29T02:43:34.000Z
analytical_engine/core/fragment/arrow_projected_fragment.h
LI-Mingyu/GraphScope-MY
942060983d3f7f8d3a3377467386e27aba285b33
[ "Apache-2.0" ]
2
2022-01-25T10:16:51.000Z
2022-02-07T11:51:20.000Z
/** Copyright 2020 Alibaba Group Holding Limited. * * 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 ANALYTICAL_ENGINE_CORE_FRAGMENT_ARROW_PROJECTED_FRAGMENT_H_ #define ANALYTICAL_ENGINE_CORE_FRAGMENT_ARROW_PROJECTED_FRAGMENT_H_ #include <limits> #include <memory> #include <set> #include <string> #include <utility> #include <vector> #include "arrow/array.h" #include "boost/lexical_cast.hpp" #include "vineyard/basic/ds/arrow_utils.h" #include "vineyard/common/util/version.h" #include "vineyard/graph/fragment/arrow_fragment.h" #include "vineyard/graph/vertex_map/arrow_vertex_map.h" #include "core/context/context_protocols.h" #include "core/fragment/arrow_projected_fragment_base.h" #include "core/vertex_map/arrow_projected_vertex_map.h" namespace gs { namespace arrow_projected_fragment_impl { template <typename T> class TypedArray { public: using value_type = T; TypedArray() : buffer_(NULL) {} explicit TypedArray(std::shared_ptr<arrow::Array> array) { if (array == nullptr) { buffer_ = NULL; } else { buffer_ = std::dynamic_pointer_cast< typename vineyard::ConvertToArrowType<T>::ArrayType>(array) ->raw_values(); } } void Init(std::shared_ptr<arrow::Array> array) { if (array == nullptr) { buffer_ = NULL; } else { buffer_ = std::dynamic_pointer_cast< typename vineyard::ConvertToArrowType<T>::ArrayType>(array) ->raw_values(); } } value_type operator[](size_t loc) const { return buffer_[loc]; } private: const T* buffer_; }; template <> class TypedArray<grape::EmptyType> { public: using value_type = grape::EmptyType; TypedArray() {} explicit TypedArray(std::shared_ptr<arrow::Array>) {} void Init(std::shared_ptr<arrow::Array>) {} value_type operator[](size_t) const { return {}; } }; template <> struct TypedArray<std::string> { public: using value_type = arrow::util::string_view; TypedArray() : array_(NULL) {} explicit TypedArray(std::shared_ptr<arrow::Array> array) { if (array == nullptr) { array_ = NULL; } else { array_ = std::dynamic_pointer_cast<arrow::LargeStringArray>(array).get(); } } void Init(std::shared_ptr<arrow::Array> array) { if (array == nullptr) { array_ = NULL; } else { array_ = std::dynamic_pointer_cast<arrow::LargeStringArray>(array).get(); } } value_type operator[](size_t loc) const { return array_->GetView(loc); } private: arrow::LargeStringArray* array_; }; /** * @brief This is the internal representation of a neighbor vertex * * @tparam VID_T VID type * @tparam EID_T Edge id type * @tparam EDATA_T Edge data type */ template <typename VID_T, typename EID_T, typename EDATA_T> class Nbr { using vid_t = VID_T; using eid_t = EID_T; using nbr_unit_t = vineyard::property_graph_utils::NbrUnit<VID_T, EID_T>; public: Nbr(const nbr_unit_t* nbr, TypedArray<EDATA_T> edata_array) : nbr_(nbr), edata_array_(edata_array) {} Nbr(const Nbr& rhs) : nbr_(rhs.nbr_), edata_array_(rhs.edata_array_) {} grape::Vertex<vid_t> neighbor() const { return grape::Vertex<vid_t>(nbr_->vid); } grape::Vertex<vid_t> get_neighbor() const { return grape::Vertex<vid_t>(nbr_->vid); } eid_t edge_id() const { return nbr_->eid; } typename TypedArray<EDATA_T>::value_type data() const { return edata_array_[nbr_->eid]; } typename TypedArray<EDATA_T>::value_type get_data() const { return edata_array_[nbr_->eid]; } inline const Nbr& operator++() const { ++nbr_; return *this; } inline Nbr operator++(int) const { Nbr ret(*this); ++ret; return ret; } inline const Nbr& operator--() const { --nbr_; return *this; } inline Nbr operator--(int) const { Nbr ret(*this); --ret; return ret; } inline bool operator==(const Nbr& rhs) const { return nbr_ == rhs.nbr_; } inline bool operator!=(const Nbr& rhs) const { return nbr_ != rhs.nbr_; } inline bool operator<(const Nbr& rhs) const { return nbr_ < rhs.nbr_; } inline const Nbr& operator*() const { return *this; } inline const Nbr* operator->() const { return this; } private: const mutable nbr_unit_t* nbr_; TypedArray<EDATA_T> edata_array_; }; /** * @brief This is the specialized Nbr for grape::EmptyType data type * @tparam VID_T * @tparam EID_T */ template <typename VID_T, typename EID_T> class Nbr<VID_T, EID_T, grape::EmptyType> { using vid_t = VID_T; using eid_t = EID_T; using nbr_unit_t = vineyard::property_graph_utils::NbrUnit<VID_T, EID_T>; public: explicit Nbr(const nbr_unit_t* nbr) : nbr_(nbr) {} Nbr(const Nbr& rhs) : nbr_(rhs.nbr_) {} grape::Vertex<vid_t> neighbor() const { return grape::Vertex<vid_t>(nbr_->vid); } grape::Vertex<vid_t> get_neighbor() const { return grape::Vertex<vid_t>(nbr_->vid); } eid_t edge_id() const { return nbr_->eid; } grape::EmptyType data() const { return grape::EmptyType(); } grape::EmptyType get_data() const { return grape::EmptyType(); } inline const Nbr& operator++() const { ++nbr_; return *this; } inline Nbr operator++(int) const { Nbr ret(*this); ++ret; return ret; } inline const Nbr& operator--() const { --nbr_; return *this; } inline Nbr operator--(int) const { Nbr ret(*this); --ret; return ret; } inline bool operator==(const Nbr& rhs) const { return nbr_ == rhs.nbr_; } inline bool operator!=(const Nbr& rhs) const { return nbr_ != rhs.nbr_; } inline bool operator<(const Nbr& rhs) const { return nbr_ < rhs.nbr_; } inline const Nbr& operator*() const { return *this; } inline const Nbr* operator->() const { return this; } private: const mutable nbr_unit_t* nbr_; }; /** * @brief This is the internal representation of neighbors for a vertex. * * @tparam VID_T VID type * @tparam EID_T Edge id type * @tparam EDATA_T Edge data type */ template <typename VID_T, typename EID_T, typename EDATA_T> class AdjList { using vid_t = VID_T; using eid_t = EID_T; using nbr_unit_t = vineyard::property_graph_utils::NbrUnit<vid_t, eid_t>; public: AdjList() : begin_(NULL), end_(NULL) {} AdjList(const nbr_unit_t* begin, const nbr_unit_t* end, TypedArray<EDATA_T> edata_array) : begin_(begin), end_(end), edata_array_(edata_array) {} Nbr<VID_T, EID_T, EDATA_T> begin() const { return Nbr<VID_T, EID_T, EDATA_T>(begin_, edata_array_); } Nbr<VID_T, EID_T, EDATA_T> end() const { return Nbr<VID_T, EID_T, EDATA_T>(end_, edata_array_); } size_t Size() const { return end_ - begin_; } inline bool Empty() const { return end_ == begin_; } inline bool NotEmpty() const { return !Empty(); } private: const nbr_unit_t* begin_; const nbr_unit_t* end_; TypedArray<EDATA_T> edata_array_; }; template <typename VID_T, typename EID_T> class AdjList<VID_T, EID_T, grape::EmptyType> { using vid_t = VID_T; using eid_t = EID_T; using nbr_unit_t = vineyard::property_graph_utils::NbrUnit<vid_t, eid_t>; public: AdjList() : begin_(NULL), end_(NULL) {} AdjList(const nbr_unit_t* begin, const nbr_unit_t* end, TypedArray<grape::EmptyType>) : begin_(begin), end_(end) {} Nbr<VID_T, EID_T, grape::EmptyType> begin() const { return Nbr<VID_T, EID_T, grape::EmptyType>(begin_); } Nbr<VID_T, EID_T, grape::EmptyType> end() const { return Nbr<VID_T, EID_T, grape::EmptyType>(end_); } size_t Size() const { return end_ - begin_; } inline bool Empty() const { return end_ == begin_; } inline bool NotEmpty() const { return !Empty(); } private: const nbr_unit_t* begin_; const nbr_unit_t* end_; }; } // namespace arrow_projected_fragment_impl /** * @brief This class represents the fragment projected from ArrowFragment which * contains only one vertex label and edge label. The fragment has no label and * property. * * @tparam OID_T OID type * @tparam VID_T VID type * @tparam VDATA_T The type of data attached with the vertex * @tparam EDATA_T The type of data attached with the edge */ template <typename OID_T, typename VID_T, typename VDATA_T, typename EDATA_T> class ArrowProjectedFragment : public ArrowProjectedFragmentBase, public vineyard::BareRegistered< ArrowProjectedFragment<OID_T, VID_T, VDATA_T, EDATA_T>> { public: using oid_t = OID_T; using vid_t = VID_T; using internal_oid_t = typename vineyard::InternalType<oid_t>::type; using eid_t = vineyard::property_graph_types::EID_TYPE; using vertex_range_t = grape::VertexRange<vid_t>; using vertex_t = grape::Vertex<vid_t>; using nbr_t = arrow_projected_fragment_impl::Nbr<vid_t, eid_t, EDATA_T>; using nbr_unit_t = vineyard::property_graph_utils::NbrUnit<vid_t, eid_t>; using adj_list_t = arrow_projected_fragment_impl::AdjList<vid_t, eid_t, EDATA_T>; using const_adj_list_t = arrow_projected_fragment_impl::AdjList<vid_t, eid_t, EDATA_T>; using vertex_map_t = ArrowProjectedVertexMap<internal_oid_t, vid_t>; using label_id_t = vineyard::property_graph_types::LABEL_ID_TYPE; using prop_id_t = vineyard::property_graph_types::PROP_ID_TYPE; using vdata_t = VDATA_T; using edata_t = EDATA_T; using property_graph_t = vineyard::ArrowFragment<oid_t, vid_t>; using vid_array_t = typename vineyard::ConvertToArrowType<vid_t>::ArrayType; using eid_array_t = typename vineyard::ConvertToArrowType<eid_t>::ArrayType; template <typename DATA_T> using vertex_array_t = grape::VertexArray<DATA_T, vid_t>; static constexpr grape::LoadStrategy load_strategy = grape::LoadStrategy::kBothOutIn; #if defined(VINEYARD_VERSION) && defined(VINEYARD_VERSION_MAJOR) #if VINEYARD_VERSION >= 2007 static std::unique_ptr<vineyard::Object> Create() __attribute__((used)) { return std::static_pointer_cast<vineyard::Object>( std::unique_ptr<ArrowProjectedFragment<oid_t, vid_t, vdata_t, edata_t>>{ new ArrowProjectedFragment<oid_t, vid_t, vdata_t, edata_t>()}); } #endif #else static std::shared_ptr<vineyard::Object> Create() __attribute__((used)) { return std::static_pointer_cast<vineyard::Object>( std::make_shared< ArrowProjectedFragment<oid_t, vid_t, vdata_t, edata_t>>()); } #endif ~ArrowProjectedFragment() {} static std::shared_ptr<ArrowProjectedFragment<oid_t, vid_t, vdata_t, edata_t>> Project(std::shared_ptr<vineyard::ArrowFragment<oid_t, vid_t>> fragment, const std::string& v_label_str, const std::string& v_prop_str, const std::string& e_label_str, const std::string& e_prop_str) { label_id_t v_label = boost::lexical_cast<label_id_t>(v_label_str); label_id_t e_label = boost::lexical_cast<label_id_t>(e_label_str); prop_id_t v_prop = boost::lexical_cast<label_id_t>(v_prop_str); prop_id_t e_prop = boost::lexical_cast<label_id_t>(e_prop_str); vineyard::Client& client = *dynamic_cast<vineyard::Client*>(fragment->meta().GetClient()); std::shared_ptr<vertex_map_t> vm = vertex_map_t::Project(fragment->vm_ptr_, v_label); vineyard::ObjectMeta meta; if (v_prop == -1) { if (!std::is_same<vdata_t, grape::EmptyType>::value) { LOG(ERROR) << "Vertex data type of projected fragment is not " "consistent with property."; return nullptr; } } else { if (!fragment->vertex_tables_[v_label]->field(v_prop)->type()->Equals( vineyard::ConvertToArrowType<vdata_t>::TypeValue())) { LOG(ERROR) << "Vertex data type of projected fragment is not " "consistent with property."; return nullptr; } } if (e_prop == -1) { if (!std::is_same<edata_t, grape::EmptyType>::value) { LOG(ERROR) << "Edge data type of projected fragment is not " "consistent with property."; return nullptr; } } else { if (!fragment->edge_tables_[e_label]->field(e_prop)->type()->Equals( vineyard::ConvertToArrowType<edata_t>::TypeValue())) { LOG(ERROR) << "Edge data type of projected fragment is not " "consistent with property."; return nullptr; } } meta.SetTypeName( type_name<ArrowProjectedFragment<oid_t, vid_t, vdata_t, edata_t>>()); meta.AddKeyValue("projected_v_label", v_label); meta.AddKeyValue("projected_v_property", v_prop); meta.AddKeyValue("projected_e_label", e_label); meta.AddKeyValue("projected_e_property", e_prop); meta.AddMember("arrow_fragment", fragment->meta()); meta.AddMember("arrow_projected_vertex_map", vm->meta()); std::shared_ptr<vineyard::NumericArray<int64_t>> ie_offsets_begin, ie_offsets_end; size_t nbytes = 0; if (fragment->directed()) { std::shared_ptr<arrow::Int64Array> ie_offsets_begin_arrow, ie_offsets_end_arrow; selectEdgeByNeighborLabel(fragment, v_label, fragment->ie_lists_[v_label][e_label], fragment->ie_offsets_lists_[v_label][e_label], ie_offsets_begin_arrow, ie_offsets_end_arrow); vineyard::NumericArrayBuilder<int64_t> ie_offsets_begin_builder( client, ie_offsets_begin_arrow); ie_offsets_begin = std::dynamic_pointer_cast<vineyard::NumericArray<int64_t>>( ie_offsets_begin_builder.Seal(client)); vineyard::NumericArrayBuilder<int64_t> ie_offsets_end_builder( client, ie_offsets_end_arrow); ie_offsets_end = std::dynamic_pointer_cast<vineyard::NumericArray<int64_t>>( ie_offsets_end_builder.Seal(client)); nbytes += ie_offsets_begin->nbytes(); nbytes += ie_offsets_end->nbytes(); } std::shared_ptr<vineyard::NumericArray<int64_t>> oe_offsets_begin, oe_offsets_end; { std::shared_ptr<arrow::Int64Array> oe_offsets_begin_arrow, oe_offsets_end_arrow; selectEdgeByNeighborLabel(fragment, v_label, fragment->oe_lists_[v_label][e_label], fragment->oe_offsets_lists_[v_label][e_label], oe_offsets_begin_arrow, oe_offsets_end_arrow); vineyard::NumericArrayBuilder<int64_t> oe_offsets_begin_builder( client, oe_offsets_begin_arrow); oe_offsets_begin = std::dynamic_pointer_cast<vineyard::NumericArray<int64_t>>( oe_offsets_begin_builder.Seal(client)); vineyard::NumericArrayBuilder<int64_t> oe_offsets_end_builder( client, oe_offsets_end_arrow); oe_offsets_end = std::dynamic_pointer_cast<vineyard::NumericArray<int64_t>>( oe_offsets_end_builder.Seal(client)); nbytes += oe_offsets_begin->nbytes(); nbytes += oe_offsets_end->nbytes(); } if (fragment->directed()) { meta.AddMember("ie_offsets_begin", ie_offsets_begin->meta()); meta.AddMember("ie_offsets_end", ie_offsets_end->meta()); } meta.AddMember("oe_offsets_begin", oe_offsets_begin->meta()); meta.AddMember("oe_offsets_end", oe_offsets_end->meta()); meta.SetNBytes(nbytes); vineyard::ObjectID id; VINEYARD_CHECK_OK(client.CreateMetaData(meta, id)); return std::dynamic_pointer_cast< ArrowProjectedFragment<oid_t, vid_t, vdata_t, edata_t>>( client.GetObject(id)); } void Construct(const vineyard::ObjectMeta& meta) override { this->meta_ = meta; this->id_ = meta.GetId(); vertex_label_ = meta.GetKeyValue<label_id_t>("projected_v_label"); edge_label_ = meta.GetKeyValue<label_id_t>("projected_e_label"); vertex_prop_ = meta.GetKeyValue<prop_id_t>("projected_v_property"); edge_prop_ = meta.GetKeyValue<prop_id_t>("projected_e_property"); fragment_ = std::make_shared<vineyard::ArrowFragment<oid_t, vid_t>>(); fragment_->Construct(meta.GetMemberMeta("arrow_fragment")); fid_ = fragment_->fid_; fnum_ = fragment_->fnum_; directed_ = fragment_->directed_; if (directed_) { vineyard::NumericArray<int64_t> ie_offsets_begin; ie_offsets_begin.Construct(meta.GetMemberMeta("ie_offsets_begin")); ie_offsets_begin_ = ie_offsets_begin.GetArray(); } if (directed_) { vineyard::NumericArray<int64_t> ie_offsets_end; ie_offsets_end.Construct(meta.GetMemberMeta("ie_offsets_end")); ie_offsets_end_ = ie_offsets_end.GetArray(); } { vineyard::NumericArray<int64_t> oe_offsets_begin; oe_offsets_begin.Construct(meta.GetMemberMeta("oe_offsets_begin")); oe_offsets_begin_ = oe_offsets_begin.GetArray(); } { vineyard::NumericArray<int64_t> oe_offsets_end; oe_offsets_end.Construct(meta.GetMemberMeta("oe_offsets_end")); oe_offsets_end_ = oe_offsets_end.GetArray(); } inner_vertices_ = fragment_->InnerVertices(vertex_label_); outer_vertices_ = fragment_->OuterVertices(vertex_label_); vertices_ = fragment_->Vertices(vertex_label_); ivnum_ = static_cast<vid_t>(inner_vertices_.size()); ovnum_ = static_cast<vid_t>(outer_vertices_.size()); tvnum_ = static_cast<vid_t>(vertices_.size()); if (ivnum_ > 0) { ienum_ = static_cast<size_t>(oe_offsets_end_->Value(ivnum_ - 1) - oe_offsets_begin_->Value(0)); if (directed_) { ienum_ += static_cast<size_t>(ie_offsets_end_->Value(ivnum_ - 1) - ie_offsets_begin_->Value(0)); } } if (ovnum_ > 0) { oenum_ = static_cast<size_t>(oe_offsets_end_->Value(tvnum_ - 1) - oe_offsets_begin_->Value(ivnum_)); if (directed_) { oenum_ += static_cast<size_t>(ie_offsets_end_->Value(tvnum_ - 1) - ie_offsets_begin_->Value(ivnum_)); } } vertex_label_num_ = fragment_->vertex_label_num_; edge_label_num_ = fragment_->edge_label_num_; if (fragment_->vertex_tables_[vertex_label_]->num_rows() == 0) { vertex_data_array_ = nullptr; } else { vertex_data_array_ = (vertex_prop_ == -1) ? nullptr : (fragment_->vertex_tables_[vertex_label_] ->column(vertex_prop_) ->chunk(0)); } ovgid_list_ = fragment_->ovgid_lists_[vertex_label_]; ovg2l_map_ = fragment_->ovg2l_maps_[vertex_label_]; if (fragment_->edge_tables_[edge_label_]->num_rows() == 0) { edge_data_array_ = nullptr; } else { edge_data_array_ = (edge_prop_ == -1) ? nullptr : (fragment_->edge_tables_[edge_label_] ->column(edge_prop_) ->chunk(0)); } if (directed_) { ie_ = fragment_->ie_lists_[vertex_label_][edge_label_]; } oe_ = fragment_->oe_lists_[vertex_label_][edge_label_]; vm_ptr_ = std::make_shared<vertex_map_t>(); vm_ptr_->Construct(meta.GetMemberMeta("arrow_projected_vertex_map")); vid_parser_.Init(fnum_, vertex_label_num_); initPointers(); } void PrepareToRunApp(grape::MessageStrategy strategy, bool need_split_edges) { if (strategy == grape::MessageStrategy::kAlongEdgeToOuterVertex) { initDestFidList(true, true, iodst_, iodoffset_); } else if (strategy == grape::MessageStrategy::kAlongIncomingEdgeToOuterVertex) { initDestFidList(true, false, idst_, idoffset_); } else if (strategy == grape::MessageStrategy::kAlongOutgoingEdgeToOuterVertex) { initDestFidList(false, true, odst_, odoffset_); } if (need_split_edges) { ie_spliters_ptr_.clear(); oe_spliters_ptr_.clear(); if (directed_) { initEdgeSpliters(ie_, ie_offsets_begin_, ie_offsets_end_, ie_spliters_); initEdgeSpliters(oe_, oe_offsets_begin_, oe_offsets_end_, oe_spliters_); for (auto& vec : ie_spliters_) { ie_spliters_ptr_.push_back(vec.data()); } for (auto& vec : oe_spliters_) { oe_spliters_ptr_.push_back(vec.data()); } } else { initEdgeSpliters(oe_, oe_offsets_begin_, oe_offsets_end_, oe_spliters_); for (auto& vec : oe_spliters_) { ie_spliters_ptr_.push_back(vec.data()); oe_spliters_ptr_.push_back(vec.data()); } } } initOuterVertexRanges(); initMirrorInfo(); } inline fid_t fid() const { return fid_; } inline fid_t fnum() const { return fnum_; } inline vertex_range_t Vertices() const { return vertices_; } inline vertex_range_t InnerVertices() const { return inner_vertices_; } inline vertex_range_t OuterVertices() const { return outer_vertices_; } inline vertex_range_t OuterVertices(fid_t fid) const { return vertex_range_t(outer_vertex_offsets_[fid], outer_vertex_offsets_[fid + 1]); } inline const std::vector<vertex_t>& MirrorVertices(fid_t fid) const { return mirrors_of_frag_[fid]; } inline bool GetVertex(const oid_t& oid, vertex_t& v) const { vid_t gid; if (vm_ptr_->GetGid(internal_oid_t(oid), gid)) { return (vid_parser_.GetFid(gid) == fid()) ? InnerVertexGid2Vertex(gid, v) : OuterVertexGid2Vertex(gid, v); } else { return false; } } inline oid_t GetId(const vertex_t& v) const { return IsInnerVertex(v) ? GetInnerVertexId(v) : GetOuterVertexId(v); } inline fid_t GetFragId(const vertex_t& v) const { return IsInnerVertex(v) ? fid_ : vid_parser_.GetFid(GetOuterVertexGid(v)); } inline typename arrow_projected_fragment_impl::TypedArray<VDATA_T>::value_type GetData(const vertex_t& v) const { return vertex_data_array_accessor_[vid_parser_.GetOffset(v.GetValue())]; } inline bool Gid2Vertex(const vid_t& gid, vertex_t& v) const { return (vid_parser_.GetFid(gid) == fid_) ? InnerVertexGid2Vertex(gid, v) : OuterVertexGid2Vertex(gid, v); } inline vid_t Vertex2Gid(const vertex_t& v) const { return IsInnerVertex(v) ? GetInnerVertexGid(v) : GetOuterVertexGid(v); } inline vid_t GetInnerVerticesNum() const { return ivnum_; } inline vid_t GetOuterVerticesNum() const { return ovnum_; } inline vid_t GetVerticesNum() const { return tvnum_; } inline size_t GetEdgeNum() const { return ienum_ + oenum_; } inline size_t GetTotalVerticesNum() const { return vm_ptr_->GetTotalVerticesNum(); } inline bool IsInnerVertex(const vertex_t& v) const { return (vid_parser_.GetOffset(v.GetValue()) < static_cast<int64_t>(ivnum_)); } inline bool IsOuterVertex(const vertex_t& v) const { return ( vid_parser_.GetOffset(v.GetValue()) < static_cast<int64_t>(tvnum_) && vid_parser_.GetOffset(v.GetValue()) >= static_cast<int64_t>(ivnum_)); } inline bool GetInnerVertex(const oid_t& oid, vertex_t& v) const { vid_t gid; if (vm_ptr_->GetGid(internal_oid_t(oid), gid)) { if (vid_parser_.GetFid(gid) == fid_) { v.SetValue(vid_parser_.GetLid(gid)); return true; } } return false; } inline bool GetOuterVertex(const oid_t& oid, vertex_t& v) const { vid_t gid; if (vm_ptr_->GetGid(internal_oid_t(oid), gid)) { return OuterVertexGid2Vertex(gid, v); } else { return false; } } inline oid_t GetInnerVertexId(const vertex_t& v) const { internal_oid_t internal_oid; CHECK(vm_ptr_->GetOid( vid_parser_.GenerateId(fid_, vid_parser_.GetLabelId(v.GetValue()), vid_parser_.GetOffset(v.GetValue())), internal_oid)); return oid_t(internal_oid); } inline oid_t GetOuterVertexId(const vertex_t& v) const { vid_t gid = GetOuterVertexGid(v); internal_oid_t internal_oid; CHECK(vm_ptr_->GetOid(gid, internal_oid)); return oid_t(internal_oid); } inline oid_t Gid2Oid(const vid_t& gid) const { internal_oid_t internal_oid; CHECK(vm_ptr_->GetOid(gid, internal_oid)); return oid_t(internal_oid); } inline bool Oid2Gid(const oid_t& oid, vid_t& gid) const { return vm_ptr_->GetGid(internal_oid_t(oid), gid); } // For Java use, can not use Oid2Gid(const oid_t & oid, vid_t & gid) since // Java can not pass vid_t by reference. inline vid_t Oid2Gid(const oid_t& oid) const { vid_t gid; if (vm_ptr_->GetGid(internal_oid_t(oid), gid)) { return gid; } return std::numeric_limits<vid_t>::max(); } inline bool InnerVertexGid2Vertex(const vid_t& gid, vertex_t& v) const { v.SetValue(vid_parser_.GetLid(gid)); return true; } inline bool OuterVertexGid2Vertex(const vid_t& gid, vertex_t& v) const { auto iter = ovg2l_map_->find(gid); if (iter != ovg2l_map_->end()) { v.SetValue(iter->second); return true; } else { return false; } } inline vid_t GetOuterVertexGid(const vertex_t& v) const { assert(vid_parser_.GetLabelId(v.GetValue()) == vertex_label_); return ovgid_list_ptr_[vid_parser_.GetOffset(v.GetValue()) - ivnum_]; } inline vid_t GetInnerVertexGid(const vertex_t& v) const { return vid_parser_.GenerateId(fid_, vid_parser_.GetLabelId(v.GetValue()), vid_parser_.GetOffset(v.GetValue())); } inline adj_list_t GetIncomingAdjList(const vertex_t& v) const { int64_t offset = vid_parser_.GetOffset(v.GetValue()); return adj_list_t(&ie_ptr_[ie_offsets_begin_ptr_[offset]], &ie_ptr_[ie_offsets_end_ptr_[offset]], edge_data_array_accessor_); } inline adj_list_t GetOutgoingAdjList(const vertex_t& v) const { int64_t offset = vid_parser_.GetOffset(v.GetValue()); return adj_list_t(&oe_ptr_[oe_offsets_begin_ptr_[offset]], &oe_ptr_[oe_offsets_end_ptr_[offset]], edge_data_array_accessor_); } inline adj_list_t GetIncomingInnerVertexAdjList(const vertex_t& v) const { int64_t offset = vid_parser_.GetOffset(v.GetValue()); return adj_list_t(&ie_ptr_[ie_offsets_begin_ptr_[offset]], &ie_ptr_[offset < static_cast<int64_t>(ivnum_) ? ie_spliters_ptr_[0][offset] : ie_offsets_end_ptr_[offset]], edge_data_array_accessor_); } inline adj_list_t GetOutgoingInnerVertexAdjList(const vertex_t& v) const { int64_t offset = vid_parser_.GetOffset(v.GetValue()); return adj_list_t(&oe_ptr_[oe_offsets_begin_ptr_[offset]], &oe_ptr_[offset < static_cast<int64_t>(ivnum_) ? oe_spliters_ptr_[0][offset] : oe_offsets_end_ptr_[offset]], edge_data_array_accessor_); } inline adj_list_t GetIncomingOuterVertexAdjList(const vertex_t& v) const { int64_t offset = vid_parser_.GetOffset(v.GetValue()); return offset < static_cast<int64_t>(ivnum_) ? adj_list_t(&ie_ptr_[ie_spliters_ptr_[0][offset]], &ie_ptr_[ie_offsets_end_ptr_[offset]], edge_data_array_accessor_) : adj_list_t(); } inline adj_list_t GetOutgoingOuterVertexAdjList(const vertex_t& v) const { int64_t offset = vid_parser_.GetOffset(v.GetValue()); return offset < static_cast<int64_t>(ivnum_) ? adj_list_t(&oe_ptr_[oe_spliters_ptr_[0][offset]], &oe_ptr_[oe_offsets_end_ptr_[offset]], edge_data_array_accessor_) : adj_list_t(); } inline adj_list_t GetIncomingAdjList(const vertex_t& v, fid_t src_fid) const { int64_t offset = vid_parser_.GetOffset(v.GetValue()); return offset < static_cast<int64_t>(ivnum_) ? adj_list_t(&ie_ptr_[ie_spliters_ptr_[src_fid][offset]], &ie_ptr_[ie_spliters_ptr_[src_fid + 1][offset]], edge_data_array_accessor_) : (src_fid == fid_ ? GetIncomingAdjList(v) : adj_list_t()); } inline adj_list_t GetOutgoingAdjList(const vertex_t& v, fid_t dst_fid) const { int64_t offset = vid_parser_.GetOffset(v.GetValue()); return offset < static_cast<int64_t>(ivnum_) ? adj_list_t(&oe_ptr_[oe_spliters_ptr_[dst_fid][offset]], &oe_ptr_[oe_spliters_ptr_[dst_fid + 1][offset]], edge_data_array_accessor_) : (dst_fid == fid_ ? GetOutgoingAdjList(v) : adj_list_t()); } inline int GetLocalOutDegree(const vertex_t& v) const { return GetOutgoingAdjList(v).Size(); } inline int GetLocalInDegree(const vertex_t& v) const { return GetIncomingAdjList(v).Size(); } inline grape::DestList IEDests(const vertex_t& v) const { int64_t offset = vid_parser_.GetOffset(v.GetValue()); assert(offset < static_cast<int64_t>(ivnum_)); return grape::DestList(idoffset_[offset], idoffset_[offset + 1]); } inline grape::DestList OEDests(const vertex_t& v) const { int64_t offset = vid_parser_.GetOffset(v.GetValue()); assert(offset < static_cast<int64_t>(ivnum_)); return grape::DestList(odoffset_[offset], odoffset_[offset + 1]); } inline grape::DestList IOEDests(const vertex_t& v) const { int64_t offset = vid_parser_.GetOffset(v.GetValue()); assert(offset < static_cast<int64_t>(ivnum_)); return grape::DestList(iodoffset_[offset], iodoffset_[offset + 1]); } inline bool directed() const { return directed_; } private: inline static std::pair<int64_t, int64_t> getRangeOfLabel( std::shared_ptr<property_graph_t> fragment, label_id_t v_label, std::shared_ptr<arrow::FixedSizeBinaryArray> nbr_list, int64_t begin, int64_t end) { int64_t i, j; for (i = begin; i != end; ++i) { const nbr_unit_t* ptr = reinterpret_cast<const nbr_unit_t*>(nbr_list->GetValue(i)); if (fragment->vid_parser_.GetLabelId(ptr->vid) == v_label) { break; } } for (j = i; j != end; ++j) { const nbr_unit_t* ptr = reinterpret_cast<const nbr_unit_t*>(nbr_list->GetValue(j)); if (fragment->vid_parser_.GetLabelId(ptr->vid) != v_label) { break; } } return std::make_pair(i, j); } static bl::result<void> selectEdgeByNeighborLabel( std::shared_ptr<property_graph_t> fragment, label_id_t v_label, std::shared_ptr<arrow::FixedSizeBinaryArray> nbr_list, std::shared_ptr<arrow::Int64Array> offsets, std::shared_ptr<arrow::Int64Array>& begins, std::shared_ptr<arrow::Int64Array>& ends) { arrow::Int64Builder begins_builder, ends_builder; vid_t tvnum = fragment->tvnums_[v_label]; for (vid_t i = 0; i != tvnum; ++i) { auto ret = getRangeOfLabel(fragment, v_label, nbr_list, offsets->Value(i), offsets->Value(i + 1)); ARROW_OK_OR_RAISE(begins_builder.Append(ret.first)); ARROW_OK_OR_RAISE(ends_builder.Append(ret.second)); } ARROW_OK_OR_RAISE(begins_builder.Finish(&begins)); ARROW_OK_OR_RAISE(ends_builder.Finish(&ends)); return {}; } void initDestFidList(bool in_edge, bool out_edge, std::vector<fid_t>& fid_list, std::vector<fid_t*>& fid_list_offset) { if (!fid_list_offset.empty()) { return; } fid_list_offset.resize(ivnum_ + 1, NULL); std::set<fid_t> dstset; std::vector<int> id_num(ivnum_, 0); vertex_t v = inner_vertices_.begin(); for (vid_t i = 0; i < ivnum_; ++i) { dstset.clear(); if (in_edge) { auto es = GetIncomingAdjList(v); for (auto& e : es) { fid_t f = GetFragId(e.neighbor()); if (f != fid_) { dstset.insert(f); } } } if (out_edge) { auto es = GetOutgoingAdjList(v); for (auto& e : es) { fid_t f = GetFragId(e.neighbor()); if (f != fid_) { dstset.insert(f); } } } id_num[i] = dstset.size(); for (auto fid : dstset) { fid_list.push_back(fid); } ++v; } fid_list.shrink_to_fit(); fid_list_offset[0] = fid_list.data(); for (vid_t i = 0; i < ivnum_; ++i) { fid_list_offset[i + 1] = fid_list_offset[i] + id_num[i]; } } void initEdgeSpliters(std::shared_ptr<arrow::FixedSizeBinaryArray> edge_list, std::shared_ptr<arrow::Int64Array> offsets_begin, std::shared_ptr<arrow::Int64Array> offsets_end, std::vector<std::vector<int64_t>>& spliters) { if (!spliters.empty()) { return; } spliters.resize(fnum_ + 1); for (auto& vec : spliters) { vec.resize(ivnum_); } std::vector<int> frag_count; for (vid_t i = 0; i < ivnum_; ++i) { frag_count.clear(); frag_count.resize(fnum_, 0); int64_t begin = offsets_begin->Value(i); int64_t end = offsets_end->Value(i); for (int64_t j = begin; j != end; ++j) { const nbr_unit_t* nbr_ptr = reinterpret_cast<const nbr_unit_t*>(edge_list->GetValue(j)); vertex_t u(nbr_ptr->vid); fid_t u_fid = GetFragId(u); ++frag_count[u_fid]; } begin += frag_count[fid_]; frag_count[fid_] = 0; spliters[0][i] = begin; for (fid_t j = 0; j < fnum_; ++j) { begin += frag_count[j]; spliters[j + 1][i] = begin; } CHECK_EQ(begin, end); } } void initOuterVertexRanges() { if (!outer_vertex_offsets_.empty()) { return; } std::vector<vid_t> outer_vnum(fnum_, 0); for (auto v : outer_vertices_) { ++outer_vnum[GetFragId(v)]; } CHECK_EQ(outer_vnum[fid_], 0); outer_vertex_offsets_.resize(fnum_ + 1); outer_vertex_offsets_[0] = outer_vertices_.begin().GetValue(); for (fid_t i = 0; i < fnum_; ++i) { outer_vertex_offsets_[i + 1] = outer_vertex_offsets_[i] + outer_vnum[i]; } CHECK_EQ(outer_vertex_offsets_[fnum_], outer_vertices_.end().GetValue()); } void initMirrorInfo() { if (!mirrors_of_frag_.empty()) { return; } mirrors_of_frag_.resize(fnum_); std::vector<bool> bm(fnum_, false); for (auto v : inner_vertices_) { auto es = GetOutgoingAdjList(v); for (auto& e : es) { fid_t fid = GetFragId(e.get_neighbor()); bm[fid] = true; } es = GetIncomingAdjList(v); for (auto& e : es) { fid_t fid = GetFragId(e.get_neighbor()); bm[fid] = true; } for (fid_t i = 0; i != fnum_; ++i) { if ((i != fid_) && bm[i]) { mirrors_of_frag_[i].push_back(v); bm[i] = false; } } } } void initPointers() { if (directed_) { ie_offsets_begin_ptr_ = ie_offsets_begin_->raw_values(); ie_offsets_end_ptr_ = ie_offsets_end_->raw_values(); } else { ie_offsets_begin_ptr_ = oe_offsets_begin_->raw_values(); ie_offsets_end_ptr_ = oe_offsets_end_->raw_values(); } oe_offsets_begin_ptr_ = oe_offsets_begin_->raw_values(); oe_offsets_end_ptr_ = oe_offsets_end_->raw_values(); vertex_data_array_accessor_.Init(vertex_data_array_); ovgid_list_ptr_ = ovgid_list_->raw_values(); edge_data_array_accessor_.Init(edge_data_array_); if (directed_) { ie_ptr_ = reinterpret_cast<const nbr_unit_t*>(ie_->GetValue(0)); } else { ie_ptr_ = reinterpret_cast<const nbr_unit_t*>(oe_->GetValue(0)); } oe_ptr_ = reinterpret_cast<const nbr_unit_t*>(oe_->GetValue(0)); } vertex_range_t inner_vertices_; vertex_range_t outer_vertices_; vertex_range_t vertices_; fid_t fid_, fnum_; bool directed_; vid_t ivnum_, ovnum_, tvnum_; size_t ienum_{}, oenum_{}; label_id_t vertex_label_num_, edge_label_num_; label_id_t vertex_label_, edge_label_; prop_id_t vertex_prop_, edge_prop_; std::shared_ptr<arrow::Int64Array> ie_offsets_begin_, ie_offsets_end_; const int64_t* ie_offsets_begin_ptr_; const int64_t* ie_offsets_end_ptr_; std::shared_ptr<arrow::Int64Array> oe_offsets_begin_, oe_offsets_end_; const int64_t* oe_offsets_begin_ptr_; const int64_t* oe_offsets_end_ptr_; std::shared_ptr<arrow::Array> vertex_data_array_; arrow_projected_fragment_impl::TypedArray<VDATA_T> vertex_data_array_accessor_; std::shared_ptr<vid_array_t> ovgid_list_; const vid_t* ovgid_list_ptr_; std::shared_ptr<vineyard::Hashmap<vid_t, vid_t>> ovg2l_map_; std::shared_ptr<arrow::Array> edge_data_array_; arrow_projected_fragment_impl::TypedArray<EDATA_T> edge_data_array_accessor_; std::shared_ptr<arrow::FixedSizeBinaryArray> ie_, oe_; const nbr_unit_t* ie_ptr_; const nbr_unit_t* oe_ptr_; std::shared_ptr<vertex_map_t> vm_ptr_; vineyard::IdParser<vid_t> vid_parser_; std::shared_ptr<vineyard::ArrowFragment<oid_t, vid_t>> fragment_; std::vector<fid_t> idst_, odst_, iodst_; std::vector<fid_t*> idoffset_, odoffset_, iodoffset_; std::vector<std::vector<int64_t>> ie_spliters_, oe_spliters_; std::vector<const int64_t*> ie_spliters_ptr_, oe_spliters_ptr_; std::vector<vid_t> outer_vertex_offsets_; std::vector<std::vector<vertex_t>> mirrors_of_frag_; }; } // namespace gs #endif // ANALYTICAL_ENGINE_CORE_FRAGMENT_ARROW_PROJECTED_FRAGMENT_H_
33.340035
80
0.657508
[ "object", "vector" ]
c5bff4ae1b6f2e515dfa19f8584a770de4e6f36e
1,655
h
C
src/application.h
zanfire/rt_image_classification
080406acd8abe3d76a164b51b8763deeb8fd3b86
[ "MIT" ]
1
2019-08-12T01:53:50.000Z
2019-08-12T01:53:50.000Z
src/application.h
zanfire/rt_image_classification
080406acd8abe3d76a164b51b8763deeb8fd3b86
[ "MIT" ]
null
null
null
src/application.h
zanfire/rt_image_classification
080406acd8abe3d76a164b51b8763deeb8fd3b86
[ "MIT" ]
null
null
null
#ifndef RT_IMG_CLASS_APPLICATION_H__ #define RT_IMG_CLASS_APPLICATION_H__ #include <glib.h> #include <gst/gst.h> #include <gst/video/video.h> #include <memory> #include "model.h" /** * @brief Application * * Here we store all things that we need to hold for make the application run and do * what we want... * * - Run gstreamer pipeline * - Host callback from gstreamer. * - Retain the model and load the model. */ class Application { public: // Main loop. std::unique_ptr<GMainLoop, decltype(&g_main_loop_unref)> mainloop_; // Bus watcher. std::unique_ptr<GstBus, decltype(&gst_object_unref)> bus_; guint bus_signal_id_message_ = 0; guint bus_signal_id_tensor_sink_new_data_ = 0; guint timer_id_ = 0; GstVideoInfo currentVideoInfo_; bool currentVideoInfoValid_ = false; // Pipeline. std::unique_ptr<GstElement, decltype(&gst_object_unref)> pipeline_; // Model Model model_; public: /** * @brief Construct a new Application object (allocate the new main loop.) * */ Application() : mainloop_(g_main_loop_new(nullptr, false), &g_main_loop_unref), bus_(nullptr, &gst_object_unref), pipeline_(nullptr, &gst_object_unref) {}; ~Application() = default; /** * @brief Setup the application and acquire needed resources (main loop and gst bus) * * @return true if setup is correct otherwise false. */ bool setup(char const* device, char const* model, char const* label, char const* tensor_name, int channel); /** * @brief Run the main loop. */ void run(); /** * @brief Signal main loop to quit. * */ void quit(); }; #endif
24.701493
109
0.682175
[ "object", "model" ]
c5c0f434bee88d972caba016703a015959efad27
17,574
c
C
mcx/mcx.c
clemensschiffer/openmcx
1c8a53857cd2d62349de3627be3b7bea68e4ecbf
[ "Apache-2.0" ]
22
2021-04-09T16:25:16.000Z
2022-03-29T19:31:16.000Z
mcx/mcx.c
clemensschiffer/openmcx
1c8a53857cd2d62349de3627be3b7bea68e4ecbf
[ "Apache-2.0" ]
null
null
null
mcx/mcx.c
clemensschiffer/openmcx
1c8a53857cd2d62349de3627be3b7bea68e4ecbf
[ "Apache-2.0" ]
3
2021-09-24T11:46:42.000Z
2021-11-09T07:05:41.000Z
/******************************************************************************** * Copyright (c) 2020 AVL List GmbH and others * * This program and the accompanying materials are made available under the * terms of the Apache Software License 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ #include "core/Config.h" #include "core/Task.h" #include "core/Model.h" #include "reader/Reader.h" #include "Memory.h" #include "util/os.h" #include "util/string.h" #include "util/signals.h" #include "util/time.h" #include <time.h> #if defined (ENABLE_MT) #include "util/mutex.h" #endif // ENABLE_MT #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ FILE * simulation_log = NULL; FILE * mcx_all_log = NULL; static int write_to_stdout = TRUE; void * _mcx_malloc(size_t len, const char * funct) { void * obj = NULL; #if defined(MEMORY_DEBUG) mcx_printf("alloc %zu from %s\n", len, funct); #endif //defined(MEMORY_DEBUG) obj = malloc(len); if (len > 0 && !obj) { mcx_log(LOG_ERROR, "No Memory"); } return obj; } void _mcx_free(void * obj, const char * funct) { #if defined(MEMORY_DEBUG) mcx_printf("free %p from %s\n", obj, funct); #endif //defined(MEMORY_DEBUG) free(obj); } void * _mcx_realloc(void * obj, size_t size, const char * funct) { void * newMemory = NULL; #if defined(MEMORY_DEBUG) mcx_printf("realloc %p to length %zu from %s\n", obj, size, funct); #endif //defined(MEMORY_DEBUG) newMemory = realloc(obj, size); if (size > 0 && !newMemory) { mcx_log(LOG_ERROR, "No Memory"); } return newMemory; } void * _mcx_calloc(size_t num, size_t size, const char * funct) { void * obj = NULL; #if defined(MEMORY_DEBUG) mcx_printf("calloc %zu * %zu from %s\n", num, size, funct); #endif //defined(MEMORY_DEBUG) obj = calloc(num, size); if (num > 0 && size > 0 && !obj) { mcx_log(LOG_ERROR, "No Memory"); } return obj; } McxStatus mcx_vlog(LogSeverity sev, const char *fmt, va_list args); McxStatus mcx_log(LogSeverity sev, const char *fmt, ...); #if defined (ENABLE_MT) McxMutex logMutex; #endif //ENABLE_MT static void EnableAllLogFile(void) { mcx_all_log = mcx_os_fopen("mcx_all.log", "w"); } static void InitLogFile(const char * logFileName) { simulation_log = mcx_os_fopen(logFileName, "w"); } static void SetupLogFiles(const char * sim_log_file, int write_all_log_file) { InitLogFile(sim_log_file ? sim_log_file : "simulation.log"); if (write_all_log_file) { EnableAllLogFile(); } } static void CleanupLogFile(void) { if (simulation_log) { fclose(simulation_log); simulation_log = NULL; } if (mcx_all_log) { fclose(mcx_all_log); mcx_all_log = NULL; } } static const char * GetLogSeverityString(LogSeverity sev) { switch(sev) { case LOG_DEBUG: return ""; case LOG_INFO: return ""; case LOG_WARNING: return "Warning: "; case LOG_ERROR: return "ERROR: "; case LOG_FATAL: return "ERROR: "; } return ""; } McxStatus mcx_write_log(LogSeverity sev, const char *fmt, size_t writeNewline, va_list args) { #define MSG_MAX_SIZE 2048 char msg[MSG_MAX_SIZE]; char * msgCopy; char * line; char lastChar = '\0'; char logLine_[MSG_MAX_SIZE]; char * logLine = logLine_; char allLogLine_[MSG_MAX_SIZE]; char * allLogLine = allLogLine_; int n = 0; int size = MSG_MAX_SIZE; static size_t startNewLine = 1; size_t len = strlen(fmt); msg[0] = '\0'; if (0 == len) { return RETURN_OK; } n = vsnprintf(msg, MSG_MAX_SIZE, fmt, args); msgCopy = msg; #if defined (ENABLE_MT) mcx_mutex_lock(&logMutex); #endif //ENABLE_MT do { line = mcx_string_sep(&msgCopy, "\n"); //Get next line of msg if (1 == startNewLine) { n = snprintf(logLine, MSG_MAX_SIZE, "%s%s", GetLogSeverityString(sev), line); n = snprintf(allLogLine, MSG_MAX_SIZE, "[%10d] %s%s", (int)clock(), GetLogSeverityString(sev), line); } else { n = snprintf(logLine, MSG_MAX_SIZE, "%s", line); n = snprintf(allLogLine, MSG_MAX_SIZE, "%s", line); } if (write_to_stdout) { if (NULL == msgCopy && 0 == writeNewline) { // last line of msg printf("%s", logLine); } else { printf("%s\n", logLine); } fflush(stdout); } if (simulation_log) { if (sev >= LOG_INFO) { if (NULL == msgCopy && 0 == writeNewline) { //last line of msg fprintf(simulation_log, "%s", logLine); } else { fprintf(simulation_log, "%s\n", logLine); } fflush(simulation_log); } } if (mcx_all_log) { if (NULL == msgCopy && 0 == writeNewline) { //last line of msg fprintf(mcx_all_log, "%s", allLogLine); } else { fprintf(mcx_all_log, "%s\n", allLogLine); } fflush(mcx_all_log); } if (NULL == msgCopy && '\0' != *line) {//in the last line of msg check if the last char written was \n, then startNewLine has to be 1 no matter what writeNewLine is. startNewLine = writeNewline; } else { startNewLine = 1; } } while (NULL != msgCopy); #if defined (ENABLE_MT) mcx_mutex_unlock(&logMutex); #endif //ENABLE_MT return RETURN_OK; } McxStatus mcx_vlog(LogSeverity sev, const char *fmt, va_list args) { return mcx_write_log(sev, fmt, 1, args); } McxStatus mcx_vlog_no_newline(LogSeverity sev, const char *fmt, va_list args) { return mcx_write_log(sev, fmt, 0, args); } McxStatus mcx_log(LogSeverity sev, const char *fmt, ...) { McxStatus retVal = RETURN_OK; va_list args; va_start(args, fmt); retVal = mcx_vlog(sev, fmt, args); va_end(args); return RETURN_OK; } McxStatus mcx_log_no_newline(LogSeverity sev, const char *fmt, ...) { McxStatus retVal = RETURN_OK; va_list args; va_start(args, fmt); retVal = mcx_vlog_no_newline(sev, fmt, args); va_end(args); return RETURN_OK; } static int mcx_log_printf(const char * fmt, ...) { McxStatus retVal = RETURN_OK; va_list args; va_start(args, fmt); retVal = mcx_vlog(LOG_INFO, fmt, args); va_end(args); return 0; } static McxStatus CompWriteDebugInfoAfterSimulation(Component * comp, void * param) { return comp->WriteDebugInfoAfterSimulation(comp); } static void model_stats(Model * model) { SubModel * subModel = model->subModel; subModel->LoopComponents(subModel, CompWriteDebugInfoAfterSimulation, NULL); } McxStatus RunMCX(int argc, char *argv[]) { Config * config = NULL; Model * model = NULL; Task * task = NULL; McxTime clock_begin; McxTime clock_read_begin, clock_read_end; McxTime clock_setup_begin, clock_setup_end; McxTime clock_sim_begin, clock_sim_end; McxTime clock_cleanup_begin, clock_cleanup_end; McxTime clock_init_begin, clock_init_end; double cpu_time_sec; McxTime cpu_time_used; McxTime time_begin; McxTime time_read_begin, time_read_end; McxTime time_setup_begin, time_setup_end; McxTime time_sim_begin, time_sim_end; McxTime time_cleanup_begin, time_cleanup_end; McxTime time_init_begin, time_init_end; McxTime time_diff; double wall_time_sec; int logInitialized = 0; McxStatus retVal = RETURN_OK; InputRoot * mcxInput = NULL; InputElement * element = NULL; Reader * reader = NULL; mcx_cpu_time_get(&clock_begin); mcx_time_get(&time_begin); config = (Config *) object_create(Config); if (!config) { mcx_log(LOG_ERROR, "Could not create config"); retVal = RETURN_ERROR; goto cleanup; } retVal = config->SetupFromCmdLine(config, argc, argv); if (retVal == RETURN_ERROR) { goto cleanup; } SetupLogFiles(config->logFile, config->writeAllLogFile); logInitialized = 1; retVal = config->SetupFromEnvironment(config); if (RETURN_OK != retVal) { mcx_log(LOG_INFO, "Setting up configuration from environment failed"); retVal = RETURN_ERROR; goto cleanup; } reader = (Reader*)object_create(Reader); if (!reader) { mcx_log(LOG_ERROR, "Could not create input file reader"); retVal = RETURN_ERROR; goto cleanup; } retVal = reader->Setup(reader, config->modelFile, config); if (retVal == RETURN_ERROR) { mcx_log(LOG_ERROR, "Input reader setup failed"); retVal = RETURN_ERROR; goto cleanup; } mcxInput = reader->Read(reader, config->modelFile); if (!mcxInput) { mcx_log(LOG_ERROR, "Parsing of input file failed"); retVal = RETURN_ERROR; goto cleanup; } element = (InputElement *) mcxInput; retVal = config->SetupFromInput(config, mcxInput->config); if (RETURN_OK != retVal) { mcx_log(LOG_ERROR, "Setting up configuration from input file failed"); retVal = RETURN_ERROR; goto cleanup; } PrintConfig(config); task = (Task *) object_create(Task); if (!task) { mcx_log(LOG_ERROR, "Could not create task settings"); retVal = RETURN_ERROR; goto cleanup; } model = (Model *) object_create(Model); if (!model) { mcx_log(LOG_ERROR, "Could not create model"); retVal = RETURN_ERROR; goto cleanup; } ComponentFactory * factory = object_create(ComponentFactory); task->SetConfig(task, config); model->SetConfig(model, config); model->SetTask(model, task); model->SetComponentFactory(model, factory); mcx_log(LOG_INFO, "******************** Read data: **************************************"); mcx_log(LOG_INFO, " "); mcx_cpu_time_get(&clock_read_begin); mcx_time_get(&time_read_begin); retVal = task->Read(task, mcxInput->task); if (RETURN_OK != retVal) { retVal = RETURN_ERROR; goto cleanup; } retVal = model->Read(model, mcxInput->model); if (RETURN_OK != retVal) { retVal = RETURN_ERROR; goto cleanup; } object_destroy(mcxInput); reader->Cleanup(reader); object_destroy(reader); mcx_cpu_time_get(&clock_read_end); mcx_time_get(&time_read_end); mcx_log(LOG_INFO, "******************** Read done. **************************************"); mcx_time_diff(&clock_read_begin, &clock_read_end, &cpu_time_used); cpu_time_sec = mcx_time_to_seconds(&cpu_time_used); mcx_log(LOG_INFO, "******************** Used CPU-Time: %fs ***********************", cpu_time_sec); mcx_time_diff(&time_read_begin, &time_read_end, &time_diff); wall_time_sec = mcx_time_to_seconds(&time_diff); mcx_log(LOG_INFO, "******************** Used Wall-Time: %fs ***********************", wall_time_sec); mcx_log(LOG_INFO, " "); mcx_log(LOG_INFO, " "); mcx_log(LOG_INFO, "******************** Setup: ******************************************"); mcx_log(LOG_INFO, " "); mcx_cpu_time_get(&clock_setup_begin); mcx_time_get(&time_setup_begin); retVal = task->Setup(task, model); if (RETURN_OK != retVal) { retVal = RETURN_ERROR; goto cleanup; } retVal = model->Setup(model); if (RETURN_OK != retVal) { retVal = RETURN_ERROR; goto cleanup; } retVal = task->PrepareRun(task, model); if (RETURN_OK != retVal) { retVal = RETURN_ERROR; goto cleanup; } mcx_cpu_time_get(&clock_setup_end); mcx_time_get(&time_setup_end); mcx_log(LOG_INFO, "******************** Setup done. *************************************"); mcx_time_diff(&clock_setup_begin, &clock_setup_end, &cpu_time_used); cpu_time_sec = mcx_time_to_seconds(&cpu_time_used); mcx_log(LOG_INFO, "******************** Used CPU-Time: %fs ***********************", cpu_time_sec); mcx_time_diff(&time_setup_begin, &time_setup_end, &time_diff); wall_time_sec = mcx_time_to_seconds(&time_diff); mcx_log(LOG_INFO, "******************** Used Wall-Time: %fs ***********************", wall_time_sec); mcx_log(LOG_INFO, " "); mcx_log(LOG_INFO, " "); mcx_log(LOG_INFO, "******************** Initialization: *********************************"); mcx_log(LOG_INFO, " "); mcx_cpu_time_get(&clock_init_begin); mcx_time_get(&time_init_begin); retVal = task->Initialize(task, model); if (RETURN_OK != retVal) { retVal = RETURN_ERROR; goto cleanup; } mcx_cpu_time_get(&clock_init_end); mcx_time_get(&time_init_end); mcx_log(LOG_INFO, "******************** Initialization done. ****************************"); mcx_time_diff(&clock_init_begin, &clock_init_end, &cpu_time_used); cpu_time_sec = mcx_time_to_seconds(&cpu_time_used); mcx_log(LOG_INFO, "******************** Used CPU-Time: %fs ***********************", cpu_time_sec); mcx_time_diff(&time_init_begin, &time_init_end, &time_diff); wall_time_sec = mcx_time_to_seconds(&time_diff); mcx_log(LOG_INFO, "******************** Used Wall-Time: %fs ***********************", wall_time_sec); mcx_log(LOG_INFO, " "); mcx_log(LOG_INFO, " "); mcx_log(LOG_INFO, "******************** Simulation: *************************************"); mcx_log(LOG_INFO, " "); mcx_cpu_time_get(&clock_sim_begin); mcx_time_get(&time_sim_begin); retVal = task->Run(task, model); if (RETURN_OK != retVal) { retVal = RETURN_ERROR; goto cleanup; } mcx_cpu_time_get(&clock_sim_end); mcx_time_get(&time_sim_end); mcx_log(LOG_INFO, "******************** Simulation done. ********************************"); mcx_time_diff(&clock_sim_begin, &clock_sim_end, &cpu_time_used); cpu_time_sec = mcx_time_to_seconds(&cpu_time_used); mcx_log(LOG_INFO, "******************** Used CPU-Time: %fs ***********************", cpu_time_sec); mcx_time_diff(&time_sim_begin, &time_sim_end, &time_diff); wall_time_sec = mcx_time_to_seconds(&time_diff); mcx_log(LOG_INFO, "******************** Used Wall-Time: %fs ***********************", wall_time_sec); mcx_log(LOG_INFO, " "); mcx_log(LOG_INFO, " "); mcx_log(LOG_INFO, "******************** Summary: ****************************************"); mcx_log(LOG_INFO, " "); model_stats(model); mcx_log(LOG_INFO, "**********************************************************************"); mcx_log(LOG_INFO, " "); mcx_log(LOG_INFO, " "); mcx_log(LOG_INFO, "******************** Clean-up: ***************************************"); mcx_log(LOG_INFO, " "); mcx_cpu_time_get(&clock_cleanup_begin); mcx_time_get(&time_cleanup_begin); object_destroy(task); object_destroy(model); object_destroy(config); mcx_cpu_time_get(&clock_cleanup_end); mcx_time_get(&time_cleanup_end); mcx_log(LOG_INFO, "******************** Clean-up done. **********************************"); mcx_time_diff(&clock_cleanup_begin, &clock_cleanup_end, &cpu_time_used); cpu_time_sec = mcx_time_to_seconds(&cpu_time_used); mcx_log(LOG_INFO, "******************** Used CPU-Time: %fs ***********************", cpu_time_sec); mcx_time_diff(&time_cleanup_begin, &time_cleanup_end, &time_diff); wall_time_sec = mcx_time_to_seconds(&time_diff); mcx_log(LOG_INFO, "******************** Used Wall-Time: %fs ***********************", wall_time_sec); mcx_log(LOG_INFO, " "); mcx_log(LOG_INFO, " "); mcx_time_diff(&clock_begin, &clock_cleanup_end, &cpu_time_used); cpu_time_sec = mcx_time_to_seconds(&cpu_time_used); mcx_time_diff(&time_begin, &time_cleanup_end, &time_diff); wall_time_sec = mcx_time_to_seconds(&time_diff); mcx_log(LOG_INFO, "******************** Statistics: *************************************"); mcx_log(LOG_INFO, " "); mcx_log(LOG_INFO, "Program finished successfully"); mcx_log(LOG_INFO, "Total used CPU-Time: %fs", cpu_time_sec); mcx_log(LOG_INFO, "Total used Wall-Time: %fs", wall_time_sec); mcx_log(LOG_INFO, " "); cleanup: if (mcxInput) { object_destroy(mcxInput); } if (model) { object_destroy(model); } if (task) { object_destroy(task); } if (config) { object_destroy(config); } if (logInitialized) { mcx_log(LOG_INFO, "**********************************************************************"); } return retVal; } int main(int argc, char *argv[]) { McxStatus retVal = RETURN_OK; char ** argList; int nArgs = 0; mcx_os_get_args(&argList, &nArgs); if (!argList) { argList = argv; nArgs = argc; } #if defined (ENABLE_MT) mcx_mutex_create(&logMutex); #endif //ENABLE_MT InitMemory(); mcx_signal_handler_enable(); retVal = RunMCX(nArgs, argList); mcx_signal_handler_disable(); if (argList != argv) { int i = 0; for (i = 0; i < nArgs; i++) { mcx_free(argList[i]); } mcx_free(argList); } CleanupLogFile(); return (RETURN_ERROR == retVal); } #ifdef __cplusplus } /* closing brace for extern "C" */ #endif /* __cplusplus */
29.338898
173
0.585581
[ "model" ]
c5c589b91f1e2f5d907ca7e2d4f58257fd259a65
586
h
C
PushExampleProject/PushTechSDK/PushTechSDK.framework/Versions/A/Headers/PSHSuccessfulDeviceIdBusEvent.h
PUSHTech/push-sdk-sample-app
b934a162be381feb42c7de58988f78afe47aa046
[ "MIT", "Unlicense" ]
1
2015-11-04T13:23:43.000Z
2015-11-04T13:23:43.000Z
PushExampleProject/PushTechSDK/PushTechSDK.framework/Versions/A/Headers/PSHSuccessfulDeviceIdBusEvent.h
PUSHTech/push-sdk-sample-app
b934a162be381feb42c7de58988f78afe47aa046
[ "MIT", "Unlicense" ]
null
null
null
PushExampleProject/PushTechSDK/PushTechSDK.framework/Versions/A/Headers/PSHSuccessfulDeviceIdBusEvent.h
PUSHTech/push-sdk-sample-app
b934a162be381feb42c7de58988f78afe47aa046
[ "MIT", "Unlicense" ]
null
null
null
#import <Foundation/Foundation.h> /** Bus event emitted after a successful app registration, that is when local model has been updated with the necessary info from PUSHTech platform in order to perform any operation. Event bus listeners (see `PSHBusProvider`) must implement the following method for event awareness: -(void)onSuccessfulDeviceIdBusEvent:(NSNotification*)notification { // Now we can obtain the DeviceID NSString *deviceId = [PSHEngine sharedInstance].deviceId; ... } */ @interface PSHSuccessfulDeviceIdBusEvent : NSObject @end
34.470588
279
0.744027
[ "model" ]
c5d33c82d4e4434ebc9b24746206a18e8d587cb3
7,230
h
C
Lecture/L10/mpe2-2.4.9b/src/slog2sdk/src/logformat/trace/trace_API.h
liweichen6/CMDA3634
d4722b1af264d30d0c92f9ac772f04be918bc105
[ "MIT" ]
null
null
null
Lecture/L10/mpe2-2.4.9b/src/slog2sdk/src/logformat/trace/trace_API.h
liweichen6/CMDA3634
d4722b1af264d30d0c92f9ac772f04be918bc105
[ "MIT" ]
null
null
null
Lecture/L10/mpe2-2.4.9b/src/slog2sdk/src/logformat/trace/trace_API.h
liweichen6/CMDA3634
d4722b1af264d30d0c92f9ac772f04be918bc105
[ "MIT" ]
null
null
null
/* * (C) 2001 by Argonne National Laboratory * See COPYRIGHT in top-level directory. */ /* * @author Bill Gropp, Anthony Chan */ /* * API to read a trace file for the SLOG algorithm */ #if defined(__cplusplus) extern "C" { #endif typedef struct _trace_file *TRACE_file; #if defined( WIN32 ) #define TRACE_EXPORT __declspec(dllexport) #define TRACE_int64_t __int64 #else #define TRACE_EXPORT #define TRACE_int64_t long long #endif /*E TRACE_Rec_Kind_t - Types of records returned by the TRACE API Types: + TRACE_EOF - End of file. Indicates that no more items are available. . TRACE_PRIMITIVE_DRAWABLE - Primitive Drawable; for example, an event, state or arrow. . TRACE_COMPOSITE_DRAWABLE - Composite Drawable; a collection of primitive drawables. . TRACE_CATEGORY - Category, describing classes of drawables. - TRACE_YCOORDMAP - Y-axis Coordinate map, describing how to interpret or label the y coordinate values Notes: These record types represent the type of data that the TRACE API presents to the calling program. The source file that the TRACE API is reading may or may not contain any of these record types. In fact, most trace files will not contain any of these record types; instead, the implementation of the TRACE API will read the source trace file and create these from the raw data in the original source file. E*/ typedef enum { TRACE_EOF=0, TRACE_PRIMITIVE_DRAWABLE=1, TRACE_COMPOSITE_DRAWABLE=2, TRACE_CATEGORY=3, TRACE_YCOORDMAP=4 } TRACE_Rec_Kind_t; /* Predefined Shapes ID - for 'TRACE_Category_head_t' */ #define TRACE_SHAPE_EVENT 0 #define TRACE_SHAPE_STATE 1 #define TRACE_SHAPE_ARROW 2 /* Predefined Method IDs - for 'TRACE_Get_next_category()' and 'TRACE_Get_next_ycoordmap()' */ #define TRACE_METHOD_CONNECT_COMPOSITE_STATE 1 /*S TRACE_Category_head_t - Structure defining the basic information about a category + index - integer value by which records will identify themselves as belonging to this category. index is assumed to be non-negative. negative index is reserved for internal use. . shape - Shape of the category. This is an integer defined by the drawing program; the value 'TRACE_SHAPE_EVENT' (=0) is reserved for an event ( a marker at one point on a timeline ), the value 'TRACE_SHAPE_STATE' (=1) is reserved for a basic state (a rectangle along a timeline), 'TRACE_SHAPE_ARROW' (=2) is reserved for an arrow (such as used to describe a message from a send state to a receive state), . red, green, blue - Color of the shape; each is in the range [0,255] . alpha - Transparency value, in the range of [0,255]. Some display programs may ignore this value. An alpha value of 255 means that the color is completely opaque and an alpha value of 0 means that the color is completely transparent. (reference java.awt.Color) - width - the pixel width of the stroke when drawing the shape. Some display programs may ignore this value. S*/ typedef struct { int index; int shape; int red, green, blue, alpha; int width; } TRACE_Category_head_t; /* . name - name of the category (See below) Questions: A prior version left the 'name' out of the 'TRACE_Category_head_t'. This was done to separate the frequently accessed data (shape, color, width) that is needed to render a member of this category from the data needed to describe the category on a legend and to describe a particular instance (the label). A more recent version included 'char *name', but the API provided no way to allocate or free the associated storage for this data. I have removed 'name' until the issues are resolved. */ TRACE_EXPORT int TRACE_Open( const char filespec[], TRACE_file *fp ); TRACE_EXPORT int TRACE_Close( TRACE_file *fp ); /* TRACE_EXPORT int TRACE_Get_total_time( const TRACE_file fp, double *starttime, double *endtime ); */ TRACE_EXPORT int TRACE_Peek_next_kind( const TRACE_file fp, TRACE_Rec_Kind_t *next_kind ); TRACE_EXPORT int TRACE_Get_next_method( const TRACE_file fp, char method_name[], char method_extra[], int *methodID ); TRACE_EXPORT int TRACE_Peek_next_category( const TRACE_file fp, int *n_legend, int *n_label, int *n_methodIDs ); TRACE_EXPORT int TRACE_Get_next_category( const TRACE_file fp, TRACE_Category_head_t *head, int *n_legend, char legend_base[], int *legend_pos, const int legend_max, int *n_label, char label_base[], int *label_pos, const int label_max, int *n_methodIDs, int methodID_base[], int *methodID_pos, const int methodID_max ); TRACE_EXPORT int TRACE_Peek_next_ycoordmap( TRACE_file fp, int *n_rows, int *n_columns, int *max_column_name, int *max_title_name, int *n_methodIDs ); TRACE_EXPORT int TRACE_Get_next_ycoordmap( TRACE_file fp, char *title_name, char **column_names, int *coordmap_sz, int coordmap_base[], int *coordmap_pos, const int coordmap_max, int *n_methodIDs, int methodID_base[], int *methodID_pos, const int methodID_max ); TRACE_EXPORT int TRACE_Peek_next_primitive( const TRACE_file fp, double *starttime, double *endtime, int *n_tcoords, int *n_ycoords, int *n_bytes ); TRACE_EXPORT int TRACE_Get_next_primitive( const TRACE_file fp, int *category_index, int *n_tcoords, double tcoord_base[], int *tcoord_pos, const int tcoord_max, int *n_ycoords, int ycoord_base[], int *ycoord_pos, const int ycoord_max, int *n_bytes, char byte_base[], int *byte_pos, const int byte_max ); TRACE_EXPORT int TRACE_Peek_next_composite( const TRACE_file fp, double *starttime, double *endtime, int *n_primitives, int *n_bytes ); TRACE_EXPORT int TRACE_Get_next_composite( const TRACE_file fp, int *category_index, int *n_bytes, char byte_base[], int *byte_pos, const int byte_max ); TRACE_EXPORT int TRACE_Get_position( TRACE_file fp, TRACE_int64_t *offset ); TRACE_EXPORT int TRACE_Set_position( TRACE_file fp, TRACE_int64_t offset ); TRACE_EXPORT const char *TRACE_Get_err_string( int ierr ); #if defined(__cplusplus) } #endif
35.792079
79
0.63195
[ "render", "shape" ]
c5db3bc9d186d2c3e060f1d90ef3526638f94e62
38,880
c
C
jerry-core/ecma/builtin-objects/ecma-builtin-helpers-date.c
socware-net/jerryscript
5c34377f165ef430e2491f40f3a219a060d1f872
[ "Apache-2.0" ]
null
null
null
jerry-core/ecma/builtin-objects/ecma-builtin-helpers-date.c
socware-net/jerryscript
5c34377f165ef430e2491f40f3a219a060d1f872
[ "Apache-2.0" ]
null
null
null
jerry-core/ecma/builtin-objects/ecma-builtin-helpers-date.c
socware-net/jerryscript
5c34377f165ef430e2491f40f3a219a060d1f872
[ "Apache-2.0" ]
null
null
null
/* Copyright 2015-2016 Samsung Electronics Co., Ltd. * Copyright 2015-2016 University of Szeged. * * 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 <math.h> #include "ecma-alloc.h" #include "ecma-builtin-helpers.h" #include "ecma-exceptions.h" #include "ecma-globals.h" #include "ecma-helpers.h" #include "ecma-objects.h" #include "ecma-try-catch-macro.h" #include "lit-char-helpers.h" #ifndef CONFIG_ECMA_COMPACT_PROFILE_DISABLE_DATE_BUILTIN /** \addtogroup ecma ECMA * @{ * * \addtogroup ecmabuiltinhelpers ECMA builtin helper operations * @{ */ /** * Helper function to get day number from time value. * * See also: * ECMA-262 v5, 15.9.1.2 * * Used by: * - The Date.prototype.setMilliseconds routine. * - The Date.prototype.setUTCMilliseconds routine. * - The Date.prototype.setSeconds routine. * - The Date.prototype.setUTCSeconds routine. * - The Date.prototype.setMinutes routine. * - The Date.prototype.setUTCMinutes routine. * - The Date.prototype.setHours routine. * - The Date.prototype.setUTCHours routine. * * @return time value for day number */ inline ecma_number_t __attr_always_inline___ ecma_date_day (ecma_number_t time) /**< time value */ { if (ecma_number_is_nan (time)) { return time; /* time is NaN */ } return (ecma_number_t) floor (time / ECMA_DATE_MS_PER_DAY); } /* ecma_date_day */ /** * Helper function to get time within day from time value. * * See also: * ECMA-262 v5, 15.9.1.2 * * Used by: * - The Date.prototype.setDate routine. * - The Date.prototype.setUTCDate routine. * - The Date.prototype.setMonth routine. * - The Date.prototype.setUTCMonth routine. * - The Date.prototype.setFullYear routine. * - The Date.prototype.setUTCFullYear routine. * * @return time value within the day */ inline ecma_number_t __attr_always_inline___ ecma_date_time_within_day (ecma_number_t time) /**< time value */ { if (ecma_number_is_nan (time)) { return time; /* time is NaN */ } return (ecma_number_t) fmod (time, ECMA_DATE_MS_PER_DAY); } /* ecma_date_time_within_day */ /** * Helper function to get number of days from year value. * * See also: * ECMA-262 v5, 15.9.1.3 * * @return number of days */ inline ecma_number_t __attr_always_inline___ ecma_date_days_in_year (ecma_number_t year) /**< year value */ { if (ecma_number_is_nan (year)) { return year; /* year is NaN */ } if (fmod (floor (year), 4)) { return (ecma_number_t) 365; } if (fmod (floor (year), 100)) { return (ecma_number_t) 366; } if (fmod (floor (year), 400)) { return (ecma_number_t) 365; } return (ecma_number_t) 366; } /* ecma_date_days_in_year */ /** * Helper function to get the day number of the first day of a year. * * See also: * ECMA-262 v5, 15.9.1.3 * * @return day number of the first day of a year */ inline ecma_number_t __attr_always_inline___ ecma_date_day_from_year (ecma_number_t year) /**< year value */ { if (ecma_number_is_nan (year)) { return year; /* year is NaN */ } return (ecma_number_t) (365 * (year - 1970) + floor ((year - 1969) / 4) - floor ((year - 1901) / 100) + floor ((year - 1601) / 400)); } /* ecma_date_day_from_year */ /** * Helper function to get the time value of the start of a year. * * See also: * ECMA-262 v5, 15.9.1.3 * * @return time value of the start of a year */ inline ecma_number_t __attr_always_inline___ ecma_date_time_from_year (ecma_number_t year) /**< year value */ { if (ecma_number_is_nan (year)) { return year; /* year is NaN */ } return ECMA_DATE_MS_PER_DAY * ecma_date_day_from_year (year); } /* ecma_date_time_from_year */ /** * Helper function to determine a year value from the time value. * * See also: * ECMA-262 v5, 15.9.1.3 * * Used by: * - The Date.prototype.getFullYear routine. (Generated.) * - The Date.prototype.getUTCFullYear routine. (Generated.) * - The Date.prototype.setDate routine. * - The Date.prototype.setUTCDate routine. * - The Date.prototype.setMonth routine. * - The Date.prototype.setUTCMonth routine. * * @return year value */ ecma_number_t ecma_date_year_from_time (ecma_number_t time) /**< time value */ { if (ecma_number_is_nan (time)) { return time; /* time is NaN */ } /* ECMA-262 v5, 15.9.1.1 define the largest year that is * representable (285616) forward from 01 January, 1970 UTC. */ ecma_number_t year = (ecma_number_t) (1970 + 285616); ecma_number_t lower_year_boundary = (ecma_number_t) (1970 - 285616); while (ecma_date_time_from_year (year) > time) { ecma_number_t year_boundary = (ecma_number_t) floor (lower_year_boundary + (year - lower_year_boundary) / 2); if (ecma_date_time_from_year (year_boundary) > time) { year = year_boundary; } else { lower_year_boundary = year_boundary; } year--; } return year; } /* ecma_date_year_from_time */ /** * Helper function to decide if time value is in a leap-year. * * See also: * ECMA-262 v5, 15.9.1.3 * * @return 1 if time within a leap year and otherwise is zero */ inline ecma_number_t __attr_always_inline___ ecma_date_in_leap_year (ecma_number_t time) /**< time value */ { if (ecma_number_is_nan (time)) { return time; /* time is NaN */ } return ecma_date_days_in_year (ecma_date_year_from_time (time)) - 365; } /* ecma_date_in_leap_year */ /** * Helper function to get day within year from time value. * * See also: * ECMA-262 v5, 15.9.1.4 * * @return number of days within year */ inline ecma_number_t __attr_always_inline___ ecma_date_day_within_year (ecma_number_t time) /**< time value */ { if (ecma_number_is_nan (time)) { return time; /* time is NaN */ } return ecma_date_day (time) - ecma_date_day_from_year (ecma_date_year_from_time (time)); } /* ecma_date_day_within_year */ /** * Helper function to get month from time value. * * See also: * ECMA-262 v5, 15.9.1.4 * * Used by: * - The Date.prototype.getMonth routine. (Generated.) * - The Date.prototype.getUTCMonth routine. (Generated.) * - The Date.prototype.setDate routine. * - The Date.prototype.setUTCDate routine. * - The Date.prototype.setFullYear routine. * - The Date.prototype.setUTCFullYear routine. * * @return month number */ ecma_number_t ecma_date_month_from_time (ecma_number_t time) /**< time value */ { if (ecma_number_is_nan (time)) { return time; /* time is NaN */ } ecma_number_t in_leap_year = ecma_date_in_leap_year (time); ecma_number_t day_within_year = ecma_date_day_within_year (time); JERRY_ASSERT (day_within_year >= 0 && day_within_year < 365 + in_leap_year); if (day_within_year < 31) { return 0; } else if (day_within_year < 59 + in_leap_year) { return 1; } else if (day_within_year < 90 + in_leap_year) { return 2; } else if (day_within_year < 120 + in_leap_year) { return 3; } else if (day_within_year < 151 + in_leap_year) { return 4; } else if (day_within_year < 181 + in_leap_year) { return 5; } else if (day_within_year < 212 + in_leap_year) { return 6; } else if (day_within_year < 243 + in_leap_year) { return 7; } else if (day_within_year < 273 + in_leap_year) { return 8; } else if (day_within_year < 304 + in_leap_year) { return 9; } else if (day_within_year < 334 + in_leap_year) { return 10; } return 11; } /* ecma_date_month_from_time */ /** * Helper function to get date number from time value. * * See also: * ECMA-262 v5, 15.9.1.5 * * Used by: * - The Date.prototype.getDate routine. (Generated.) * - The Date.prototype.getUTCDate routine. (Generated.) * - The Date.prototype.setMonth routine. * - The Date.prototype.setUTCMonth routine. * - The Date.prototype.setFullYear routine. * - The Date.prototype.setUTCFullYear routine. * * @return date number */ ecma_number_t ecma_date_date_from_time (ecma_number_t time) /**< time value */ { if (ecma_number_is_nan (time)) { return time; /* time is NaN */ } ecma_number_t in_leap_year = ecma_date_in_leap_year (time); ecma_number_t day_within_year = ecma_date_day_within_year (time); JERRY_ASSERT (!ecma_number_is_nan (ecma_date_month_from_time (time))); int month = ecma_number_to_int32 (ecma_date_month_from_time (time)); switch (month) { case 0: { return day_within_year + 1; } case 1: { return day_within_year - 30 ; } case 2: { return day_within_year - 58 - in_leap_year; } case 3: { return day_within_year - 89 - in_leap_year; } case 4: { return day_within_year - 119 - in_leap_year; } case 5: { return day_within_year - 150 - in_leap_year; } case 6: { return day_within_year - 180 - in_leap_year; } case 7: { return day_within_year - 211 - in_leap_year; } case 8: { return day_within_year - 242 - in_leap_year; } case 9: { return day_within_year - 272 - in_leap_year; } case 10: { return day_within_year - 303 - in_leap_year; } case 11: { return day_within_year - 333 - in_leap_year; } } JERRY_UNREACHABLE (); return 0; } /* ecma_date_date_from_time */ /** * Helper function to get weekday from time value. * * See also: * ECMA-262 v5, 15.9.1.6 * * Used by: * - The Date.prototype.getDay routine. (Generated.) * - The Date.prototype.getUTCDay routine. (Generated.) * * @return weekday number */ inline ecma_number_t __attr_always_inline___ ecma_date_week_day (ecma_number_t time) /**< time value */ { if (ecma_number_is_nan (time)) { return time; /* time is NaN */ } return (ecma_number_t) fmod ((ecma_date_day (time) + 4), 7); } /* ecma_date_week_day */ /** * Helper function to get local time zone adjustment. * * See also: * ECMA-262 v5, 15.9.1.7 * * @return local time zone adjustment */ inline ecma_number_t __attr_always_inline___ ecma_date_local_tza () { jerry_time_zone_t tz; if (!jerry_port_get_time_zone (&tz)) { return ecma_number_make_nan (); } return tz.offset * -ECMA_DATE_MS_PER_MINUTE; } /* ecma_date_local_tza */ /** * Helper function to get the daylight saving time adjustment. * * See also: * ECMA-262 v5, 15.9.1.8 * * @return daylight saving time adjustment */ inline ecma_number_t __attr_always_inline___ ecma_date_daylight_saving_ta (ecma_number_t time) /**< time value */ { if (ecma_number_is_nan (time)) { return time; /* time is NaN */ } jerry_time_zone_t tz; if (!jerry_port_get_time_zone (&tz)) { return ecma_number_make_nan (); } return tz.daylight_saving_time * ECMA_DATE_MS_PER_HOUR; } /* ecma_date_daylight_saving_ta */ /** * Helper function to get local time from UTC. * * See also: * ECMA-262 v5, 15.9.1.9 * * Used by: * - All Date.prototype.getUTC routines. (Generated.) * - The Date.prototype.getTimezoneOffset routine. * - The Date.prototype.setMilliseconds routine. * - The Date.prototype.setSeconds routine. * - The Date.prototype.setMinutes routine. * - The Date.prototype.setHours routine. * - The Date.prototype.setDate routine. * - The Date.prototype.setMonth routine. * - The Date.prototype.setFullYear routine. * - The ecma_date_timezone_offset helper function. * * @return local time */ inline ecma_number_t __attr_always_inline___ ecma_date_local_time (ecma_number_t time) /**< time value */ { if (ecma_number_is_nan (time)) { return time; /* time is NaN */ } return time + ecma_date_local_tza () + ecma_date_daylight_saving_ta (time); } /* ecma_date_local_time */ /** * Helper function to get utc from local time. * * See also: * ECMA-262 v5, 15.9.1.9 * * Used by: * - The Date object's 'parse' routine. * - The [[Construct]] of built-in Date object rutine. * * @return utc value */ inline ecma_number_t __attr_always_inline___ ecma_date_utc (ecma_number_t time) /**< time value */ { if (ecma_number_is_nan (time)) { return time; /* time is NaN */ } ecma_number_t simple_utc_time = time - ecma_date_local_tza (); return simple_utc_time - ecma_date_daylight_saving_ta (simple_utc_time); } /* ecma_date_utc */ /** * Helper function to get hour from time value. * * See also: * ECMA-262 v5, 15.9.1.10 * * Used by: * - The Date.prototype.getHour routine. (Generated.) * - The Date.prototype.getUTCHour routine. (Generated.) * - The Date.prototype.setMilliseconds routine. * - The Date.prototype.setUTCMilliseconds routine. * - The Date.prototype.setSeconds routine. * - The Date.prototype.setUTCSeconds routine. * - The Date.prototype.setMinutes routine. * - The Date.prototype.setUTCMinutes routine. * * @return hour value */ inline ecma_number_t __attr_always_inline___ ecma_date_hour_from_time (ecma_number_t time) /**< time value */ { if (ecma_number_is_nan (time)) { return time; /* time is NaN */ } ecma_number_t hour = (ecma_number_t) fmod (floor (time / ECMA_DATE_MS_PER_HOUR), ECMA_DATE_HOURS_PER_DAY); return (hour < 0) ? ECMA_DATE_HOURS_PER_DAY + hour : hour; } /* ecma_date_hour_from_time */ /** * Helper function to get minute from time value. * * See also: * ECMA-262 v5, 15.9.1.10 * * Used by: * - The Date.prototype.getMinutes routine. (Generated.) * - The Date.prototype.getUTCMinutes routine. (Generated.) * - The Date.prototype.setMilliseconds routine. * - The Date.prototype.setUTCMilliseconds routine. * - The Date.prototype.setSeconds routine. * - The Date.prototype.setUTCSeconds routine. * - The Date.prototype.setHours routine. * - The Date.prototype.setUTCHours routine. * * @return minute value */ inline ecma_number_t __attr_always_inline___ ecma_date_min_from_time (ecma_number_t time) /**< time value */ { if (ecma_number_is_nan (time)) { return time; /* time is NaN */ } ecma_number_t min = (ecma_number_t) fmod (floor (time / ECMA_DATE_MS_PER_MINUTE), ECMA_DATE_MINUTES_PER_HOUR); return (min < 0) ? ECMA_DATE_MINUTES_PER_HOUR + min : min; } /* ecma_date_min_from_time */ /** * Helper function to get second from time value. * * See also: * ECMA-262 v5, 15.9.1.10 * * Used by: * - The Date.prototype.getSeconds routine. (Generated.) * - The Date.prototype.getUTCSeconds routine. (Generated.) * - The Date.prototype.setMilliseconds routine. * - The Date.prototype.setUTCMilliseconds routine. * - The Date.prototype.setMinutes routine. * - The Date.prototype.setUTCMinutes routine. * - The Date.prototype.setHours routine. * - The Date.prototype.setUTCHours routine. * * @return second value */ inline ecma_number_t __attr_always_inline___ ecma_date_sec_from_time (ecma_number_t time) /**< time value */ { if (ecma_number_is_nan (time)) { return time; /* time is NaN */ } ecma_number_t sec = (ecma_number_t) fmod (floor (time / ECMA_DATE_MS_PER_SECOND), ECMA_DATE_SECONDS_PER_MINUTE); return (sec < 0) ? ECMA_DATE_SECONDS_PER_MINUTE + sec : sec; } /* ecma_date_sec_from_time */ /** * Helper function to get millisecond from time value. * * See also: * ECMA-262 v5, 15.9.1.10 * * Used by: * - The Date.prototype.getMilliseconds routine. (Generated.) * - The Date.prototype.getUTCMilliseconds routine. (Generated.) * - The Date.prototype.setSeconds routine. * - The Date.prototype.setUTCSeconds routine. * - The Date.prototype.setMinutes routine. * - The Date.prototype.setUTCMinutes routine. * - The Date.prototype.setHours routine. * - The Date.prototype.setUTCHours routine. * * @return millisecond value */ inline ecma_number_t __attr_always_inline___ ecma_date_ms_from_time (ecma_number_t time) /**< time value */ { if (ecma_number_is_nan (time)) { return time; /* time is NaN */ } ecma_number_t milli = (ecma_number_t) fmod (time, ECMA_DATE_MS_PER_SECOND); return (milli < 0) ? ECMA_DATE_MS_PER_SECOND + milli : milli; } /* ecma_date_ms_from_time */ /** * Helper function to make time value from hour, min, sec and ms. * * See also: * ECMA-262 v5, 15.9.1.11 * * Used by: * - The Date.prototype.setMilliseconds routine. * - The Date.prototype.setUTCMilliseconds routine. * - The Date.prototype.setSeconds routine. * - The Date.prototype.setUTCSeconds routine. * - The Date.prototype.setMinutes routine. * - The Date.prototype.setUTCMinutes routine. * - The Date.prototype.setHours routine. * - The Date.prototype.setUTCHours routine. * * @return time value */ ecma_number_t ecma_date_make_time (ecma_number_t hour, /**< hour value */ ecma_number_t min, /**< minute value */ ecma_number_t sec, /**< second value */ ecma_number_t ms) /**< millisecond value */ { if (ecma_number_is_nan (hour) || ecma_number_is_nan (min) || ecma_number_is_nan (sec) || ecma_number_is_nan (ms) || ecma_number_is_infinity (hour) || ecma_number_is_infinity (min) || ecma_number_is_infinity (sec) || ecma_number_is_infinity (ms)) { return ecma_number_make_nan (); } /* Replaced toInteger to ecma_number_trunc because it does the same thing. */ ecma_number_t h = ecma_number_trunc (hour); ecma_number_t m = ecma_number_trunc (min); ecma_number_t s = ecma_number_trunc (sec); ecma_number_t milli = ecma_number_trunc (ms); return (h * ECMA_DATE_MS_PER_HOUR + m * ECMA_DATE_MS_PER_MINUTE + s * ECMA_DATE_MS_PER_SECOND + milli); } /* ecma_date_make_time */ /** * Helper function to make day value from year, month and date. * * See also: * ECMA-262 v5, 15.9.1.12 * * Used by: * - The Date.prototype.setDate routine. * - The Date.prototype.setUTCDate routine. * - The Date.prototype.setMonth routine. * - The Date.prototype.setUTCMonth routine. * - The Date.prototype.setFullYear routine. * - The Date.prototype.setUTCFullYear routine. * * @return day value */ ecma_number_t ecma_date_make_day (ecma_number_t year, /**< year value */ ecma_number_t month, /**< month value */ ecma_number_t date) /**< date value */ { /* 1. */ if (ecma_number_is_nan (year) || ecma_number_is_nan (month) || ecma_number_is_nan (date) || ecma_number_is_infinity (year) || ecma_number_is_infinity (month) || ecma_number_is_infinity (date)) { return ecma_number_make_nan (); } /* 2., 3., 4. */ ecma_number_t y = ecma_number_trunc (year); ecma_number_t m = ecma_number_trunc (month); ecma_number_t dt = ecma_number_trunc (date); /* 5. */ ecma_number_t ym = y + (ecma_number_t) floor (m / 12); /* 6. */ ecma_number_t mn = (ecma_number_t) fmod (m, 12); mn = (mn < 0) ? 12 + mn : mn; /* 7. */ ecma_number_t time = ecma_date_time_from_year (ym); int32_t step = 182; int32_t delta = step; /** * The algorithm below searches the following date: ym-mn-1 * To find this time it starts from the beggining of the year (ym) * then increase it by ECMA_DATE_MS_PER_DAY until it reaches the * right date. */ if (ecma_date_year_from_time (time) == ym) { /** * Binary search to get the closest day in the previous month. * It has to use integer days so sometimes the found time * needs some more increasing which is done day by day below. */ while (delta) { if (ecma_date_month_from_time (time + step * ECMA_DATE_MS_PER_DAY) < mn) { step += delta; } else { step -= delta; } delta = delta / 2; } if (ecma_date_month_from_time (time + step) < mn) { time += step * ECMA_DATE_MS_PER_DAY; } /* Get the month's first day */ while (ecma_date_month_from_time (time) < mn) { time += ECMA_DATE_MS_PER_DAY; } if (ecma_date_month_from_time (time) == mn && ecma_date_date_from_time (time) == 1) { /* 8. */ return ecma_date_day (time) + dt - ((ecma_number_t) 1.0); } } return ecma_number_make_nan (); } /* ecma_date_make_day */ /** * Helper function to make date value from day and time. * * See also: * ECMA-262 v5, 15.9.1.13 * * @return date value */ inline ecma_number_t __attr_always_inline___ ecma_date_make_date (ecma_number_t day, /**< day value */ ecma_number_t time) /**< time value */ { if (ecma_number_is_nan (day) || ecma_number_is_nan (time) || ecma_number_is_infinity (day) || ecma_number_is_infinity (time)) { return ecma_number_make_nan (); } return day * ECMA_DATE_MS_PER_DAY + time; } /* ecma_date_make_date */ /** * Helper function to calculate number of milliseconds from time value. * * See also: * ECMA-262 v5, 15.9.1.14 * * Used by: * - The Date.prototype.setTime routine. * - The ecma_date_set_internal_property helper function. * * @return number of milliseconds */ inline ecma_number_t __attr_always_inline___ ecma_date_time_clip (ecma_number_t time) /**< time value */ { if (ecma_number_is_nan (time) || ecma_number_is_infinity (time) || fabs (time) > ECMA_DATE_MAX_VALUE) { return ecma_number_make_nan (); } return ecma_number_trunc (time); } /* ecma_date_time_clip */ /** * Helper function to calculate timezone offset. * * See also: * ECMA-262 v5, 15.9.5.26 * * Used by: * - The Date.prototype.getTimezoneOffset routine. (Generated.) * * @return timezone offset */ inline ecma_number_t __attr_always_inline___ ecma_date_timezone_offset (ecma_number_t time) /**< time value */ { if (ecma_number_is_nan (time)) { return ecma_number_make_nan (); } return (time - ecma_date_local_time (time)) / ECMA_DATE_MS_PER_MINUTE; } /* ecma_date_timezone_offset */ /** * Helper function to set Date internal property. * * Used by: * - All Date.prototype.set *routine except Date.prototype.setTime. * * @return ecma value containing the new internal time value * Returned value must be freed with ecma_free_value. */ ecma_value_t ecma_date_set_internal_property (ecma_value_t this_arg, /**< this argument */ ecma_number_t day, /**< day */ ecma_number_t time, /**< time */ ecma_date_timezone_t is_utc) /**< input is utc */ { JERRY_ASSERT (ecma_is_value_object (this_arg)); ecma_number_t *value_p = ecma_alloc_number (); ecma_number_t date = ecma_date_make_date (day, time); if (is_utc != ECMA_DATE_UTC) { date = ecma_date_utc (date); } *value_p = ecma_date_time_clip (date); ecma_object_t *obj_p = ecma_get_object_from_value (this_arg); ecma_property_t *prim_value_prop_p = ecma_get_internal_property (obj_p, ECMA_INTERNAL_PROPERTY_PRIMITIVE_NUMBER_VALUE); ecma_number_t *prim_value_num_p; prim_value_num_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_number_t, ecma_get_internal_property_value (prim_value_prop_p)); *prim_value_num_p = *value_p; return ecma_make_number_value (value_p); } /* ecma_date_set_internal_property */ /** * Common function to copy utf8 characters. * * @return next destination buffer position */ static lit_utf8_byte_t * ecma_date_value_copy_utf8_bytes (lit_utf8_byte_t *dest_p, /**< destination buffer */ const char *source_p) /**< source buffer */ { while (*source_p != LIT_CHAR_NULL) { *dest_p++ = (lit_utf8_byte_t) *source_p++; } return dest_p; } /* ecma_date_value_copy_utf8_bytes */ /** * Common function to generate fixed width, right aligned decimal numbers. * * @return next destination buffer position */ static lit_utf8_byte_t * ecma_date_value_number_to_bytes (lit_utf8_byte_t *dest_p, /**< destination buffer */ int32_t number, /**< number */ int32_t width) /**< width */ { dest_p += width; lit_utf8_byte_t *result_p = dest_p; do { dest_p--; *dest_p = (lit_utf8_byte_t) ((number % 10) + (int32_t) LIT_CHAR_0); number /= 10; } while (--width > 0); return result_p; } /* ecma_date_value_number_to_bytes */ /** * Common function to get the 3 character abbreviation of a week day. * * @return next destination buffer position */ static lit_utf8_byte_t * ecma_date_value_week_day_to_abbreviation (lit_utf8_byte_t *dest_p, /**< destination buffer */ ecma_number_t datetime_number) /**< datetime */ { const char *abbreviations_p[8] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "---" }; int32_t day = (int32_t) ecma_date_week_day (datetime_number); if (day < 0 || day > 6) { /* Just for safety, it should never happen. */ day = 7; } return ecma_date_value_copy_utf8_bytes (dest_p, abbreviations_p[day]); } /* ecma_date_value_week_day_to_abbreviation */ /** * Common function to get the 3 character abbreviation of a month. * * @return next destination buffer position */ static lit_utf8_byte_t * ecma_date_value_month_to_abbreviation (lit_utf8_byte_t *dest_p, /**< destination buffer */ ecma_number_t datetime_number) /**< datetime */ { const char *abbreviations_p[13] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "---" }; int32_t month = (int32_t) ecma_date_month_from_time (datetime_number); if (month < 0 || month > 11) { /* Just for safety, it should never happen. */ month = 12; } return ecma_date_value_copy_utf8_bytes (dest_p, abbreviations_p[(int) month]); } /* ecma_date_value_month_to_abbreviation */ /** * The common 17 character long part of ecma_date_value_to_string and ecma_date_value_to_utc_string. * * @return next destination buffer position */ static lit_utf8_byte_t * ecma_date_value_to_string_common (lit_utf8_byte_t *dest_p, /**< destination buffer */ ecma_number_t datetime_number) /**< datetime */ { ecma_number_t year = ecma_date_year_from_time (datetime_number); dest_p = ecma_date_value_number_to_bytes (dest_p, (int32_t) year, 4); *dest_p++ = LIT_CHAR_SP; ecma_number_t hours = ecma_date_hour_from_time (datetime_number); dest_p = ecma_date_value_number_to_bytes (dest_p, (int32_t) hours, 2); *dest_p++ = LIT_CHAR_COLON; ecma_number_t minutes = ecma_date_min_from_time (datetime_number); dest_p = ecma_date_value_number_to_bytes (dest_p, (int32_t) minutes, 2); *dest_p++ = LIT_CHAR_COLON; ecma_number_t seconds = ecma_date_sec_from_time (datetime_number); dest_p = ecma_date_value_number_to_bytes (dest_p, (int32_t) seconds, 2); return ecma_date_value_copy_utf8_bytes (dest_p, " GMT"); } /* ecma_date_value_to_string_common */ /** * Common function to create a time zone specific string from a numeric value. * * Used by: * - The Date routine. * - The Date.prototype.toString routine. * * @return ecma value * Returned value must be freed with ecma_free_value. */ ecma_value_t ecma_date_value_to_string (ecma_number_t datetime_number) /**< datetime */ { /* * Character length of the result string. */ const uint32_t result_string_length = 34; lit_utf8_byte_t character_buffer[result_string_length]; lit_utf8_byte_t *dest_p = character_buffer; datetime_number = ecma_date_local_time (datetime_number); dest_p = ecma_date_value_week_day_to_abbreviation (dest_p, datetime_number); *dest_p++ = LIT_CHAR_SP; dest_p = ecma_date_value_month_to_abbreviation (dest_p, datetime_number); *dest_p++ = LIT_CHAR_SP; ecma_number_t day = ecma_date_date_from_time (datetime_number); dest_p = ecma_date_value_number_to_bytes (dest_p, (int32_t) day, 2); *dest_p++ = LIT_CHAR_SP; dest_p = ecma_date_value_to_string_common (dest_p, datetime_number); int32_t time_zone = (int32_t) (ecma_date_local_tza () + ecma_date_daylight_saving_ta (datetime_number)); if (time_zone >= 0) { *dest_p++ = LIT_CHAR_PLUS; } else { *dest_p++ = LIT_CHAR_MINUS; time_zone = -time_zone; } dest_p = ecma_date_value_number_to_bytes (dest_p, time_zone / (int32_t) ECMA_DATE_MS_PER_HOUR, 2); *dest_p++ = LIT_CHAR_COLON; dest_p = ecma_date_value_number_to_bytes (dest_p, time_zone % (int32_t) ECMA_DATE_MS_PER_HOUR, 2); JERRY_ASSERT ((uint32_t) (dest_p - character_buffer) == result_string_length); ecma_string_t *date_string_p = ecma_new_ecma_string_from_utf8 (character_buffer, result_string_length); return ecma_make_string_value (date_string_p); } /* ecma_date_value_to_string */ /** * Common function to create a time zone specific string from a numeric value. * * Used by: * - The Date.prototype.toUTCString routine. * * @return ecma value * Returned value must be freed with ecma_free_value. */ ecma_value_t ecma_date_value_to_utc_string (ecma_number_t datetime_number) /**< datetime */ { /* * Character length of the result string. */ const uint32_t result_string_length = 29; lit_utf8_byte_t character_buffer[result_string_length]; lit_utf8_byte_t *dest_p = character_buffer; dest_p = ecma_date_value_week_day_to_abbreviation (dest_p, datetime_number); *dest_p++ = LIT_CHAR_COMMA; *dest_p++ = LIT_CHAR_SP; ecma_number_t day = ecma_date_date_from_time (datetime_number); dest_p = ecma_date_value_number_to_bytes (dest_p, (int32_t) day, 2); *dest_p++ = LIT_CHAR_SP; dest_p = ecma_date_value_month_to_abbreviation (dest_p, datetime_number); *dest_p++ = LIT_CHAR_SP; dest_p = ecma_date_value_to_string_common (dest_p, datetime_number); JERRY_ASSERT ((uint32_t) (dest_p - character_buffer) == result_string_length); ecma_string_t *date_string_p = ecma_new_ecma_string_from_utf8 (character_buffer, result_string_length); return ecma_make_string_value (date_string_p); } /* ecma_date_value_to_utc_string */ /** * Common function to create a ISO specific string from a numeric value. * * Used by: * - The Date.prototype.toISOString routine. * * @return ecma value * Returned value must be freed with ecma_free_value. */ ecma_value_t ecma_date_value_to_iso_string (ecma_number_t datetime_number) /**<datetime */ { /* * Character length of the result string. */ const uint32_t result_string_length = 24; lit_utf8_byte_t character_buffer[result_string_length]; lit_utf8_byte_t *dest_p = character_buffer; ecma_number_t year = ecma_date_year_from_time (datetime_number); dest_p = ecma_date_value_number_to_bytes (dest_p, (int32_t) year, 4); *dest_p++ = LIT_CHAR_MINUS; /* * Note: * 'ecma_date_month_from_time' (ECMA 262 v5, 15.9.1.4) returns a number from 0 to 11, * but we have to print the month from 1 to 12 for ISO 8601 standard (ECMA 262 v5, 15.9.1.15). */ ecma_number_t month = ecma_date_month_from_time (datetime_number) + 1; dest_p = ecma_date_value_number_to_bytes (dest_p, (int32_t) month, 2); *dest_p++ = LIT_CHAR_MINUS; ecma_number_t day = ecma_date_date_from_time (datetime_number); dest_p = ecma_date_value_number_to_bytes (dest_p, (int32_t) day, 2); *dest_p++ = LIT_CHAR_UPPERCASE_T; ecma_number_t hours = ecma_date_hour_from_time (datetime_number); dest_p = ecma_date_value_number_to_bytes (dest_p, (int32_t) hours, 2); *dest_p++ = LIT_CHAR_COLON; ecma_number_t minutes = ecma_date_min_from_time (datetime_number); dest_p = ecma_date_value_number_to_bytes (dest_p, (int32_t) minutes, 2); *dest_p++ = LIT_CHAR_COLON; ecma_number_t seconds = ecma_date_sec_from_time (datetime_number); dest_p = ecma_date_value_number_to_bytes (dest_p, (int32_t) seconds, 2); *dest_p++ = LIT_CHAR_DOT; ecma_number_t milliseconds = ecma_date_ms_from_time (datetime_number); dest_p = ecma_date_value_number_to_bytes (dest_p, (int32_t) milliseconds, 3); *dest_p++ = LIT_CHAR_UPPERCASE_Z; JERRY_ASSERT ((uint32_t) (dest_p - character_buffer) == result_string_length); ecma_string_t *date_string_p = ecma_new_ecma_string_from_utf8 (character_buffer, result_string_length); return ecma_make_string_value (date_string_p); } /* ecma_date_value_to_iso_string */ /** * Common function to create a date string from a numeric value. * * Used by: * - The Date.prototype.toDateString routine. * * @return ecma value * Returned value must be freed with ecma_free_value. */ ecma_value_t ecma_date_value_to_date_string (ecma_number_t datetime_number) /**<datetime */ { /* * Character length of the result string. */ const uint32_t result_string_length = 10; lit_utf8_byte_t character_buffer[result_string_length]; lit_utf8_byte_t *dest_p = character_buffer; ecma_number_t year = ecma_date_year_from_time (datetime_number); dest_p = ecma_date_value_number_to_bytes (dest_p, (int32_t) year, 4); *dest_p++ = LIT_CHAR_MINUS; /* * Note: * 'ecma_date_month_from_time' (ECMA 262 v5, 15.9.1.4) returns a number from 0 to 11, * but we have to print the month from 1 to 12 for ISO 8601 standard (ECMA 262 v5, 15.9.1.15). */ ecma_number_t month = ecma_date_month_from_time (datetime_number) + 1; dest_p = ecma_date_value_number_to_bytes (dest_p, (int32_t) month, 2); *dest_p++ = LIT_CHAR_MINUS; ecma_number_t day = ecma_date_date_from_time (datetime_number); dest_p = ecma_date_value_number_to_bytes (dest_p, (int32_t) day, 2); JERRY_ASSERT ((uint32_t) (dest_p - character_buffer) == result_string_length); ecma_string_t *date_string_p = ecma_new_ecma_string_from_utf8 (character_buffer, result_string_length); return ecma_make_string_value (date_string_p); } /* ecma_date_value_to_date_string */ /** * Common function to create a time string from a numeric value. * * Used by: * - The Date.prototype.toTimeString routine. * * @return ecma value * Returned value must be freed with ecma_free_value. */ ecma_value_t ecma_date_value_to_time_string (ecma_number_t datetime_number) /**<datetime */ { /* * Character length of the result string. */ const uint32_t result_string_length = 12; lit_utf8_byte_t character_buffer[result_string_length]; lit_utf8_byte_t *dest_p = character_buffer; ecma_number_t hours = ecma_date_hour_from_time (datetime_number); dest_p = ecma_date_value_number_to_bytes (dest_p, (int32_t) hours, 2); *dest_p++ = LIT_CHAR_COLON; ecma_number_t minutes = ecma_date_min_from_time (datetime_number); dest_p = ecma_date_value_number_to_bytes (dest_p, (int32_t) minutes, 2); *dest_p++ = LIT_CHAR_COLON; ecma_number_t seconds = ecma_date_sec_from_time (datetime_number); dest_p = ecma_date_value_number_to_bytes (dest_p, (int32_t) seconds, 2); *dest_p++ = LIT_CHAR_DOT; ecma_number_t milliseconds = ecma_date_ms_from_time (datetime_number); dest_p = ecma_date_value_number_to_bytes (dest_p, (int32_t) milliseconds, 3); JERRY_ASSERT ((uint32_t) (dest_p - character_buffer) == result_string_length); ecma_string_t *time_string_p = ecma_new_ecma_string_from_utf8 (character_buffer, result_string_length); return ecma_make_string_value (time_string_p); } /* ecma_date_value_to_time_string */ /** * Common function to get the primitive value of the Date object. * * Used by: * - The Date.prototype.toString routine. * - The Date.prototype.toISOString routine. * - The Date.prototype.toUTCString routine. * * @return ecma value * Returned value must be freed with ecma_free_value. */ ecma_value_t ecma_date_get_primitive_value (ecma_value_t this_arg) /**< this argument */ { ecma_value_t ret_value = ecma_make_simple_value (ECMA_SIMPLE_VALUE_EMPTY); if (!ecma_is_value_object (this_arg) || ecma_object_get_class_name (ecma_get_object_from_value (this_arg)) != LIT_MAGIC_STRING_DATE_UL) { ret_value = ecma_raise_type_error (ECMA_ERR_MSG ("Incompatible type")); } else { ecma_object_t *obj_p = ecma_get_object_from_value (this_arg); ecma_property_t *prim_value_prop_p = ecma_get_internal_property (obj_p, ECMA_INTERNAL_PROPERTY_PRIMITIVE_NUMBER_VALUE); JERRY_ASSERT (prim_value_prop_p != NULL); ecma_number_t *prim_value_num_p = ecma_alloc_number (); *prim_value_num_p = *ECMA_GET_INTERNAL_VALUE_POINTER (ecma_number_t, ecma_get_internal_property_value (prim_value_prop_p)); ret_value = ecma_make_number_value (prim_value_num_p); } return ret_value; } /* ecma_date_get_primitive_value */ /** * @} * @} */ #endif /* !CONFIG_ECMA_COMPACT_PROFILE_DISABLE_DATE_BUILTIN */
29.365559
116
0.663812
[ "object" ]
300b3ee2245f2ecfe8344ac5cf781e4c361a12fc
5,456
h
C
node_modules/couchbase/deps/lcb/src/lcbio/manager.h
tkopacz/FY19AzureAppCouchbaseDriver
cf4e244593bd229981ce2b3249dca9246e2cee1b
[ "MIT" ]
1
2019-01-08T10:04:14.000Z
2019-01-08T10:04:14.000Z
node_modules/couchbase/deps/lcb/src/lcbio/manager.h
tkopacz/FY19AzureAppCouchbaseDriver
cf4e244593bd229981ce2b3249dca9246e2cee1b
[ "MIT" ]
null
null
null
node_modules/couchbase/deps/lcb/src/lcbio/manager.h
tkopacz/FY19AzureAppCouchbaseDriver
cf4e244593bd229981ce2b3249dca9246e2cee1b
[ "MIT" ]
null
null
null
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2014 Couchbase, 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 LCBIO_MANAGER_H #define LCBIO_MANAGER_H #include "connect.h" #include "settings.h" #include "list.h" #include "ioutils.h" #include <stdio.h> /** * @file * @brief Socket pooling routines * * @details * General purpose connection manager for LCB sockets. This object is * responsible for maintaining and properly handling idle connections * and pooling them (optionally). */ /** * @ingroup lcbio * @defgroup lcbio-mgr Socket Pooling * @addtogroup lcbio-mgr * @{ */ #ifdef __cplusplus #include <map> namespace lcb { namespace io { /** @brief Socket Pool */ class Pool; /** @brief Pooled connection */ struct PoolConnInfo; /** @brief Cancellable pool request */ struct PoolRequest; struct PoolHost; } } typedef lcb::io::Pool lcbio_MGR; extern "C" { #else /* C only */ typedef struct lcbio_MGR_CDUMMY lcbio_MGR; #endif #ifdef __cplusplus } namespace lcb { namespace io { class Pool { public: /** * Create a socket pool controlled by the given settings and IO structure. * This function will increment the refcount on both the settings and table * objects. */ Pool(lcb_settings*, lcbio_pTABLE); /** * Destroy the socket pool. Note that internally this just decrements the * reference count. The object is only destroyed when its count hits zero. */ void shutdown(); /** * Request a connection from the socket pool. The semantics and prototype * of this function are by design similar to lcbio_connect() as they do the * same things. * * @param dest the host to connect to * @param timeout amount of time to wait for a connection to be estblished * @param handler a callback to invoke when the result is ready * @param arg an argument passed to the callback * @return a request handle which may be cancelled * @see lcbio_connect() */ ConnectionRequest* get(const lcb_host_t&, uint32_t, lcbio_CONNDONE_cb, void *); /** * Release a socket back into the pool. This means the socket is no longer * used and shall be available for reuse for another request. To verify these * constraints, the socket's reference count must be one. Once the socket * has been released its reference count should not be modified. */ static void put(lcbio_SOCKET *sock); /** * Mark a slot as available but discard the current connection. This should be * done if the connection itself is "dirty", i.e. has a protocol error on it * or is otherwise not suitable for reuse */ static void discard(lcbio_SOCKET *sock); /** * Like lcbio_mgr_discard() except the source connection is left untouched. It * is removed from the pool instead. * * Because the lcbio_MGR object itself has internal limits and thresholds on how * many leased and/or open connections it can contain, when a connection receives * an error it must either be discarded back to the pool (in which case the * connection is cleaned up and is freed) or it must be detached (in which case * the connection object itself still remains valid, but the pool does not know * about it, and all its counters are restored, as with lcbio_mgr_discard()). * * lcbio_mgr_discard() itself is now implemented as the equivalent to: * `lcbio_mgr_detach(mgr, conn)`; */ static void detach(lcbio_SOCKET *sock); static bool is_from_pool(const lcbio_SOCKET *sock); /** * Dumps the connection manager state to stderr */ void dump(FILE *) const; inline void ref(); inline void unref(); struct Options { Options() : maxtotal(0), maxidle(0), tmoidle(0) { } /** Maximum *total* number of connections opened by the pool. If this * number is exceeded, the pool will black hole future requests until * a new slot becomes available. */ unsigned maxtotal; /** * Maximum number of idle connections to keep around */ unsigned maxidle; /** * The amount of time the pool should wait before closing idle * connections. In microseconds */ uint32_t tmoidle; }; void set_options(const Options& opts) { options = opts; } Options& get_options() { return options; } void toJSON(hrtime_t now, Json::Value &node); private: friend struct PoolRequest; friend struct PoolConnInfo; friend struct PoolHost; typedef std::map<std::string, PoolHost*> HostMap; HostMap ht; lcb_settings *settings; lcbio_pTABLE io; Options options; unsigned refcount; }; } // namespace io } // namespace lcb #endif /**@}*/ #endif /* LCB_SOCKPOOL_H */
27.836735
85
0.669172
[ "object" ]
300fbf84e3fd2ebbaecfc9750235d709adef23f7
66,213
h
C
BCC102/include/windows/sdk/casetup.h
FarouDev/Projects-for-beginner-with-Cpp
1210457c122cb5da8f7c5a4a7386eb064e8b31b0
[ "MIT" ]
null
null
null
BCC102/include/windows/sdk/casetup.h
FarouDev/Projects-for-beginner-with-Cpp
1210457c122cb5da8f7c5a4a7386eb064e8b31b0
[ "MIT" ]
null
null
null
BCC102/include/windows/sdk/casetup.h
FarouDev/Projects-for-beginner-with-Cpp
1210457c122cb5da8f7c5a4a7386eb064e8b31b0
[ "MIT" ]
null
null
null
#pragma option push -b -a8 -pc -A- -w-pun /*P_O_Push*/ /* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 8.00.0611 */ /* @@MIDL_FILE_HEADING( ) */ /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 500 #endif /* verify that the <rpcsal.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCSAL_H_VERSION__ #define __REQUIRED_RPCSAL_H_VERSION__ 100 #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 __casetup_h__ #define __casetup_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef __ICertSrvSetupKeyInformation_FWD_DEFINED__ #define __ICertSrvSetupKeyInformation_FWD_DEFINED__ typedef interface ICertSrvSetupKeyInformation ICertSrvSetupKeyInformation; #endif /* __ICertSrvSetupKeyInformation_FWD_DEFINED__ */ #ifndef __ICertSrvSetupKeyInformationCollection_FWD_DEFINED__ #define __ICertSrvSetupKeyInformationCollection_FWD_DEFINED__ typedef interface ICertSrvSetupKeyInformationCollection ICertSrvSetupKeyInformationCollection; #endif /* __ICertSrvSetupKeyInformationCollection_FWD_DEFINED__ */ #ifndef __ICertSrvSetup_FWD_DEFINED__ #define __ICertSrvSetup_FWD_DEFINED__ typedef interface ICertSrvSetup ICertSrvSetup; #endif /* __ICertSrvSetup_FWD_DEFINED__ */ #ifndef __IMSCEPSetup_FWD_DEFINED__ #define __IMSCEPSetup_FWD_DEFINED__ typedef interface IMSCEPSetup IMSCEPSetup; #endif /* __IMSCEPSetup_FWD_DEFINED__ */ #ifndef __ICertificateEnrollmentServerSetup_FWD_DEFINED__ #define __ICertificateEnrollmentServerSetup_FWD_DEFINED__ typedef interface ICertificateEnrollmentServerSetup ICertificateEnrollmentServerSetup; #endif /* __ICertificateEnrollmentServerSetup_FWD_DEFINED__ */ #ifndef __ICertificateEnrollmentPolicyServerSetup_FWD_DEFINED__ #define __ICertificateEnrollmentPolicyServerSetup_FWD_DEFINED__ typedef interface ICertificateEnrollmentPolicyServerSetup ICertificateEnrollmentPolicyServerSetup; #endif /* __ICertificateEnrollmentPolicyServerSetup_FWD_DEFINED__ */ #ifndef __CCertSrvSetupKeyInformation_FWD_DEFINED__ #define __CCertSrvSetupKeyInformation_FWD_DEFINED__ #ifdef __cplusplus typedef class CCertSrvSetupKeyInformation CCertSrvSetupKeyInformation; #else typedef struct CCertSrvSetupKeyInformation CCertSrvSetupKeyInformation; #endif /* __cplusplus */ #endif /* __CCertSrvSetupKeyInformation_FWD_DEFINED__ */ #ifndef __CCertSrvSetup_FWD_DEFINED__ #define __CCertSrvSetup_FWD_DEFINED__ #ifdef __cplusplus typedef class CCertSrvSetup CCertSrvSetup; #else typedef struct CCertSrvSetup CCertSrvSetup; #endif /* __cplusplus */ #endif /* __CCertSrvSetup_FWD_DEFINED__ */ #ifndef __CMSCEPSetup_FWD_DEFINED__ #define __CMSCEPSetup_FWD_DEFINED__ #ifdef __cplusplus typedef class CMSCEPSetup CMSCEPSetup; #else typedef struct CMSCEPSetup CMSCEPSetup; #endif /* __cplusplus */ #endif /* __CMSCEPSetup_FWD_DEFINED__ */ #ifndef __CCertificateEnrollmentServerSetup_FWD_DEFINED__ #define __CCertificateEnrollmentServerSetup_FWD_DEFINED__ #ifdef __cplusplus typedef class CCertificateEnrollmentServerSetup CCertificateEnrollmentServerSetup; #else typedef struct CCertificateEnrollmentServerSetup CCertificateEnrollmentServerSetup; #endif /* __cplusplus */ #endif /* __CCertificateEnrollmentServerSetup_FWD_DEFINED__ */ #ifndef __CCertificateEnrollmentPolicyServerSetup_FWD_DEFINED__ #define __CCertificateEnrollmentPolicyServerSetup_FWD_DEFINED__ #ifdef __cplusplus typedef class CCertificateEnrollmentPolicyServerSetup CCertificateEnrollmentPolicyServerSetup; #else typedef struct CCertificateEnrollmentPolicyServerSetup CCertificateEnrollmentPolicyServerSetup; #endif /* __cplusplus */ #endif /* __CCertificateEnrollmentPolicyServerSetup_FWD_DEFINED__ */ /* header files for imported files */ #include "wtypes.h" #include "oaidl.h" #ifdef __cplusplus extern "C"{ #endif /* interface __MIDL_itf_casetup_0000_0000 */ /* [local] */ #include <winapifamily.h> #pragma region Desktop Family #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) extern RPC_IF_HANDLE __MIDL_itf_casetup_0000_0000_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_casetup_0000_0000_v0_0_s_ifspec; #ifndef __ICertSrvSetupKeyInformation_INTERFACE_DEFINED__ #define __ICertSrvSetupKeyInformation_INTERFACE_DEFINED__ /* interface ICertSrvSetupKeyInformation */ /* [unique][dual][helpstring][uuid][object] */ EXTERN_C const IID IID_ICertSrvSetupKeyInformation; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("6ba73778-36da-4c39-8a85-bcfa7d000793") ICertSrvSetupKeyInformation : public IDispatch { public: virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_ProviderName( /* [retval][out] */ __RPC__deref_out_opt BSTR *pVal) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_ProviderName( /* [in] */ __RPC__in const BSTR bstrVal) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Length( /* [retval][out] */ __RPC__out LONG *pVal) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_Length( /* [in] */ LONG lVal) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Existing( /* [retval][out] */ __RPC__out VARIANT_BOOL *pVal) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_Existing( /* [in] */ VARIANT_BOOL bVal) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_ContainerName( /* [retval][out] */ __RPC__deref_out_opt BSTR *pVal) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_ContainerName( /* [in] */ __RPC__in const BSTR bstrVal) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_HashAlgorithm( /* [retval][out] */ __RPC__deref_out_opt BSTR *pVal) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_HashAlgorithm( /* [in] */ __RPC__in const BSTR bstrVal) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_ExistingCACertificate( /* [retval][out] */ __RPC__out VARIANT *pVal) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_ExistingCACertificate( /* [in] */ VARIANT varVal) = 0; }; #else /* C style interface */ typedef struct ICertSrvSetupKeyInformationVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in ICertSrvSetupKeyInformation * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in ICertSrvSetupKeyInformation * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in ICertSrvSetupKeyInformation * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( __RPC__in ICertSrvSetupKeyInformation * This, /* [out] */ __RPC__out UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( __RPC__in ICertSrvSetupKeyInformation * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ __RPC__deref_out_opt ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( __RPC__in ICertSrvSetupKeyInformation * This, /* [in] */ __RPC__in REFIID riid, /* [size_is][in] */ __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames, /* [range][in] */ __RPC__in_range(0,16384) UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ __RPC__out_ecount_full(cNames) DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( ICertSrvSetupKeyInformation * This, /* [annotation][in] */ _In_ DISPID dispIdMember, /* [annotation][in] */ _In_ REFIID riid, /* [annotation][in] */ _In_ LCID lcid, /* [annotation][in] */ _In_ WORD wFlags, /* [annotation][out][in] */ _In_ DISPPARAMS *pDispParams, /* [annotation][out] */ _Out_opt_ VARIANT *pVarResult, /* [annotation][out] */ _Out_opt_ EXCEPINFO *pExcepInfo, /* [annotation][out] */ _Out_opt_ UINT *puArgErr); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ProviderName )( __RPC__in ICertSrvSetupKeyInformation * This, /* [retval][out] */ __RPC__deref_out_opt BSTR *pVal); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_ProviderName )( __RPC__in ICertSrvSetupKeyInformation * This, /* [in] */ __RPC__in const BSTR bstrVal); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Length )( __RPC__in ICertSrvSetupKeyInformation * This, /* [retval][out] */ __RPC__out LONG *pVal); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Length )( __RPC__in ICertSrvSetupKeyInformation * This, /* [in] */ LONG lVal); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Existing )( __RPC__in ICertSrvSetupKeyInformation * This, /* [retval][out] */ __RPC__out VARIANT_BOOL *pVal); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Existing )( __RPC__in ICertSrvSetupKeyInformation * This, /* [in] */ VARIANT_BOOL bVal); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ContainerName )( __RPC__in ICertSrvSetupKeyInformation * This, /* [retval][out] */ __RPC__deref_out_opt BSTR *pVal); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_ContainerName )( __RPC__in ICertSrvSetupKeyInformation * This, /* [in] */ __RPC__in const BSTR bstrVal); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_HashAlgorithm )( __RPC__in ICertSrvSetupKeyInformation * This, /* [retval][out] */ __RPC__deref_out_opt BSTR *pVal); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_HashAlgorithm )( __RPC__in ICertSrvSetupKeyInformation * This, /* [in] */ __RPC__in const BSTR bstrVal); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ExistingCACertificate )( __RPC__in ICertSrvSetupKeyInformation * This, /* [retval][out] */ __RPC__out VARIANT *pVal); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_ExistingCACertificate )( __RPC__in ICertSrvSetupKeyInformation * This, /* [in] */ VARIANT varVal); END_INTERFACE } ICertSrvSetupKeyInformationVtbl; interface ICertSrvSetupKeyInformation { CONST_VTBL struct ICertSrvSetupKeyInformationVtbl *lpVtbl; }; #ifdef COBJMACROS #define ICertSrvSetupKeyInformation_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ICertSrvSetupKeyInformation_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define ICertSrvSetupKeyInformation_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define ICertSrvSetupKeyInformation_GetTypeInfoCount(This,pctinfo) \ ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define ICertSrvSetupKeyInformation_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define ICertSrvSetupKeyInformation_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define ICertSrvSetupKeyInformation_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define ICertSrvSetupKeyInformation_get_ProviderName(This,pVal) \ ( (This)->lpVtbl -> get_ProviderName(This,pVal) ) #define ICertSrvSetupKeyInformation_put_ProviderName(This,bstrVal) \ ( (This)->lpVtbl -> put_ProviderName(This,bstrVal) ) #define ICertSrvSetupKeyInformation_get_Length(This,pVal) \ ( (This)->lpVtbl -> get_Length(This,pVal) ) #define ICertSrvSetupKeyInformation_put_Length(This,lVal) \ ( (This)->lpVtbl -> put_Length(This,lVal) ) #define ICertSrvSetupKeyInformation_get_Existing(This,pVal) \ ( (This)->lpVtbl -> get_Existing(This,pVal) ) #define ICertSrvSetupKeyInformation_put_Existing(This,bVal) \ ( (This)->lpVtbl -> put_Existing(This,bVal) ) #define ICertSrvSetupKeyInformation_get_ContainerName(This,pVal) \ ( (This)->lpVtbl -> get_ContainerName(This,pVal) ) #define ICertSrvSetupKeyInformation_put_ContainerName(This,bstrVal) \ ( (This)->lpVtbl -> put_ContainerName(This,bstrVal) ) #define ICertSrvSetupKeyInformation_get_HashAlgorithm(This,pVal) \ ( (This)->lpVtbl -> get_HashAlgorithm(This,pVal) ) #define ICertSrvSetupKeyInformation_put_HashAlgorithm(This,bstrVal) \ ( (This)->lpVtbl -> put_HashAlgorithm(This,bstrVal) ) #define ICertSrvSetupKeyInformation_get_ExistingCACertificate(This,pVal) \ ( (This)->lpVtbl -> get_ExistingCACertificate(This,pVal) ) #define ICertSrvSetupKeyInformation_put_ExistingCACertificate(This,varVal) \ ( (This)->lpVtbl -> put_ExistingCACertificate(This,varVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __ICertSrvSetupKeyInformation_INTERFACE_DEFINED__ */ #ifndef __ICertSrvSetupKeyInformationCollection_INTERFACE_DEFINED__ #define __ICertSrvSetupKeyInformationCollection_INTERFACE_DEFINED__ /* interface ICertSrvSetupKeyInformationCollection */ /* [unique][helpstring][nonextensible][dual][uuid][object] */ EXTERN_C const IID IID_ICertSrvSetupKeyInformationCollection; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("e65c8b00-e58f-41f9-a9ec-a28d7427c844") ICertSrvSetupKeyInformationCollection : public IDispatch { public: virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get__NewEnum( /* [retval][out] */ __RPC__deref_out_opt IUnknown **ppVal) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Item( /* [in] */ LONG Index, /* [retval][out] */ __RPC__out VARIANT *pVal) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Count( /* [retval][out] */ __RPC__out LONG *pVal) = 0; virtual HRESULT STDMETHODCALLTYPE Add( /* [in] */ __RPC__in_opt ICertSrvSetupKeyInformation *pIKeyInformation) = 0; }; #else /* C style interface */ typedef struct ICertSrvSetupKeyInformationCollectionVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in ICertSrvSetupKeyInformationCollection * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in ICertSrvSetupKeyInformationCollection * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in ICertSrvSetupKeyInformationCollection * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( __RPC__in ICertSrvSetupKeyInformationCollection * This, /* [out] */ __RPC__out UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( __RPC__in ICertSrvSetupKeyInformationCollection * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ __RPC__deref_out_opt ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( __RPC__in ICertSrvSetupKeyInformationCollection * This, /* [in] */ __RPC__in REFIID riid, /* [size_is][in] */ __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames, /* [range][in] */ __RPC__in_range(0,16384) UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ __RPC__out_ecount_full(cNames) DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( ICertSrvSetupKeyInformationCollection * This, /* [annotation][in] */ _In_ DISPID dispIdMember, /* [annotation][in] */ _In_ REFIID riid, /* [annotation][in] */ _In_ LCID lcid, /* [annotation][in] */ _In_ WORD wFlags, /* [annotation][out][in] */ _In_ DISPPARAMS *pDispParams, /* [annotation][out] */ _Out_opt_ VARIANT *pVarResult, /* [annotation][out] */ _Out_opt_ EXCEPINFO *pExcepInfo, /* [annotation][out] */ _Out_opt_ UINT *puArgErr); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get__NewEnum )( __RPC__in ICertSrvSetupKeyInformationCollection * This, /* [retval][out] */ __RPC__deref_out_opt IUnknown **ppVal); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Item )( __RPC__in ICertSrvSetupKeyInformationCollection * This, /* [in] */ LONG Index, /* [retval][out] */ __RPC__out VARIANT *pVal); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Count )( __RPC__in ICertSrvSetupKeyInformationCollection * This, /* [retval][out] */ __RPC__out LONG *pVal); HRESULT ( STDMETHODCALLTYPE *Add )( __RPC__in ICertSrvSetupKeyInformationCollection * This, /* [in] */ __RPC__in_opt ICertSrvSetupKeyInformation *pIKeyInformation); END_INTERFACE } ICertSrvSetupKeyInformationCollectionVtbl; interface ICertSrvSetupKeyInformationCollection { CONST_VTBL struct ICertSrvSetupKeyInformationCollectionVtbl *lpVtbl; }; #ifdef COBJMACROS #define ICertSrvSetupKeyInformationCollection_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ICertSrvSetupKeyInformationCollection_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define ICertSrvSetupKeyInformationCollection_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define ICertSrvSetupKeyInformationCollection_GetTypeInfoCount(This,pctinfo) \ ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define ICertSrvSetupKeyInformationCollection_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define ICertSrvSetupKeyInformationCollection_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define ICertSrvSetupKeyInformationCollection_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define ICertSrvSetupKeyInformationCollection_get__NewEnum(This,ppVal) \ ( (This)->lpVtbl -> get__NewEnum(This,ppVal) ) #define ICertSrvSetupKeyInformationCollection_get_Item(This,Index,pVal) \ ( (This)->lpVtbl -> get_Item(This,Index,pVal) ) #define ICertSrvSetupKeyInformationCollection_get_Count(This,pVal) \ ( (This)->lpVtbl -> get_Count(This,pVal) ) #define ICertSrvSetupKeyInformationCollection_Add(This,pIKeyInformation) \ ( (This)->lpVtbl -> Add(This,pIKeyInformation) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __ICertSrvSetupKeyInformationCollection_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_casetup_0000_0002 */ /* [local] */ typedef /* [public][public][public][public] */ enum __MIDL___MIDL_itf_casetup_0000_0002_0001 { ENUM_SETUPPROP_INVALID = -1, ENUM_SETUPPROP_CATYPE = 0, ENUM_SETUPPROP_CAKEYINFORMATION = 1, ENUM_SETUPPROP_INTERACTIVE = 2, ENUM_SETUPPROP_CANAME = 3, ENUM_SETUPPROP_CADSSUFFIX = 4, ENUM_SETUPPROP_VALIDITYPERIOD = 5, ENUM_SETUPPROP_VALIDITYPERIODUNIT = 6, ENUM_SETUPPROP_EXPIRATIONDATE = 7, ENUM_SETUPPROP_PRESERVEDATABASE = 8, ENUM_SETUPPROP_DATABASEDIRECTORY = 9, ENUM_SETUPPROP_LOGDIRECTORY = 10, ENUM_SETUPPROP_SHAREDFOLDER = 11, ENUM_SETUPPROP_PARENTCAMACHINE = 12, ENUM_SETUPPROP_PARENTCANAME = 13, ENUM_SETUPPROP_REQUESTFILE = 14, ENUM_SETUPPROP_WEBCAMACHINE = 15, ENUM_SETUPPROP_WEBCANAME = 16 } CASetupProperty; extern RPC_IF_HANDLE __MIDL_itf_casetup_0000_0002_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_casetup_0000_0002_v0_0_s_ifspec; #ifndef __ICertSrvSetup_INTERFACE_DEFINED__ #define __ICertSrvSetup_INTERFACE_DEFINED__ /* interface ICertSrvSetup */ /* [unique][dual][helpstring][uuid][object] */ EXTERN_C const IID IID_ICertSrvSetup; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("b760a1bb-4784-44c0-8f12-555f0780ff25") ICertSrvSetup : public IDispatch { public: virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_CAErrorId( /* [retval][out] */ __RPC__out LONG *pVal) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_CAErrorString( /* [retval][out] */ __RPC__deref_out_opt BSTR *pVal) = 0; virtual HRESULT STDMETHODCALLTYPE InitializeDefaults( /* [in] */ VARIANT_BOOL bServer, /* [in] */ VARIANT_BOOL bClient) = 0; virtual HRESULT STDMETHODCALLTYPE GetCASetupProperty( /* [in] */ CASetupProperty propertyId, /* [retval][out] */ __RPC__out VARIANT *pPropertyValue) = 0; virtual HRESULT STDMETHODCALLTYPE SetCASetupProperty( /* [in] */ CASetupProperty propertyId, /* [in] */ __RPC__in VARIANT *pPropertyValue) = 0; virtual HRESULT STDMETHODCALLTYPE IsPropertyEditable( /* [in] */ CASetupProperty propertyId, /* [retval][out] */ __RPC__out VARIANT_BOOL *pbEditable) = 0; virtual HRESULT STDMETHODCALLTYPE GetSupportedCATypes( /* [retval][out] */ __RPC__out VARIANT *pCATypes) = 0; virtual HRESULT STDMETHODCALLTYPE GetProviderNameList( /* [retval][out] */ __RPC__out VARIANT *pVal) = 0; virtual HRESULT STDMETHODCALLTYPE GetKeyLengthList( /* [in] */ __RPC__in const BSTR bstrProviderName, /* [retval][out] */ __RPC__out VARIANT *pVal) = 0; virtual HRESULT STDMETHODCALLTYPE GetHashAlgorithmList( /* [in] */ __RPC__in const BSTR bstrProviderName, /* [retval][out] */ __RPC__out VARIANT *pVal) = 0; virtual HRESULT STDMETHODCALLTYPE GetPrivateKeyContainerList( /* [in] */ __RPC__in const BSTR bstrProviderName, /* [retval][out] */ __RPC__out VARIANT *pVal) = 0; virtual HRESULT STDMETHODCALLTYPE GetExistingCACertificates( /* [retval][out] */ __RPC__deref_out_opt ICertSrvSetupKeyInformationCollection **ppVal) = 0; virtual HRESULT STDMETHODCALLTYPE CAImportPFX( /* [in] */ __RPC__in const BSTR bstrFileName, /* [in] */ __RPC__in const BSTR bstrPasswd, /* [in] */ VARIANT_BOOL bOverwriteExistingKey, /* [retval][out] */ __RPC__deref_out_opt ICertSrvSetupKeyInformation **ppVal) = 0; virtual HRESULT STDMETHODCALLTYPE SetCADistinguishedName( /* [in] */ __RPC__in const BSTR bstrCADN, /* [in] */ VARIANT_BOOL bIgnoreUnicode, /* [in] */ VARIANT_BOOL bOverwriteExistingKey, /* [in] */ VARIANT_BOOL bOverwriteExistingCAInDS) = 0; virtual HRESULT STDMETHODCALLTYPE SetDatabaseInformation( /* [in] */ __RPC__in const BSTR bstrDBDirectory, /* [in] */ __RPC__in const BSTR bstrLogDirectory, /* [in] */ __RPC__in const BSTR bstrSharedFolder, /* [in] */ VARIANT_BOOL bForceOverwrite) = 0; virtual HRESULT STDMETHODCALLTYPE SetParentCAInformation( /* [in] */ __RPC__in const BSTR bstrCAConfiguration) = 0; virtual HRESULT STDMETHODCALLTYPE SetWebCAInformation( /* [in] */ __RPC__in const BSTR bstrCAConfiguration) = 0; virtual HRESULT STDMETHODCALLTYPE Install( void) = 0; virtual HRESULT STDMETHODCALLTYPE PreUnInstall( /* [in] */ VARIANT_BOOL bClientOnly) = 0; virtual HRESULT STDMETHODCALLTYPE PostUnInstall( void) = 0; }; #else /* C style interface */ typedef struct ICertSrvSetupVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in ICertSrvSetup * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in ICertSrvSetup * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in ICertSrvSetup * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( __RPC__in ICertSrvSetup * This, /* [out] */ __RPC__out UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( __RPC__in ICertSrvSetup * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ __RPC__deref_out_opt ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( __RPC__in ICertSrvSetup * This, /* [in] */ __RPC__in REFIID riid, /* [size_is][in] */ __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames, /* [range][in] */ __RPC__in_range(0,16384) UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ __RPC__out_ecount_full(cNames) DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( ICertSrvSetup * This, /* [annotation][in] */ _In_ DISPID dispIdMember, /* [annotation][in] */ _In_ REFIID riid, /* [annotation][in] */ _In_ LCID lcid, /* [annotation][in] */ _In_ WORD wFlags, /* [annotation][out][in] */ _In_ DISPPARAMS *pDispParams, /* [annotation][out] */ _Out_opt_ VARIANT *pVarResult, /* [annotation][out] */ _Out_opt_ EXCEPINFO *pExcepInfo, /* [annotation][out] */ _Out_opt_ UINT *puArgErr); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_CAErrorId )( __RPC__in ICertSrvSetup * This, /* [retval][out] */ __RPC__out LONG *pVal); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_CAErrorString )( __RPC__in ICertSrvSetup * This, /* [retval][out] */ __RPC__deref_out_opt BSTR *pVal); HRESULT ( STDMETHODCALLTYPE *InitializeDefaults )( __RPC__in ICertSrvSetup * This, /* [in] */ VARIANT_BOOL bServer, /* [in] */ VARIANT_BOOL bClient); HRESULT ( STDMETHODCALLTYPE *GetCASetupProperty )( __RPC__in ICertSrvSetup * This, /* [in] */ CASetupProperty propertyId, /* [retval][out] */ __RPC__out VARIANT *pPropertyValue); HRESULT ( STDMETHODCALLTYPE *SetCASetupProperty )( __RPC__in ICertSrvSetup * This, /* [in] */ CASetupProperty propertyId, /* [in] */ __RPC__in VARIANT *pPropertyValue); HRESULT ( STDMETHODCALLTYPE *IsPropertyEditable )( __RPC__in ICertSrvSetup * This, /* [in] */ CASetupProperty propertyId, /* [retval][out] */ __RPC__out VARIANT_BOOL *pbEditable); HRESULT ( STDMETHODCALLTYPE *GetSupportedCATypes )( __RPC__in ICertSrvSetup * This, /* [retval][out] */ __RPC__out VARIANT *pCATypes); HRESULT ( STDMETHODCALLTYPE *GetProviderNameList )( __RPC__in ICertSrvSetup * This, /* [retval][out] */ __RPC__out VARIANT *pVal); HRESULT ( STDMETHODCALLTYPE *GetKeyLengthList )( __RPC__in ICertSrvSetup * This, /* [in] */ __RPC__in const BSTR bstrProviderName, /* [retval][out] */ __RPC__out VARIANT *pVal); HRESULT ( STDMETHODCALLTYPE *GetHashAlgorithmList )( __RPC__in ICertSrvSetup * This, /* [in] */ __RPC__in const BSTR bstrProviderName, /* [retval][out] */ __RPC__out VARIANT *pVal); HRESULT ( STDMETHODCALLTYPE *GetPrivateKeyContainerList )( __RPC__in ICertSrvSetup * This, /* [in] */ __RPC__in const BSTR bstrProviderName, /* [retval][out] */ __RPC__out VARIANT *pVal); HRESULT ( STDMETHODCALLTYPE *GetExistingCACertificates )( __RPC__in ICertSrvSetup * This, /* [retval][out] */ __RPC__deref_out_opt ICertSrvSetupKeyInformationCollection **ppVal); HRESULT ( STDMETHODCALLTYPE *CAImportPFX )( __RPC__in ICertSrvSetup * This, /* [in] */ __RPC__in const BSTR bstrFileName, /* [in] */ __RPC__in const BSTR bstrPasswd, /* [in] */ VARIANT_BOOL bOverwriteExistingKey, /* [retval][out] */ __RPC__deref_out_opt ICertSrvSetupKeyInformation **ppVal); HRESULT ( STDMETHODCALLTYPE *SetCADistinguishedName )( __RPC__in ICertSrvSetup * This, /* [in] */ __RPC__in const BSTR bstrCADN, /* [in] */ VARIANT_BOOL bIgnoreUnicode, /* [in] */ VARIANT_BOOL bOverwriteExistingKey, /* [in] */ VARIANT_BOOL bOverwriteExistingCAInDS); HRESULT ( STDMETHODCALLTYPE *SetDatabaseInformation )( __RPC__in ICertSrvSetup * This, /* [in] */ __RPC__in const BSTR bstrDBDirectory, /* [in] */ __RPC__in const BSTR bstrLogDirectory, /* [in] */ __RPC__in const BSTR bstrSharedFolder, /* [in] */ VARIANT_BOOL bForceOverwrite); HRESULT ( STDMETHODCALLTYPE *SetParentCAInformation )( __RPC__in ICertSrvSetup * This, /* [in] */ __RPC__in const BSTR bstrCAConfiguration); HRESULT ( STDMETHODCALLTYPE *SetWebCAInformation )( __RPC__in ICertSrvSetup * This, /* [in] */ __RPC__in const BSTR bstrCAConfiguration); HRESULT ( STDMETHODCALLTYPE *Install )( __RPC__in ICertSrvSetup * This); HRESULT ( STDMETHODCALLTYPE *PreUnInstall )( __RPC__in ICertSrvSetup * This, /* [in] */ VARIANT_BOOL bClientOnly); HRESULT ( STDMETHODCALLTYPE *PostUnInstall )( __RPC__in ICertSrvSetup * This); END_INTERFACE } ICertSrvSetupVtbl; interface ICertSrvSetup { CONST_VTBL struct ICertSrvSetupVtbl *lpVtbl; }; #ifdef COBJMACROS #define ICertSrvSetup_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ICertSrvSetup_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define ICertSrvSetup_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define ICertSrvSetup_GetTypeInfoCount(This,pctinfo) \ ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define ICertSrvSetup_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define ICertSrvSetup_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define ICertSrvSetup_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define ICertSrvSetup_get_CAErrorId(This,pVal) \ ( (This)->lpVtbl -> get_CAErrorId(This,pVal) ) #define ICertSrvSetup_get_CAErrorString(This,pVal) \ ( (This)->lpVtbl -> get_CAErrorString(This,pVal) ) #define ICertSrvSetup_InitializeDefaults(This,bServer,bClient) \ ( (This)->lpVtbl -> InitializeDefaults(This,bServer,bClient) ) #define ICertSrvSetup_GetCASetupProperty(This,propertyId,pPropertyValue) \ ( (This)->lpVtbl -> GetCASetupProperty(This,propertyId,pPropertyValue) ) #define ICertSrvSetup_SetCASetupProperty(This,propertyId,pPropertyValue) \ ( (This)->lpVtbl -> SetCASetupProperty(This,propertyId,pPropertyValue) ) #define ICertSrvSetup_IsPropertyEditable(This,propertyId,pbEditable) \ ( (This)->lpVtbl -> IsPropertyEditable(This,propertyId,pbEditable) ) #define ICertSrvSetup_GetSupportedCATypes(This,pCATypes) \ ( (This)->lpVtbl -> GetSupportedCATypes(This,pCATypes) ) #define ICertSrvSetup_GetProviderNameList(This,pVal) \ ( (This)->lpVtbl -> GetProviderNameList(This,pVal) ) #define ICertSrvSetup_GetKeyLengthList(This,bstrProviderName,pVal) \ ( (This)->lpVtbl -> GetKeyLengthList(This,bstrProviderName,pVal) ) #define ICertSrvSetup_GetHashAlgorithmList(This,bstrProviderName,pVal) \ ( (This)->lpVtbl -> GetHashAlgorithmList(This,bstrProviderName,pVal) ) #define ICertSrvSetup_GetPrivateKeyContainerList(This,bstrProviderName,pVal) \ ( (This)->lpVtbl -> GetPrivateKeyContainerList(This,bstrProviderName,pVal) ) #define ICertSrvSetup_GetExistingCACertificates(This,ppVal) \ ( (This)->lpVtbl -> GetExistingCACertificates(This,ppVal) ) #define ICertSrvSetup_CAImportPFX(This,bstrFileName,bstrPasswd,bOverwriteExistingKey,ppVal) \ ( (This)->lpVtbl -> CAImportPFX(This,bstrFileName,bstrPasswd,bOverwriteExistingKey,ppVal) ) #define ICertSrvSetup_SetCADistinguishedName(This,bstrCADN,bIgnoreUnicode,bOverwriteExistingKey,bOverwriteExistingCAInDS) \ ( (This)->lpVtbl -> SetCADistinguishedName(This,bstrCADN,bIgnoreUnicode,bOverwriteExistingKey,bOverwriteExistingCAInDS) ) #define ICertSrvSetup_SetDatabaseInformation(This,bstrDBDirectory,bstrLogDirectory,bstrSharedFolder,bForceOverwrite) \ ( (This)->lpVtbl -> SetDatabaseInformation(This,bstrDBDirectory,bstrLogDirectory,bstrSharedFolder,bForceOverwrite) ) #define ICertSrvSetup_SetParentCAInformation(This,bstrCAConfiguration) \ ( (This)->lpVtbl -> SetParentCAInformation(This,bstrCAConfiguration) ) #define ICertSrvSetup_SetWebCAInformation(This,bstrCAConfiguration) \ ( (This)->lpVtbl -> SetWebCAInformation(This,bstrCAConfiguration) ) #define ICertSrvSetup_Install(This) \ ( (This)->lpVtbl -> Install(This) ) #define ICertSrvSetup_PreUnInstall(This,bClientOnly) \ ( (This)->lpVtbl -> PreUnInstall(This,bClientOnly) ) #define ICertSrvSetup_PostUnInstall(This) \ ( (This)->lpVtbl -> PostUnInstall(This) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __ICertSrvSetup_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_casetup_0000_0003 */ /* [local] */ typedef /* [public][public][public] */ enum __MIDL___MIDL_itf_casetup_0000_0003_0001 { ENUM_CEPSETUPPROP_USELOCALSYSTEM = 0, ENUM_CEPSETUPPROP_USECHALLENGE = 1, ENUM_CEPSETUPPROP_RANAME_CN = 2, ENUM_CEPSETUPPROP_RANAME_EMAIL = 3, ENUM_CEPSETUPPROP_RANAME_COMPANY = 4, ENUM_CEPSETUPPROP_RANAME_DEPT = 5, ENUM_CEPSETUPPROP_RANAME_CITY = 6, ENUM_CEPSETUPPROP_RANAME_STATE = 7, ENUM_CEPSETUPPROP_RANAME_COUNTRY = 8, ENUM_CEPSETUPPROP_SIGNINGKEYINFORMATION = 9, ENUM_CEPSETUPPROP_EXCHANGEKEYINFORMATION = 10, ENUM_CEPSETUPPROP_CAINFORMATION = 11, ENUM_CEPSETUPPROP_MSCEPURL = 12, ENUM_CEPSETUPPROP_CHALLENGEURL = 13 } MSCEPSetupProperty; extern RPC_IF_HANDLE __MIDL_itf_casetup_0000_0003_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_casetup_0000_0003_v0_0_s_ifspec; #ifndef __IMSCEPSetup_INTERFACE_DEFINED__ #define __IMSCEPSetup_INTERFACE_DEFINED__ /* interface IMSCEPSetup */ /* [unique][dual][helpstring][uuid][object] */ EXTERN_C const IID IID_IMSCEPSetup; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("4f7761bb-9f3b-4592-9ee0-9a73259c313e") IMSCEPSetup : public IDispatch { public: virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_MSCEPErrorId( /* [retval][out] */ __RPC__out LONG *pVal) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_MSCEPErrorString( /* [retval][out] */ __RPC__deref_out_opt BSTR *pVal) = 0; virtual HRESULT STDMETHODCALLTYPE InitializeDefaults( void) = 0; virtual HRESULT STDMETHODCALLTYPE GetMSCEPSetupProperty( /* [in] */ MSCEPSetupProperty propertyId, /* [retval][out] */ __RPC__out VARIANT *pVal) = 0; virtual HRESULT STDMETHODCALLTYPE SetMSCEPSetupProperty( /* [in] */ MSCEPSetupProperty propertyId, /* [in] */ __RPC__in VARIANT *pPropertyValue) = 0; virtual HRESULT STDMETHODCALLTYPE SetAccountInformation( /* [in] */ __RPC__in const BSTR bstrUserName, /* [in] */ __RPC__in const BSTR bstrPassword) = 0; virtual HRESULT STDMETHODCALLTYPE IsMSCEPStoreEmpty( /* [retval][out] */ __RPC__out VARIANT_BOOL *pbEmpty) = 0; virtual HRESULT STDMETHODCALLTYPE GetProviderNameList( /* [in] */ VARIANT_BOOL bExchange, /* [retval][out] */ __RPC__out VARIANT *pVal) = 0; virtual HRESULT STDMETHODCALLTYPE GetKeyLengthList( /* [in] */ VARIANT_BOOL bExchange, /* [in] */ __RPC__in const BSTR bstrProviderName, /* [retval][out] */ __RPC__out VARIANT *pVal) = 0; virtual HRESULT STDMETHODCALLTYPE Install( void) = 0; virtual HRESULT STDMETHODCALLTYPE PreUnInstall( void) = 0; virtual HRESULT STDMETHODCALLTYPE PostUnInstall( void) = 0; }; #else /* C style interface */ typedef struct IMSCEPSetupVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IMSCEPSetup * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IMSCEPSetup * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IMSCEPSetup * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( __RPC__in IMSCEPSetup * This, /* [out] */ __RPC__out UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( __RPC__in IMSCEPSetup * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ __RPC__deref_out_opt ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( __RPC__in IMSCEPSetup * This, /* [in] */ __RPC__in REFIID riid, /* [size_is][in] */ __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames, /* [range][in] */ __RPC__in_range(0,16384) UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ __RPC__out_ecount_full(cNames) DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( IMSCEPSetup * This, /* [annotation][in] */ _In_ DISPID dispIdMember, /* [annotation][in] */ _In_ REFIID riid, /* [annotation][in] */ _In_ LCID lcid, /* [annotation][in] */ _In_ WORD wFlags, /* [annotation][out][in] */ _In_ DISPPARAMS *pDispParams, /* [annotation][out] */ _Out_opt_ VARIANT *pVarResult, /* [annotation][out] */ _Out_opt_ EXCEPINFO *pExcepInfo, /* [annotation][out] */ _Out_opt_ UINT *puArgErr); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_MSCEPErrorId )( __RPC__in IMSCEPSetup * This, /* [retval][out] */ __RPC__out LONG *pVal); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_MSCEPErrorString )( __RPC__in IMSCEPSetup * This, /* [retval][out] */ __RPC__deref_out_opt BSTR *pVal); HRESULT ( STDMETHODCALLTYPE *InitializeDefaults )( __RPC__in IMSCEPSetup * This); HRESULT ( STDMETHODCALLTYPE *GetMSCEPSetupProperty )( __RPC__in IMSCEPSetup * This, /* [in] */ MSCEPSetupProperty propertyId, /* [retval][out] */ __RPC__out VARIANT *pVal); HRESULT ( STDMETHODCALLTYPE *SetMSCEPSetupProperty )( __RPC__in IMSCEPSetup * This, /* [in] */ MSCEPSetupProperty propertyId, /* [in] */ __RPC__in VARIANT *pPropertyValue); HRESULT ( STDMETHODCALLTYPE *SetAccountInformation )( __RPC__in IMSCEPSetup * This, /* [in] */ __RPC__in const BSTR bstrUserName, /* [in] */ __RPC__in const BSTR bstrPassword); HRESULT ( STDMETHODCALLTYPE *IsMSCEPStoreEmpty )( __RPC__in IMSCEPSetup * This, /* [retval][out] */ __RPC__out VARIANT_BOOL *pbEmpty); HRESULT ( STDMETHODCALLTYPE *GetProviderNameList )( __RPC__in IMSCEPSetup * This, /* [in] */ VARIANT_BOOL bExchange, /* [retval][out] */ __RPC__out VARIANT *pVal); HRESULT ( STDMETHODCALLTYPE *GetKeyLengthList )( __RPC__in IMSCEPSetup * This, /* [in] */ VARIANT_BOOL bExchange, /* [in] */ __RPC__in const BSTR bstrProviderName, /* [retval][out] */ __RPC__out VARIANT *pVal); HRESULT ( STDMETHODCALLTYPE *Install )( __RPC__in IMSCEPSetup * This); HRESULT ( STDMETHODCALLTYPE *PreUnInstall )( __RPC__in IMSCEPSetup * This); HRESULT ( STDMETHODCALLTYPE *PostUnInstall )( __RPC__in IMSCEPSetup * This); END_INTERFACE } IMSCEPSetupVtbl; interface IMSCEPSetup { CONST_VTBL struct IMSCEPSetupVtbl *lpVtbl; }; #ifdef COBJMACROS #define IMSCEPSetup_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IMSCEPSetup_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IMSCEPSetup_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IMSCEPSetup_GetTypeInfoCount(This,pctinfo) \ ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define IMSCEPSetup_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define IMSCEPSetup_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define IMSCEPSetup_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define IMSCEPSetup_get_MSCEPErrorId(This,pVal) \ ( (This)->lpVtbl -> get_MSCEPErrorId(This,pVal) ) #define IMSCEPSetup_get_MSCEPErrorString(This,pVal) \ ( (This)->lpVtbl -> get_MSCEPErrorString(This,pVal) ) #define IMSCEPSetup_InitializeDefaults(This) \ ( (This)->lpVtbl -> InitializeDefaults(This) ) #define IMSCEPSetup_GetMSCEPSetupProperty(This,propertyId,pVal) \ ( (This)->lpVtbl -> GetMSCEPSetupProperty(This,propertyId,pVal) ) #define IMSCEPSetup_SetMSCEPSetupProperty(This,propertyId,pPropertyValue) \ ( (This)->lpVtbl -> SetMSCEPSetupProperty(This,propertyId,pPropertyValue) ) #define IMSCEPSetup_SetAccountInformation(This,bstrUserName,bstrPassword) \ ( (This)->lpVtbl -> SetAccountInformation(This,bstrUserName,bstrPassword) ) #define IMSCEPSetup_IsMSCEPStoreEmpty(This,pbEmpty) \ ( (This)->lpVtbl -> IsMSCEPStoreEmpty(This,pbEmpty) ) #define IMSCEPSetup_GetProviderNameList(This,bExchange,pVal) \ ( (This)->lpVtbl -> GetProviderNameList(This,bExchange,pVal) ) #define IMSCEPSetup_GetKeyLengthList(This,bExchange,bstrProviderName,pVal) \ ( (This)->lpVtbl -> GetKeyLengthList(This,bExchange,bstrProviderName,pVal) ) #define IMSCEPSetup_Install(This) \ ( (This)->lpVtbl -> Install(This) ) #define IMSCEPSetup_PreUnInstall(This) \ ( (This)->lpVtbl -> PreUnInstall(This) ) #define IMSCEPSetup_PostUnInstall(This) \ ( (This)->lpVtbl -> PostUnInstall(This) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IMSCEPSetup_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_casetup_0000_0004 */ /* [local] */ typedef /* [public][public][public] */ enum __MIDL___MIDL_itf_casetup_0000_0004_0001 { ENUM_CESSETUPPROP_USE_IISAPPPOOLIDENTITY = 0, ENUM_CESSETUPPROP_CACONFIG = 1, ENUM_CESSETUPPROP_AUTHENTICATION = 2, ENUM_CESSETUPPROP_SSLCERTHASH = 3, ENUM_CESSETUPPROP_URL = 4, ENUM_CESSETUPPROP_RENEWALONLY = 5, ENUM_CESSETUPPROP_ALLOW_KEYBASED_RENEWAL = 6 } CESSetupProperty; extern RPC_IF_HANDLE __MIDL_itf_casetup_0000_0004_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_casetup_0000_0004_v0_0_s_ifspec; #ifndef __ICertificateEnrollmentServerSetup_INTERFACE_DEFINED__ #define __ICertificateEnrollmentServerSetup_INTERFACE_DEFINED__ /* interface ICertificateEnrollmentServerSetup */ /* [unique][dual][helpstring][uuid][object] */ EXTERN_C const IID IID_ICertificateEnrollmentServerSetup; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("70027FDB-9DD9-4921-8944-B35CB31BD2EC") ICertificateEnrollmentServerSetup : public IDispatch { public: virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_ErrorString( /* [retval][out] */ __RPC__deref_out_opt BSTR *pVal) = 0; virtual HRESULT STDMETHODCALLTYPE InitializeInstallDefaults( void) = 0; virtual HRESULT STDMETHODCALLTYPE GetProperty( /* [in] */ CESSetupProperty propertyId, /* [retval][out] */ __RPC__out VARIANT *pPropertyValue) = 0; virtual HRESULT STDMETHODCALLTYPE SetProperty( /* [in] */ CESSetupProperty propertyId, /* [in] */ __RPC__in VARIANT *pPropertyValue) = 0; virtual HRESULT STDMETHODCALLTYPE SetApplicationPoolCredentials( /* [in] */ __RPC__in const BSTR bstrUsername, /* [in] */ __RPC__in const BSTR bstrPassword) = 0; virtual HRESULT STDMETHODCALLTYPE Install( void) = 0; virtual HRESULT STDMETHODCALLTYPE UnInstall( /* [optional][in] */ __RPC__in VARIANT *pCAConfig, /* [optional][in] */ __RPC__in VARIANT *pAuthentication) = 0; }; #else /* C style interface */ typedef struct ICertificateEnrollmentServerSetupVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in ICertificateEnrollmentServerSetup * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in ICertificateEnrollmentServerSetup * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in ICertificateEnrollmentServerSetup * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( __RPC__in ICertificateEnrollmentServerSetup * This, /* [out] */ __RPC__out UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( __RPC__in ICertificateEnrollmentServerSetup * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ __RPC__deref_out_opt ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( __RPC__in ICertificateEnrollmentServerSetup * This, /* [in] */ __RPC__in REFIID riid, /* [size_is][in] */ __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames, /* [range][in] */ __RPC__in_range(0,16384) UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ __RPC__out_ecount_full(cNames) DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( ICertificateEnrollmentServerSetup * This, /* [annotation][in] */ _In_ DISPID dispIdMember, /* [annotation][in] */ _In_ REFIID riid, /* [annotation][in] */ _In_ LCID lcid, /* [annotation][in] */ _In_ WORD wFlags, /* [annotation][out][in] */ _In_ DISPPARAMS *pDispParams, /* [annotation][out] */ _Out_opt_ VARIANT *pVarResult, /* [annotation][out] */ _Out_opt_ EXCEPINFO *pExcepInfo, /* [annotation][out] */ _Out_opt_ UINT *puArgErr); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ErrorString )( __RPC__in ICertificateEnrollmentServerSetup * This, /* [retval][out] */ __RPC__deref_out_opt BSTR *pVal); HRESULT ( STDMETHODCALLTYPE *InitializeInstallDefaults )( __RPC__in ICertificateEnrollmentServerSetup * This); HRESULT ( STDMETHODCALLTYPE *GetProperty )( __RPC__in ICertificateEnrollmentServerSetup * This, /* [in] */ CESSetupProperty propertyId, /* [retval][out] */ __RPC__out VARIANT *pPropertyValue); HRESULT ( STDMETHODCALLTYPE *SetProperty )( __RPC__in ICertificateEnrollmentServerSetup * This, /* [in] */ CESSetupProperty propertyId, /* [in] */ __RPC__in VARIANT *pPropertyValue); HRESULT ( STDMETHODCALLTYPE *SetApplicationPoolCredentials )( __RPC__in ICertificateEnrollmentServerSetup * This, /* [in] */ __RPC__in const BSTR bstrUsername, /* [in] */ __RPC__in const BSTR bstrPassword); HRESULT ( STDMETHODCALLTYPE *Install )( __RPC__in ICertificateEnrollmentServerSetup * This); HRESULT ( STDMETHODCALLTYPE *UnInstall )( __RPC__in ICertificateEnrollmentServerSetup * This, /* [optional][in] */ __RPC__in VARIANT *pCAConfig, /* [optional][in] */ __RPC__in VARIANT *pAuthentication); END_INTERFACE } ICertificateEnrollmentServerSetupVtbl; interface ICertificateEnrollmentServerSetup { CONST_VTBL struct ICertificateEnrollmentServerSetupVtbl *lpVtbl; }; #ifdef COBJMACROS #define ICertificateEnrollmentServerSetup_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ICertificateEnrollmentServerSetup_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define ICertificateEnrollmentServerSetup_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define ICertificateEnrollmentServerSetup_GetTypeInfoCount(This,pctinfo) \ ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define ICertificateEnrollmentServerSetup_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define ICertificateEnrollmentServerSetup_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define ICertificateEnrollmentServerSetup_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define ICertificateEnrollmentServerSetup_get_ErrorString(This,pVal) \ ( (This)->lpVtbl -> get_ErrorString(This,pVal) ) #define ICertificateEnrollmentServerSetup_InitializeInstallDefaults(This) \ ( (This)->lpVtbl -> InitializeInstallDefaults(This) ) #define ICertificateEnrollmentServerSetup_GetProperty(This,propertyId,pPropertyValue) \ ( (This)->lpVtbl -> GetProperty(This,propertyId,pPropertyValue) ) #define ICertificateEnrollmentServerSetup_SetProperty(This,propertyId,pPropertyValue) \ ( (This)->lpVtbl -> SetProperty(This,propertyId,pPropertyValue) ) #define ICertificateEnrollmentServerSetup_SetApplicationPoolCredentials(This,bstrUsername,bstrPassword) \ ( (This)->lpVtbl -> SetApplicationPoolCredentials(This,bstrUsername,bstrPassword) ) #define ICertificateEnrollmentServerSetup_Install(This) \ ( (This)->lpVtbl -> Install(This) ) #define ICertificateEnrollmentServerSetup_UnInstall(This,pCAConfig,pAuthentication) \ ( (This)->lpVtbl -> UnInstall(This,pCAConfig,pAuthentication) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __ICertificateEnrollmentServerSetup_INTERFACE_DEFINED__ */ /* interface __MIDL_itf_casetup_0000_0005 */ /* [local] */ typedef /* [public][public][public] */ enum __MIDL___MIDL_itf_casetup_0000_0005_0001 { ENUM_CEPSETUPPROP_AUTHENTICATION = 0, ENUM_CEPSETUPPROP_SSLCERTHASH = 1, ENUM_CEPSETUPPROP_URL = 2, ENUM_CEPSETUPPROP_KEYBASED_RENEWAL = 3 } CEPSetupProperty; extern RPC_IF_HANDLE __MIDL_itf_casetup_0000_0005_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_casetup_0000_0005_v0_0_s_ifspec; #ifndef __ICertificateEnrollmentPolicyServerSetup_INTERFACE_DEFINED__ #define __ICertificateEnrollmentPolicyServerSetup_INTERFACE_DEFINED__ /* interface ICertificateEnrollmentPolicyServerSetup */ /* [unique][dual][helpstring][uuid][object] */ EXTERN_C const IID IID_ICertificateEnrollmentPolicyServerSetup; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("859252CC-238C-4a88-B8FD-A37E7D04E68B") ICertificateEnrollmentPolicyServerSetup : public IDispatch { public: virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_ErrorString( /* [retval][out] */ __RPC__deref_out_opt BSTR *pVal) = 0; virtual HRESULT STDMETHODCALLTYPE InitializeInstallDefaults( void) = 0; virtual HRESULT STDMETHODCALLTYPE GetProperty( /* [in] */ CEPSetupProperty propertyId, /* [retval][out] */ __RPC__out VARIANT *pPropertyValue) = 0; virtual HRESULT STDMETHODCALLTYPE SetProperty( /* [in] */ CEPSetupProperty propertyId, /* [in] */ __RPC__in VARIANT *pPropertyValue) = 0; virtual HRESULT STDMETHODCALLTYPE Install( void) = 0; virtual HRESULT STDMETHODCALLTYPE UnInstall( /* [optional][in] */ __RPC__in VARIANT *pAuthKeyBasedRenewal) = 0; }; #else /* C style interface */ typedef struct ICertificateEnrollmentPolicyServerSetupVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in ICertificateEnrollmentPolicyServerSetup * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in ICertificateEnrollmentPolicyServerSetup * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in ICertificateEnrollmentPolicyServerSetup * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( __RPC__in ICertificateEnrollmentPolicyServerSetup * This, /* [out] */ __RPC__out UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( __RPC__in ICertificateEnrollmentPolicyServerSetup * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ __RPC__deref_out_opt ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( __RPC__in ICertificateEnrollmentPolicyServerSetup * This, /* [in] */ __RPC__in REFIID riid, /* [size_is][in] */ __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames, /* [range][in] */ __RPC__in_range(0,16384) UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ __RPC__out_ecount_full(cNames) DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( ICertificateEnrollmentPolicyServerSetup * This, /* [annotation][in] */ _In_ DISPID dispIdMember, /* [annotation][in] */ _In_ REFIID riid, /* [annotation][in] */ _In_ LCID lcid, /* [annotation][in] */ _In_ WORD wFlags, /* [annotation][out][in] */ _In_ DISPPARAMS *pDispParams, /* [annotation][out] */ _Out_opt_ VARIANT *pVarResult, /* [annotation][out] */ _Out_opt_ EXCEPINFO *pExcepInfo, /* [annotation][out] */ _Out_opt_ UINT *puArgErr); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ErrorString )( __RPC__in ICertificateEnrollmentPolicyServerSetup * This, /* [retval][out] */ __RPC__deref_out_opt BSTR *pVal); HRESULT ( STDMETHODCALLTYPE *InitializeInstallDefaults )( __RPC__in ICertificateEnrollmentPolicyServerSetup * This); HRESULT ( STDMETHODCALLTYPE *GetProperty )( __RPC__in ICertificateEnrollmentPolicyServerSetup * This, /* [in] */ CEPSetupProperty propertyId, /* [retval][out] */ __RPC__out VARIANT *pPropertyValue); HRESULT ( STDMETHODCALLTYPE *SetProperty )( __RPC__in ICertificateEnrollmentPolicyServerSetup * This, /* [in] */ CEPSetupProperty propertyId, /* [in] */ __RPC__in VARIANT *pPropertyValue); HRESULT ( STDMETHODCALLTYPE *Install )( __RPC__in ICertificateEnrollmentPolicyServerSetup * This); HRESULT ( STDMETHODCALLTYPE *UnInstall )( __RPC__in ICertificateEnrollmentPolicyServerSetup * This, /* [optional][in] */ __RPC__in VARIANT *pAuthKeyBasedRenewal); END_INTERFACE } ICertificateEnrollmentPolicyServerSetupVtbl; interface ICertificateEnrollmentPolicyServerSetup { CONST_VTBL struct ICertificateEnrollmentPolicyServerSetupVtbl *lpVtbl; }; #ifdef COBJMACROS #define ICertificateEnrollmentPolicyServerSetup_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define ICertificateEnrollmentPolicyServerSetup_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define ICertificateEnrollmentPolicyServerSetup_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define ICertificateEnrollmentPolicyServerSetup_GetTypeInfoCount(This,pctinfo) \ ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define ICertificateEnrollmentPolicyServerSetup_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define ICertificateEnrollmentPolicyServerSetup_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define ICertificateEnrollmentPolicyServerSetup_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define ICertificateEnrollmentPolicyServerSetup_get_ErrorString(This,pVal) \ ( (This)->lpVtbl -> get_ErrorString(This,pVal) ) #define ICertificateEnrollmentPolicyServerSetup_InitializeInstallDefaults(This) \ ( (This)->lpVtbl -> InitializeInstallDefaults(This) ) #define ICertificateEnrollmentPolicyServerSetup_GetProperty(This,propertyId,pPropertyValue) \ ( (This)->lpVtbl -> GetProperty(This,propertyId,pPropertyValue) ) #define ICertificateEnrollmentPolicyServerSetup_SetProperty(This,propertyId,pPropertyValue) \ ( (This)->lpVtbl -> SetProperty(This,propertyId,pPropertyValue) ) #define ICertificateEnrollmentPolicyServerSetup_Install(This) \ ( (This)->lpVtbl -> Install(This) ) #define ICertificateEnrollmentPolicyServerSetup_UnInstall(This,pAuthKeyBasedRenewal) \ ( (This)->lpVtbl -> UnInstall(This,pAuthKeyBasedRenewal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __ICertificateEnrollmentPolicyServerSetup_INTERFACE_DEFINED__ */ #ifndef __CertSrvSetupLib_LIBRARY_DEFINED__ #define __CertSrvSetupLib_LIBRARY_DEFINED__ /* library CertSrvSetupLib */ /* [helpstring][version][uuid] */ EXTERN_C const IID LIBID_CertSrvSetupLib; EXTERN_C const CLSID CLSID_CCertSrvSetupKeyInformation; #ifdef __cplusplus class DECLSPEC_UUID("38373906-5433-4633-b0fb-29b7e78262e1") CCertSrvSetupKeyInformation; #endif EXTERN_C const CLSID CLSID_CCertSrvSetup; #ifdef __cplusplus class DECLSPEC_UUID("961f180f-f55c-413d-a9b3-7d2af4d8e42f") CCertSrvSetup; #endif EXTERN_C const CLSID CLSID_CMSCEPSetup; #ifdef __cplusplus class DECLSPEC_UUID("aa4f5c02-8e7c-49c4-94fa-67a5cc5eadb4") CMSCEPSetup; #endif EXTERN_C const CLSID CLSID_CCertificateEnrollmentServerSetup; #ifdef __cplusplus class DECLSPEC_UUID("9902F3BC-88AF-4cf8-AE62-7140531552B6") CCertificateEnrollmentServerSetup; #endif EXTERN_C const CLSID CLSID_CCertificateEnrollmentPolicyServerSetup; #ifdef __cplusplus class DECLSPEC_UUID("AFE2FA32-41B1-459d-A5DE-49ADD8A72182") CCertificateEnrollmentPolicyServerSetup; #endif #endif /* __CertSrvSetupLib_LIBRARY_DEFINED__ */ /* interface __MIDL_itf_casetup_0000_0007 */ /* [local] */ #endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) */ #pragma endregion extern RPC_IF_HANDLE __MIDL_itf_casetup_0000_0007_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_casetup_0000_0007_v0_0_s_ifspec; /* Additional Prototypes for ALL interfaces */ unsigned long __RPC_USER BSTR_UserSize( __RPC__in unsigned long *, unsigned long , __RPC__in BSTR * ); unsigned char * __RPC_USER BSTR_UserMarshal( __RPC__in unsigned long *, __RPC__inout_xcount(0) unsigned char *, __RPC__in BSTR * ); unsigned char * __RPC_USER BSTR_UserUnmarshal(__RPC__in unsigned long *, __RPC__in_xcount(0) unsigned char *, __RPC__out BSTR * ); void __RPC_USER BSTR_UserFree( __RPC__in unsigned long *, __RPC__in BSTR * ); unsigned long __RPC_USER VARIANT_UserSize( __RPC__in unsigned long *, unsigned long , __RPC__in VARIANT * ); unsigned char * __RPC_USER VARIANT_UserMarshal( __RPC__in unsigned long *, __RPC__inout_xcount(0) unsigned char *, __RPC__in VARIANT * ); unsigned char * __RPC_USER VARIANT_UserUnmarshal(__RPC__in unsigned long *, __RPC__in_xcount(0) unsigned char *, __RPC__out VARIANT * ); void __RPC_USER VARIANT_UserFree( __RPC__in unsigned long *, __RPC__in VARIANT * ); unsigned long __RPC_USER BSTR_UserSize64( __RPC__in unsigned long *, unsigned long , __RPC__in BSTR * ); unsigned char * __RPC_USER BSTR_UserMarshal64( __RPC__in unsigned long *, __RPC__inout_xcount(0) unsigned char *, __RPC__in BSTR * ); unsigned char * __RPC_USER BSTR_UserUnmarshal64(__RPC__in unsigned long *, __RPC__in_xcount(0) unsigned char *, __RPC__out BSTR * ); void __RPC_USER BSTR_UserFree64( __RPC__in unsigned long *, __RPC__in BSTR * ); unsigned long __RPC_USER VARIANT_UserSize64( __RPC__in unsigned long *, unsigned long , __RPC__in VARIANT * ); unsigned char * __RPC_USER VARIANT_UserMarshal64( __RPC__in unsigned long *, __RPC__inout_xcount(0) unsigned char *, __RPC__in VARIANT * ); unsigned char * __RPC_USER VARIANT_UserUnmarshal64(__RPC__in unsigned long *, __RPC__in_xcount(0) unsigned char *, __RPC__out VARIANT * ); void __RPC_USER VARIANT_UserFree64( __RPC__in unsigned long *, __RPC__in VARIANT * ); /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif #pragma option pop /*P_O_Pop*/
38.473562
142
0.663978
[ "object" ]
3014cedbc32e4aa7b12a61c9c73a4f0ce93519e8
6,683
h
C
kklib/include/kklib/atomic.h
kamoii/koka
4ef04cd7cfa965c413a985dfaabbfb69a4c64d11
[ "Apache-2.0" ]
null
null
null
kklib/include/kklib/atomic.h
kamoii/koka
4ef04cd7cfa965c413a985dfaabbfb69a4c64d11
[ "Apache-2.0" ]
null
null
null
kklib/include/kklib/atomic.h
kamoii/koka
4ef04cd7cfa965c413a985dfaabbfb69a4c64d11
[ "Apache-2.0" ]
null
null
null
#pragma once #ifndef KK_ATOMIC_H #define KK_ATOMIC_H /*--------------------------------------------------------------------------- Copyright 2020-2021, Microsoft Research, Daan Leijen. This is free software; you can redistribute it and/or modify it under the terms of the Apache License, Version 2.0. A copy of the License can be found in the LICENSE file at the root of this distribution. ---------------------------------------------------------------------------*/ #if defined(__cplusplus) // Use C++ atomics #include <atomic> #define _Atomic(tp) std::atomic<tp> #define kk_atomic(name) std::atomic_##name #define kk_memory_order(name) std::memory_order_##name #define kk_memory_order_t std::kk_memory_order #elif defined(_MSC_VER) // Use MSVC C wrapper for C11 atomics #define _Atomic(tp) tp #define ATOMIC_VAR_INIT(x) x #define kk_atomic(name) kk_atomic_##name #define kk_memory_order(name) kk_memory_order_##name #define kk_memory_order_t kk_memory_order #else // Use C11 atomics #include <stdatomic.h> #define kk_atomic(name) atomic_##name #define kk_memory_order(name) memory_order_##name #define kk_memory_order_t memory_order #endif #define kk_atomic_add32_relaxed(p,x) kk_atomic_fetch_add32_explicit(p,x,kk_memory_order(relaxed)) #define kk_atomic_sub32_relaxed(p,x) kk_atomic_fetch_sub32_explicit(p,x,kk_memory_order(relaxed)) #define kk_atomic_add32_acq_rel(p,x) kk_atomic_fetch_add32_explicit(p,x,kk_memory_order(acq_rel)) #define kk_atomic_sub32_acq_rel(p,x) kk_atomic_fetch_sub32_explicit(p,x,kk_memory_order(acq_rel)) #define kk_atomic_load_relaxed(p) kk_atomic(load_explicit)(p,kk_memory_order(relaxed)) #define kk_atomic_load_acquire(p) kk_atomic(load_explicit)(p,kk_memory_order(acquire)) #define kk_atomic_store_relaxed(p,x) kk_atomic(store_explicit)(p,x,kk_memory_order(relaxed)) #define kk_atomic_store_release(p,x) kk_atomic(store_explicit)(p,x,kk_memory_order(release)) #define kk_atomic_cas_weak_relaxed(p,exp,des) kk_atomic(compare_exchange_weak_explicit)(p,exp,des,kk_memory_order(relaxed),kk_memory_order(relaxed)) #define kk_atomic_cas_weak_acq_rel(p,exp,des) kk_atomic(compare_exchange_weak_explicit)(p,exp,des,kk_memory_order(acq_rel),kk_memory_order(acquire)) #define kk_atomic_cas_strong_relaxed(p,exp,des) kk_atomic(compare_exchange_strong_explicit)(p,exp,des,kk_memory_order(relaxed),kk_memory_order(relaxed)) #define kk_atomic_cas_strong_acq_rel(p,exp,des) kk_atomic(compare_exchange_strong_explicit)(p,exp,des,kk_memory_order(acq_rel),kk_memory_order(acquire)) #define kk_atomic_inc32_relaxed(p) kk_atomic_add32_relaxed(p,1) #define kk_atomic_dec32_relaxed(p) kk_atomic_sub32_relaxed(p,1) #define kk_atomic_inc32_acq_rel(p) kk_atomic_add32_acq_rel(p,1) #define kk_atomic_dec32_acq_rel(p) kk_atomic_sub32_acq_rel(p,1) #if defined(__cplusplus) || !defined(_MSC_VER) // C++ or standard C11 #define kk_atomic_fetch_add32_explicit(p,x,mo) kk_atomic(fetch_add_explicit)(p,x,mo) #define kk_atomic_fetch_sub32_explicit(p,x,mo) kk_atomic(fetch_sub_explicit)(p,x,mo) #elif defined(_MSC_VER) // MSVC C compilation wrapper that uses Interlocked operations to model C11 atomics. #define MICROSOFT_WINDOWS_WINBASE_H_DEFINE_INTERLOCKED_CPLUSPLUS_OVERLOADS 1 // to avoid warnings #include <Windows.h> #include <intrin.h> #ifdef _WIN64 typedef LONG64 msc_intptr_t; #define WRAP64(f) f##64 #else typedef LONG msc_intptr_t; #define WRAP64(f) f #endif typedef enum kk_memory_order_e { kk_memory_order_relaxed, kk_memory_order_consume, kk_memory_order_acquire, kk_memory_order_release, kk_memory_order_acq_rel, kk_memory_order_seq_cst } kk_memory_order; static inline uintptr_t kk_atomic_fetch_add_explicit(_Atomic(uintptr_t)*p, uintptr_t add, kk_memory_order_t mo) { KK_UNUSED(mo); return (uintptr_t)WRAP64(_InterlockedExchangeAdd)((volatile msc_intptr_t*)p, (msc_intptr_t)add); } static inline uintptr_t kk_atomic_fetch_sub_explicit(_Atomic(uintptr_t)*p, uintptr_t sub, kk_memory_order_t mo) { KK_UNUSED(mo); return (uintptr_t)WRAP64(_InterlockedExchangeAdd)((volatile msc_intptr_t*)p, -((msc_intptr_t)sub)); } static inline uintptr_t kk_atomic_load_explicit(_Atomic(uintptr_t)*p, kk_memory_order_t mo) { KK_UNUSED(mo); #if defined(_M_X64) || defined(_M_IX86) if (mo == kk_memory_order_relaxed) { return *p; } #endif return (uintptr_t)WRAP64(_InterlockedOr)((volatile msc_intptr_t*)p, (msc_intptr_t)0); } static inline void kk_atomic_store_explicit(_Atomic(uintptr_t)*p, uintptr_t x, kk_memory_order_t mo) { KK_UNUSED(mo); #if defined(_M_X64) || defined(_M_IX86) if (mo == kk_memory_order_relaxed) { *p = x; return; } #endif WRAP64(_InterlockedExchange)((volatile msc_intptr_t*)p, (msc_intptr_t)x); } static inline bool kk_atomic_compare_exchange_weak_explicit(_Atomic(uintptr_t)*p, uintptr_t* expected, uintptr_t desired, kk_memory_order_t mo, kk_memory_order_t mofail) { KK_UNUSED(mo); KK_UNUSED(mofail); uintptr_t prev; #ifdef InterlockedCompareExchangeNoFence if (mo == kk_memory_order_relaxed) { prev = (uintptr_t)WRAP64(InterlockedCompareExchangeNoFence)((volatile msc_intptr_t*)p, (msc_intptr_t)desired, (msc_intptr_t)(*expected)); } else #endif { prev = (uintptr_t)WRAP64(InterlockedCompareExchange)((volatile msc_intptr_t*)p, (msc_intptr_t)desired, (msc_intptr_t)(*expected)); } if (prev==*expected) return true; *expected = prev; return false; } static inline bool kk_atomic_compare_exchange_strong_explicit(_Atomic(uintptr_t)*p, uintptr_t* expected, uintptr_t desired, kk_memory_order_t mo, kk_memory_order_t mofail) { return kk_atomic_compare_exchange_weak_explicit(p, expected, desired, mo, mofail); } static inline uint32_t kk_atomic_fetch_add32_explicit(_Atomic(uint32_t)*p, uint32_t add, kk_memory_order_t mo) { #ifdef InterlockedExchangeAddNoFence if (mo == kk_memory_order_relaxed) { return (uint32_t)InterlockedExchangeAddNoFence((volatile LONG*)p, (LONG)add); } else #endif { return (uint32_t)InterlockedExchangeAdd((volatile LONG*)p, (LONG)add); } } static inline uint32_t kk_atomic_fetch_sub32_explicit(_Atomic(uint32_t)*p, uint32_t sub, kk_memory_order_t mo) { KK_UNUSED(mo); const LONG add = -((LONG)sub); #ifdef InterlockedExchangeAddNoFence if (mo == kk_memory_order_relaxed) { return (uint32_t)InterlockedExchangeAddNoFence((volatile LONG*)p, add); } else #endif { return (uint32_t)InterlockedExchangeAdd((volatile LONG*)p, add); } } #endif #endif // include guard
41.509317
173
0.754003
[ "model" ]
3016cefc45919a1b9d655c4badeaa33045f471d6
39,693
h
C
Dump/Niagara_classes.h
patrickcjk/RogueCompanyDump
fc83446500e8713f12e9f6a95cfa07f756a6b5c3
[ "MIT" ]
null
null
null
Dump/Niagara_classes.h
patrickcjk/RogueCompanyDump
fc83446500e8713f12e9f6a95cfa07f756a6b5c3
[ "MIT" ]
null
null
null
Dump/Niagara_classes.h
patrickcjk/RogueCompanyDump
fc83446500e8713f12e9f6a95cfa07f756a6b5c3
[ "MIT" ]
1
2021-02-25T00:48:25.000Z
2021-02-25T00:48:25.000Z
// Class Niagara.MovieSceneNiagaraTrack // Size: 0x68 (Inherited: 0x58) struct UMovieSceneNiagaraTrack : public UMovieSceneNameableTrack { struct TArray<struct UMovieSceneSection*> Sections; // 0x58(0x10) }; // Class Niagara.MovieSceneNiagaraParameterTrack // Size: 0x90 (Inherited: 0x68) struct UMovieSceneNiagaraParameterTrack : public UMovieSceneNiagaraTrack { struct FNiagaraVariable Parameter; // 0x68(0x28) }; // Class Niagara.MovieSceneNiagaraSystemSpawnSection // Size: 0xf0 (Inherited: 0xe0) struct UMovieSceneNiagaraSystemSpawnSection : public UMovieSceneSection { enum class ENiagaraSystemSpawnSectionStartBehavior SectionStartBehavior; // 0xe0(0x04) enum class ENiagaraSystemSpawnSectionEvaluateBehavior SectionEvaluateBehavior; // 0xe4(0x04) enum class ENiagaraSystemSpawnSectionEndBehavior SectionEndBehavior; // 0xe8(0x04) enum class ENiagaraAgeUpdateMode AgeUpdateMode; // 0xec(0x01) char UnknownData_ED[0x3]; // 0xed(0x03) }; // Class Niagara.MovieSceneNiagaraVectorParameterTrack // Size: 0x98 (Inherited: 0x90) struct UMovieSceneNiagaraVectorParameterTrack : public UMovieSceneNiagaraParameterTrack { int32_t ChannelsUsed; // 0x90(0x04) char UnknownData_94[0x4]; // 0x94(0x04) }; // Class Niagara.NiagaraActor // Size: 0x230 (Inherited: 0x220) struct ANiagaraActor : public AActor { struct UNiagaraComponent* NiagaraComponent; // 0x220(0x08) char bDestroyOnSystemFinish : 1; // 0x228(0x01) char UnknownData_228_1 : 7; // 0x228(0x01) char UnknownData_229[0x7]; // 0x229(0x07) void SetDestroyOnSystemFinish(bool bShouldDestroyOnSystemFinish); // Function Niagara.NiagaraActor.SetDestroyOnSystemFinish void OnNiagaraSystemFinished(struct UNiagaraComponent* FinishedComponent); // Function Niagara.NiagaraActor.OnNiagaraSystemFinished }; // Class Niagara.NiagaraComponent // Size: 0x5e0 (Inherited: 0x430) struct UNiagaraComponent : public UFXSystemComponent { struct UNiagaraSystem* Asset; // 0x430(0x08) enum class ENiagaraTickBehavior TickBehavior; // 0x438(0x01) char UnknownData_439[0x7]; // 0x439(0x07) struct FNiagaraUserRedirectionParameterStore OverrideParameters; // 0x440(0x108) char bForceSolo : 1; // 0x548(0x01) char UnknownData_548_1 : 7; // 0x548(0x01) char UnknownData_549[0x2b]; // 0x549(0x2b) char bAutoDestroy : 1; // 0x574(0x01) char bRenderingEnabled : 1; // 0x574(0x01) char bAutoManageAttachment : 1; // 0x574(0x01) char bAutoAttachWeldSimulatedBodies : 1; // 0x574(0x01) char UnknownData_574_4 : 4; // 0x574(0x01) char UnknownData_575[0x3]; // 0x575(0x03) float MaxTimeBeforeForceUpdateTransform; // 0x578(0x04) char UnknownData_57C[0x4]; // 0x57c(0x04) struct FMulticastInlineDelegate OnSystemFinished; // 0x580(0x10) struct FWeakObjectPtr<struct USceneComponent> AutoAttachParent; // 0x590(0x08) struct FName AutoAttachSocketName; // 0x598(0x08) enum class EAttachmentRule AutoAttachLocationRule; // 0x5a0(0x01) enum class EAttachmentRule AutoAttachRotationRule; // 0x5a1(0x01) enum class EAttachmentRule AutoAttachScaleRule; // 0x5a2(0x01) char UnknownData_5A3[0x3d]; // 0x5a3(0x3d) void SetVariableVec4(struct FName InVariableName, struct FVector4 InValue); // Function Niagara.NiagaraComponent.SetVariableVec4 void SetVariableVec3(struct FName InVariableName, struct FVector InValue); // Function Niagara.NiagaraComponent.SetVariableVec3 void SetVariableVec2(struct FName InVariableName, struct FVector2D InValue); // Function Niagara.NiagaraComponent.SetVariableVec2 void SetVariableQuat(struct FName InVariableName, struct FQuat InValue); // Function Niagara.NiagaraComponent.SetVariableQuat void SetVariableObject(struct FName InVariableName, struct UObject* Object); // Function Niagara.NiagaraComponent.SetVariableObject void SetVariableMaterial(struct FName InVariableName, struct UMaterialInterface* Object); // Function Niagara.NiagaraComponent.SetVariableMaterial void SetVariableLinearColor(struct FName InVariableName, struct FLinearColor InValue); // Function Niagara.NiagaraComponent.SetVariableLinearColor void SetVariableInt(struct FName InVariableName, int32_t InValue); // Function Niagara.NiagaraComponent.SetVariableInt void SetVariableFloat(struct FName InVariableName, float InValue); // Function Niagara.NiagaraComponent.SetVariableFloat void SetVariableBool(struct FName InVariableName, bool InValue); // Function Niagara.NiagaraComponent.SetVariableBool void SetVariableActor(struct FName InVariableName, struct AActor* Actor); // Function Niagara.NiagaraComponent.SetVariableActor void SetSeekDelta(float InSeekDelta); // Function Niagara.NiagaraComponent.SetSeekDelta void SetRenderingEnabled(bool bInRenderingEnabled); // Function Niagara.NiagaraComponent.SetRenderingEnabled void SetPreviewLODDistance(bool bEnablePreviewLODDistance, float PreviewLODDistance); // Function Niagara.NiagaraComponent.SetPreviewLODDistance void SetPaused(bool bInPaused); // Function Niagara.NiagaraComponent.SetPaused void SetNiagaraVariableVec4(struct FString InVariableName, struct FVector4 InValue); // Function Niagara.NiagaraComponent.SetNiagaraVariableVec4 void SetNiagaraVariableVec3(struct FString InVariableName, struct FVector InValue); // Function Niagara.NiagaraComponent.SetNiagaraVariableVec3 void SetNiagaraVariableVec2(struct FString InVariableName, struct FVector2D InValue); // Function Niagara.NiagaraComponent.SetNiagaraVariableVec2 void SetNiagaraVariableQuat(struct FString InVariableName, struct FQuat InValue); // Function Niagara.NiagaraComponent.SetNiagaraVariableQuat void SetNiagaraVariableObject(struct FString InVariableName, struct UObject* Object); // Function Niagara.NiagaraComponent.SetNiagaraVariableObject void SetNiagaraVariableLinearColor(struct FString InVariableName, struct FLinearColor InValue); // Function Niagara.NiagaraComponent.SetNiagaraVariableLinearColor void SetNiagaraVariableInt(struct FString InVariableName, int32_t InValue); // Function Niagara.NiagaraComponent.SetNiagaraVariableInt void SetNiagaraVariableFloat(struct FString InVariableName, float InValue); // Function Niagara.NiagaraComponent.SetNiagaraVariableFloat void SetNiagaraVariableBool(struct FString InVariableName, bool InValue); // Function Niagara.NiagaraComponent.SetNiagaraVariableBool void SetNiagaraVariableActor(struct FString InVariableName, struct AActor* Actor); // Function Niagara.NiagaraComponent.SetNiagaraVariableActor void SetMaxSimTime(float InMaxTime); // Function Niagara.NiagaraComponent.SetMaxSimTime void SetForceSolo(bool bInForceSolo); // Function Niagara.NiagaraComponent.SetForceSolo void SetDesiredAge(float InDesiredAge); // Function Niagara.NiagaraComponent.SetDesiredAge void SetCanRenderWhileSeeking(bool bInCanRenderWhileSeeking); // Function Niagara.NiagaraComponent.SetCanRenderWhileSeeking void SetAutoDestroy(bool bInAutoDestroy); // Function Niagara.NiagaraComponent.SetAutoDestroy void SetAsset(struct UNiagaraSystem* InAsset); // Function Niagara.NiagaraComponent.SetAsset void SetAllowScalability(bool bAllow); // Function Niagara.NiagaraComponent.SetAllowScalability void SetAgeUpdateMode(enum class ENiagaraAgeUpdateMode InAgeUpdateMode); // Function Niagara.NiagaraComponent.SetAgeUpdateMode void SeekToDesiredAge(float InDesiredAge); // Function Niagara.NiagaraComponent.SeekToDesiredAge void ResetSystem(); // Function Niagara.NiagaraComponent.ResetSystem void ReinitializeSystem(); // Function Niagara.NiagaraComponent.ReinitializeSystem bool IsPaused(); // Function Niagara.NiagaraComponent.IsPaused float GetSeekDelta(); // Function Niagara.NiagaraComponent.GetSeekDelta bool GetPreviewLODDistanceEnabled(); // Function Niagara.NiagaraComponent.GetPreviewLODDistanceEnabled int32_t GetPreviewLODDistance(); // Function Niagara.NiagaraComponent.GetPreviewLODDistance struct TArray<struct FVector> GetNiagaraParticleValueVec3_DebugOnly(struct FString InEmitterName, struct FString InValueName); // Function Niagara.NiagaraComponent.GetNiagaraParticleValueVec3_DebugOnly struct TArray<float> GetNiagaraParticleValues_DebugOnly(struct FString InEmitterName, struct FString InValueName); // Function Niagara.NiagaraComponent.GetNiagaraParticleValues_DebugOnly struct TArray<struct FVector> GetNiagaraParticlePositions_DebugOnly(struct FString InEmitterName); // Function Niagara.NiagaraComponent.GetNiagaraParticlePositions_DebugOnly float GetMaxSimTime(); // Function Niagara.NiagaraComponent.GetMaxSimTime bool GetForceSolo(); // Function Niagara.NiagaraComponent.GetForceSolo float GetDesiredAge(); // Function Niagara.NiagaraComponent.GetDesiredAge struct UNiagaraDataInterface* GetDataInterface(struct FString Name); // Function Niagara.NiagaraComponent.GetDataInterface struct UNiagaraSystem* GetAsset(); // Function Niagara.NiagaraComponent.GetAsset enum class ENiagaraAgeUpdateMode GetAgeUpdateMode(); // Function Niagara.NiagaraComponent.GetAgeUpdateMode void AdvanceSimulationByTime(float SimulateTime, float TickDeltaSeconds); // Function Niagara.NiagaraComponent.AdvanceSimulationByTime void AdvanceSimulation(int32_t TickCount, float TickDeltaSeconds); // Function Niagara.NiagaraComponent.AdvanceSimulation }; // Class Niagara.NiagaraComponentPool // Size: 0x80 (Inherited: 0x28) struct UNiagaraComponentPool : public UObject { struct TMap<struct UNiagaraSystem*, struct FNCPool> WorldParticleSystemPools; // 0x28(0x50) char UnknownData_78[0x8]; // 0x78(0x08) }; // Class Niagara.NiagaraDataInterface // Size: 0x30 (Inherited: 0x28) struct UNiagaraDataInterface : public UNiagaraDataInterfaceBase { char UnknownData_28[0x8]; // 0x28(0x08) }; // Class Niagara.NiagaraDataInterfaceAudioSubmix // Size: 0x38 (Inherited: 0x30) struct UNiagaraDataInterfaceAudioSubmix : public UNiagaraDataInterface { struct USoundSubmix* Submix; // 0x30(0x08) }; // Class Niagara.NiagaraDataInterfaceAudioOscilloscope // Size: 0x40 (Inherited: 0x30) struct UNiagaraDataInterfaceAudioOscilloscope : public UNiagaraDataInterface { struct USoundSubmix* Submix; // 0x30(0x08) int32_t Resolution; // 0x38(0x04) float ScopeInMilliseconds; // 0x3c(0x04) }; // Class Niagara.NiagaraDataInterfaceAudioSpectrum // Size: 0x48 (Inherited: 0x38) struct UNiagaraDataInterfaceAudioSpectrum : public UNiagaraDataInterfaceAudioSubmix { int32_t Resolution; // 0x38(0x04) float MinimumFrequency; // 0x3c(0x04) float MaximumFrequency; // 0x40(0x04) float NoiseFloorDb; // 0x44(0x04) }; // Class Niagara.NiagaraDataInterfaceCamera // Size: 0x38 (Inherited: 0x30) struct UNiagaraDataInterfaceCamera : public UNiagaraDataInterface { int32_t PlayerControllerIndex; // 0x30(0x04) char UnknownData_34[0x4]; // 0x34(0x04) }; // Class Niagara.NiagaraDataInterfaceCollisionQuery // Size: 0x40 (Inherited: 0x30) struct UNiagaraDataInterfaceCollisionQuery : public UNiagaraDataInterface { char UnknownData_30[0x10]; // 0x30(0x10) }; // Class Niagara.NiagaraDataInterfaceCurveBase // Size: 0x58 (Inherited: 0x30) struct UNiagaraDataInterfaceCurveBase : public UNiagaraDataInterface { struct TArray<float> ShaderLUT; // 0x30(0x10) float LUTMinTime; // 0x40(0x04) float LUTMaxTime; // 0x44(0x04) float LUTInvTimeRange; // 0x48(0x04) float LUTNumSamplesMinusOne; // 0x4c(0x04) char bUseLUT : 1; // 0x50(0x01) char UnknownData_50_1 : 7; // 0x50(0x01) char UnknownData_51[0x7]; // 0x51(0x07) }; // Class Niagara.NiagaraDataInterfaceColorCurve // Size: 0x258 (Inherited: 0x58) struct UNiagaraDataInterfaceColorCurve : public UNiagaraDataInterfaceCurveBase { struct FRichCurve RedCurve; // 0x58(0x80) struct FRichCurve GreenCurve; // 0xd8(0x80) struct FRichCurve BlueCurve; // 0x158(0x80) struct FRichCurve AlphaCurve; // 0x1d8(0x80) }; // Class Niagara.NiagaraDataInterfaceCurlNoise // Size: 0x40 (Inherited: 0x30) struct UNiagaraDataInterfaceCurlNoise : public UNiagaraDataInterface { uint32_t Seed; // 0x30(0x04) char UnknownData_34[0xc]; // 0x34(0x0c) }; // Class Niagara.NiagaraDataInterfaceCurve // Size: 0xd8 (Inherited: 0x58) struct UNiagaraDataInterfaceCurve : public UNiagaraDataInterfaceCurveBase { struct FRichCurve Curve; // 0x58(0x80) }; // Class Niagara.NiagaraDataInterfaceExport // Size: 0x58 (Inherited: 0x30) struct UNiagaraDataInterfaceExport : public UNiagaraDataInterface { struct FNiagaraUserParameterBinding CallbackHandlerParameter; // 0x30(0x28) }; // Class Niagara.NiagaraDataInterfaceRWBase // Size: 0xd0 (Inherited: 0x30) struct UNiagaraDataInterfaceRWBase : public UNiagaraDataInterface { struct TSet<int32_t> OutputShaderStages; // 0x30(0x50) struct TSet<int32_t> IterationShaderStages; // 0x80(0x50) }; // Class Niagara.NiagaraDataInterfaceGrid2D // Size: 0xf0 (Inherited: 0xd0) struct UNiagaraDataInterfaceGrid2D : public UNiagaraDataInterfaceRWBase { int32_t NumCellsX; // 0xd0(0x04) int32_t NumCellsY; // 0xd4(0x04) int32_t NumCellsMaxAxis; // 0xd8(0x04) int32_t NumAttributes; // 0xdc(0x04) bool SetGridFromMaxAxis; // 0xe0(0x01) char UnknownData_E1[0x3]; // 0xe1(0x03) struct FVector2D WorldBBoxSize; // 0xe4(0x08) char UnknownData_EC[0x4]; // 0xec(0x04) }; // Class Niagara.NiagaraDataInterfaceGrid2DCollection // Size: 0x140 (Inherited: 0xf0) struct UNiagaraDataInterfaceGrid2DCollection : public UNiagaraDataInterfaceGrid2D { char UnknownData_F0[0x50]; // 0xf0(0x50) void GetTextureSize(struct UNiagaraComponent* Component, int32_t SizeX, int32_t SizeY); // Function Niagara.NiagaraDataInterfaceGrid2DCollection.GetTextureSize void GetRawTextureSize(struct UNiagaraComponent* Component, int32_t SizeX, int32_t SizeY); // Function Niagara.NiagaraDataInterfaceGrid2DCollection.GetRawTextureSize bool FillTexture2D(struct UNiagaraComponent* Component, struct UTextureRenderTarget2D* Dest, int32_t AttributeIndex); // Function Niagara.NiagaraDataInterfaceGrid2DCollection.FillTexture2D bool FillRawTexture2D(struct UNiagaraComponent* Component, struct UTextureRenderTarget2D* Dest, int32_t TilesX, int32_t TilesY); // Function Niagara.NiagaraDataInterfaceGrid2DCollection.FillRawTexture2D }; // Class Niagara.NiagaraDataInterfaceGrid3D // Size: 0xf0 (Inherited: 0xd0) struct UNiagaraDataInterfaceGrid3D : public UNiagaraDataInterfaceRWBase { struct FIntVector NumVoxels; // 0xd0(0x0c) float VoxelSize; // 0xdc(0x04) bool SetGridFromVoxelSize; // 0xe0(0x01) char UnknownData_E1[0x3]; // 0xe1(0x03) struct FVector WorldBBoxSize; // 0xe4(0x0c) }; // Class Niagara.NiagaraDataInterfaceNeighborGrid3D // Size: 0xf8 (Inherited: 0xf0) struct UNiagaraDataInterfaceNeighborGrid3D : public UNiagaraDataInterfaceGrid3D { uint32_t MaxNeighborsPerVoxel; // 0xf0(0x04) char UnknownData_F4[0x4]; // 0xf4(0x04) }; // Class Niagara.NiagaraDataInterfaceParticleRead // Size: 0x40 (Inherited: 0x30) struct UNiagaraDataInterfaceParticleRead : public UNiagaraDataInterface { struct FString EmitterName; // 0x30(0x10) }; // Class Niagara.NiagaraDataInterfaceSkeletalMesh // Size: 0xb8 (Inherited: 0x30) struct UNiagaraDataInterfaceSkeletalMesh : public UNiagaraDataInterface { struct AActor* Source; // 0x30(0x08) struct FNiagaraUserParameterBinding MeshUserParameter; // 0x38(0x28) struct USkeletalMeshComponent* SourceComponent; // 0x60(0x08) enum class ENDISkeletalMesh_SkinningMode SkinningMode; // 0x68(0x01) char UnknownData_69[0x7]; // 0x69(0x07) struct TArray<struct FName> SamplingRegions; // 0x70(0x10) int32_t WholeMeshLOD; // 0x80(0x04) char UnknownData_84[0x4]; // 0x84(0x04) struct TArray<struct FName> FilteredBones; // 0x88(0x10) struct TArray<struct FName> FilteredSockets; // 0x98(0x10) struct FName ExcludeBoneName; // 0xa8(0x08) char bExcludeBone : 1; // 0xb0(0x01) char UnknownData_B0_1 : 7; // 0xb0(0x01) char UnknownData_B1[0x7]; // 0xb1(0x07) }; // Class Niagara.NiagaraDataInterfaceSpline // Size: 0x38 (Inherited: 0x30) struct UNiagaraDataInterfaceSpline : public UNiagaraDataInterface { struct AActor* Source; // 0x30(0x08) }; // Class Niagara.NiagaraDataInterfaceStaticMesh // Size: 0x60 (Inherited: 0x30) struct UNiagaraDataInterfaceStaticMesh : public UNiagaraDataInterface { struct UStaticMesh* DefaultMesh; // 0x30(0x08) struct AActor* Source; // 0x38(0x08) struct UStaticMeshComponent* SourceComponent; // 0x40(0x08) struct FNDIStaticMeshSectionFilter SectionFilter; // 0x48(0x10) char UnknownData_58[0x8]; // 0x58(0x08) }; // Class Niagara.NiagaraDataInterfaceTexture // Size: 0x38 (Inherited: 0x30) struct UNiagaraDataInterfaceTexture : public UNiagaraDataInterface { struct UTexture* Texture; // 0x30(0x08) }; // Class Niagara.NiagaraDataInterfaceVector2DCurve // Size: 0x158 (Inherited: 0x58) struct UNiagaraDataInterfaceVector2DCurve : public UNiagaraDataInterfaceCurveBase { struct FRichCurve XCurve; // 0x58(0x80) struct FRichCurve YCurve; // 0xd8(0x80) }; // Class Niagara.NiagaraDataInterfaceVector4Curve // Size: 0x258 (Inherited: 0x58) struct UNiagaraDataInterfaceVector4Curve : public UNiagaraDataInterfaceCurveBase { struct FRichCurve XCurve; // 0x58(0x80) struct FRichCurve YCurve; // 0xd8(0x80) struct FRichCurve ZCurve; // 0x158(0x80) struct FRichCurve WCurve; // 0x1d8(0x80) }; // Class Niagara.NiagaraDataInterfaceVectorCurve // Size: 0x1d8 (Inherited: 0x58) struct UNiagaraDataInterfaceVectorCurve : public UNiagaraDataInterfaceCurveBase { struct FRichCurve XCurve; // 0x58(0x80) struct FRichCurve YCurve; // 0xd8(0x80) struct FRichCurve ZCurve; // 0x158(0x80) }; // Class Niagara.NiagaraDataInterfaceVectorField // Size: 0x40 (Inherited: 0x30) struct UNiagaraDataInterfaceVectorField : public UNiagaraDataInterface { struct UVectorField* Field; // 0x30(0x08) bool bTileX; // 0x38(0x01) bool bTileY; // 0x39(0x01) bool bTileZ; // 0x3a(0x01) char UnknownData_3B[0x5]; // 0x3b(0x05) }; // Class Niagara.NiagaraDataInterfaceVolumeTexture // Size: 0x38 (Inherited: 0x30) struct UNiagaraDataInterfaceVolumeTexture : public UNiagaraDataInterface { struct UVolumeTexture* Texture; // 0x30(0x08) }; // Class Niagara.NiagaraEffectType // Size: 0x100 (Inherited: 0x28) struct UNiagaraEffectType : public UObject { enum class ENiagaraScalabilityUpdateFrequency UpdateFrequency; // 0x28(0x04) enum class ENiagaraCullReaction CullReaction; // 0x2c(0x04) struct TArray<struct FNiagaraSystemScalabilitySettings> DetailLevelScalabilitySettings; // 0x30(0x10) struct FNiagaraSystemScalabilitySettingsArray SystemScalabilitySettings; // 0x40(0x10) struct FNiagaraEmitterScalabilitySettingsArray EmitterScalabilitySettings; // 0x50(0x10) char UnknownData_60[0xa0]; // 0x60(0xa0) }; // Class Niagara.NiagaraEmitter // Size: 0x2b0 (Inherited: 0x28) struct UNiagaraEmitter : public UObject { bool bLocalSpace; // 0x28(0x01) bool bDeterminism; // 0x29(0x01) char UnknownData_2A[0x2]; // 0x2a(0x02) int32_t RandomSeed; // 0x2c(0x04) enum class EParticleAllocationMode AllocationMode; // 0x30(0x01) char UnknownData_31[0x3]; // 0x31(0x03) int32_t PreAllocationCount; // 0x34(0x04) struct FNiagaraEmitterScriptProperties UpdateScriptProps; // 0x38(0x28) struct FNiagaraEmitterScriptProperties SpawnScriptProps; // 0x60(0x28) struct FNiagaraEmitterScriptProperties EmitterSpawnScriptProps; // 0x88(0x28) struct FNiagaraEmitterScriptProperties EmitterUpdateScriptProps; // 0xb0(0x28) enum class ENiagaraSimTarget SimTarget; // 0xd8(0x01) char UnknownData_D9[0x3]; // 0xd9(0x03) struct FBox FixedBounds; // 0xdc(0x1c) int32_t MinDetailLevel; // 0xf8(0x04) int32_t MaxDetailLevel; // 0xfc(0x04) struct FNiagaraDetailsLevelScaleOverrides GlobalSpawnCountScaleOverrides; // 0x100(0x14) char UnknownData_114[0x4]; // 0x114(0x04) struct FNiagaraPlatformSet Platforms; // 0x118(0x20) struct FNiagaraEmitterScalabilityOverrides ScalabilityOverrides; // 0x138(0x10) char bInterpolatedSpawning : 1; // 0x148(0x01) char bFixedBounds : 1; // 0x148(0x01) char bUseMinDetailLevel : 1; // 0x148(0x01) char bUseMaxDetailLevel : 1; // 0x148(0x01) char bOverrideGlobalSpawnCountScale : 1; // 0x148(0x01) char bRequiresPersistentIDs : 1; // 0x148(0x01) char UnknownData_148_6 : 2; // 0x148(0x01) char UnknownData_149[0x3]; // 0x149(0x03) float MaxDeltaTimePerTick; // 0x14c(0x04) uint32_t DefaultShaderStageIndex; // 0x150(0x04) uint32_t MaxUpdateIterations; // 0x154(0x04) struct TSet<uint32_t> SpawnStages; // 0x158(0x50) char bSimulationStagesEnabled : 1; // 0x1a8(0x01) char bDeprecatedShaderStagesEnabled : 1; // 0x1a8(0x01) char bLimitDeltaTime : 1; // 0x1a8(0x01) char UnknownData_1A8_3 : 5; // 0x1a8(0x01) char UnknownData_1A9[0x7]; // 0x1a9(0x07) struct FString UniqueEmitterName; // 0x1b0(0x10) struct TArray<struct UNiagaraRendererProperties*> RendererProperties; // 0x1c0(0x10) struct TArray<struct FNiagaraEventScriptProperties> EventHandlerScriptProps; // 0x1d0(0x10) struct TArray<struct UNiagaraSimulationStageBase*> SimulationStages; // 0x1e0(0x10) struct UNiagaraScript* GPUComputeScript; // 0x1f0(0x08) struct TArray<struct FName> SharedEventGeneratorIds; // 0x1f8(0x10) char UnknownData_208[0xa8]; // 0x208(0xa8) }; // Class Niagara.NiagaraEventReceiverEmitterAction_SpawnParticles // Size: 0x30 (Inherited: 0x28) struct UNiagaraEventReceiverEmitterAction_SpawnParticles : public UNiagaraEventReceiverEmitterAction { uint32_t NumParticles; // 0x28(0x04) char UnknownData_2C[0x4]; // 0x2c(0x04) }; // Class Niagara.NiagaraRendererProperties // Size: 0x50 (Inherited: 0x28) struct UNiagaraRendererProperties : public UNiagaraMergeable { int32_t SortOrderHint; // 0x28(0x04) bool bIsEnabled; // 0x2c(0x01) bool bMotionBlurEnabled; // 0x2d(0x01) char UnknownData_2E[0x22]; // 0x2e(0x22) }; // Class Niagara.NiagaraLightRendererProperties // Size: 0x338 (Inherited: 0x50) struct UNiagaraLightRendererProperties : public UNiagaraRendererProperties { char bUseInverseSquaredFalloff : 1; // 0x50(0x01) char bAffectsTranslucency : 1; // 0x50(0x01) char bOverrideRenderingEnabled : 1; // 0x50(0x01) char UnknownData_50_3 : 5; // 0x50(0x01) char UnknownData_51[0x3]; // 0x51(0x03) float RadiusScale; // 0x54(0x04) struct FVector ColorAdd; // 0x58(0x0c) char UnknownData_64[0x4]; // 0x64(0x04) struct FNiagaraVariableAttributeBinding LightRenderingEnabledBinding; // 0x68(0x78) struct FNiagaraVariableAttributeBinding LightExponentBinding; // 0xe0(0x78) struct FNiagaraVariableAttributeBinding PositionBinding; // 0x158(0x78) struct FNiagaraVariableAttributeBinding ColorBinding; // 0x1d0(0x78) struct FNiagaraVariableAttributeBinding RadiusBinding; // 0x248(0x78) struct FNiagaraVariableAttributeBinding VolumetricScatteringBinding; // 0x2c0(0x78) }; // Class Niagara.NiagaraMeshRendererProperties // Size: 0x728 (Inherited: 0x50) struct UNiagaraMeshRendererProperties : public UNiagaraRendererProperties { struct UStaticMesh* ParticleMesh; // 0x50(0x08) enum class ENiagaraSortMode SortMode; // 0x58(0x01) char UnknownData_59[0x3]; // 0x59(0x03) char bOverrideMaterials : 1; // 0x5c(0x01) char bSortOnlyWhenTranslucent : 1; // 0x5c(0x01) char UnknownData_5C_2 : 6; // 0x5c(0x01) char UnknownData_5D[0x3]; // 0x5d(0x03) struct TArray<struct FNiagaraMeshMaterialOverride> OverrideMaterials; // 0x60(0x10) struct FVector2D SubImageSize; // 0x70(0x08) char bSubImageBlend : 1; // 0x78(0x01) char UnknownData_78_1 : 7; // 0x78(0x01) char UnknownData_79[0x3]; // 0x79(0x03) enum class ENiagaraMeshFacingMode FacingMode; // 0x7c(0x01) char UnknownData_7D[0x3]; // 0x7d(0x03) char bLockedAxisEnable : 1; // 0x80(0x01) char UnknownData_80_1 : 7; // 0x80(0x01) char UnknownData_81[0x3]; // 0x81(0x03) struct FVector LockedAxis; // 0x84(0x0c) enum class ENiagaraMeshLockedAxisSpace LockedAxisSpace; // 0x90(0x01) char UnknownData_91[0x7]; // 0x91(0x07) struct FNiagaraVariableAttributeBinding PositionBinding; // 0x98(0x78) struct FNiagaraVariableAttributeBinding ColorBinding; // 0x110(0x78) struct FNiagaraVariableAttributeBinding VelocityBinding; // 0x188(0x78) struct FNiagaraVariableAttributeBinding MeshOrientationBinding; // 0x200(0x78) struct FNiagaraVariableAttributeBinding ScaleBinding; // 0x278(0x78) struct FNiagaraVariableAttributeBinding SubImageIndexBinding; // 0x2f0(0x78) struct FNiagaraVariableAttributeBinding DynamicMaterialBinding; // 0x368(0x78) struct FNiagaraVariableAttributeBinding DynamicMaterial1Binding; // 0x3e0(0x78) struct FNiagaraVariableAttributeBinding DynamicMaterial2Binding; // 0x458(0x78) struct FNiagaraVariableAttributeBinding DynamicMaterial3Binding; // 0x4d0(0x78) struct FNiagaraVariableAttributeBinding MaterialRandomBinding; // 0x548(0x78) struct FNiagaraVariableAttributeBinding CustomSortingBinding; // 0x5c0(0x78) struct FNiagaraVariableAttributeBinding NormalizedAgeBinding; // 0x638(0x78) struct FNiagaraVariableAttributeBinding CameraOffsetBinding; // 0x6b0(0x78) }; // Class Niagara.NiagaraParameterCollectionInstance // Size: 0xf8 (Inherited: 0x28) struct UNiagaraParameterCollectionInstance : public UObject { struct UNiagaraParameterCollection* Collection; // 0x28(0x08) struct TArray<struct FNiagaraVariable> OverridenParameters; // 0x30(0x10) struct FNiagaraParameterStore ParameterStorage; // 0x40(0xb8) void SetVectorParameter(struct FString InVariableName, struct FVector InValue); // Function Niagara.NiagaraParameterCollectionInstance.SetVectorParameter void SetVector4Parameter(struct FString InVariableName, struct FVector4 InValue); // Function Niagara.NiagaraParameterCollectionInstance.SetVector4Parameter void SetVector2DParameter(struct FString InVariableName, struct FVector2D InValue); // Function Niagara.NiagaraParameterCollectionInstance.SetVector2DParameter void SetQuatParameter(struct FString InVariableName, struct FQuat InValue); // Function Niagara.NiagaraParameterCollectionInstance.SetQuatParameter void SetIntParameter(struct FString InVariableName, int32_t InValue); // Function Niagara.NiagaraParameterCollectionInstance.SetIntParameter void SetFloatParameter(struct FString InVariableName, float InValue); // Function Niagara.NiagaraParameterCollectionInstance.SetFloatParameter void SetColorParameter(struct FString InVariableName, struct FLinearColor InValue); // Function Niagara.NiagaraParameterCollectionInstance.SetColorParameter void SetBoolParameter(struct FString InVariableName, bool InValue); // Function Niagara.NiagaraParameterCollectionInstance.SetBoolParameter struct FVector GetVectorParameter(struct FString InVariableName); // Function Niagara.NiagaraParameterCollectionInstance.GetVectorParameter struct FVector4 GetVector4Parameter(struct FString InVariableName); // Function Niagara.NiagaraParameterCollectionInstance.GetVector4Parameter struct FVector2D GetVector2DParameter(struct FString InVariableName); // Function Niagara.NiagaraParameterCollectionInstance.GetVector2DParameter struct FQuat GetQuatParameter(struct FString InVariableName); // Function Niagara.NiagaraParameterCollectionInstance.GetQuatParameter int32_t GetIntParameter(struct FString InVariableName); // Function Niagara.NiagaraParameterCollectionInstance.GetIntParameter float GetFloatParameter(struct FString InVariableName); // Function Niagara.NiagaraParameterCollectionInstance.GetFloatParameter struct FLinearColor GetColorParameter(struct FString InVariableName); // Function Niagara.NiagaraParameterCollectionInstance.GetColorParameter bool GetBoolParameter(struct FString InVariableName); // Function Niagara.NiagaraParameterCollectionInstance.GetBoolParameter }; // Class Niagara.NiagaraParameterCollection // Size: 0x58 (Inherited: 0x28) struct UNiagaraParameterCollection : public UObject { struct FName Namespace; // 0x28(0x08) struct TArray<struct FNiagaraVariable> Parameters; // 0x30(0x10) struct UNiagaraParameterCollectionInstance* DefaultInstance; // 0x40(0x08) struct FGuid CompileId; // 0x48(0x10) }; // Class Niagara.NiagaraPrecompileContainer // Size: 0x40 (Inherited: 0x28) struct UNiagaraPrecompileContainer : public UObject { struct TArray<struct UNiagaraScript*> Scripts; // 0x28(0x10) struct UNiagaraSystem* System; // 0x38(0x08) }; // Class Niagara.NiagaraPreviewAxis_InterpParamBase // Size: 0x38 (Inherited: 0x28) struct UNiagaraPreviewAxis_InterpParamBase : public UNiagaraPreviewAxis { struct FName Param; // 0x28(0x08) int32_t Count; // 0x30(0x04) char UnknownData_34[0x4]; // 0x34(0x04) }; // Class Niagara.NiagaraPreviewAxis_InterpParamInt32 // Size: 0x40 (Inherited: 0x38) struct UNiagaraPreviewAxis_InterpParamInt32 : public UNiagaraPreviewAxis_InterpParamBase { int32_t Min; // 0x38(0x04) int32_t Max; // 0x3c(0x04) }; // Class Niagara.NiagaraPreviewAxis_InterpParamFloat // Size: 0x40 (Inherited: 0x38) struct UNiagaraPreviewAxis_InterpParamFloat : public UNiagaraPreviewAxis_InterpParamBase { float Min; // 0x38(0x04) float Max; // 0x3c(0x04) }; // Class Niagara.NiagaraPreviewAxis_InterpParamVector2D // Size: 0x48 (Inherited: 0x38) struct UNiagaraPreviewAxis_InterpParamVector2D : public UNiagaraPreviewAxis_InterpParamBase { struct FVector2D Min; // 0x38(0x08) struct FVector2D Max; // 0x40(0x08) }; // Class Niagara.NiagaraPreviewAxis_InterpParamVector // Size: 0x50 (Inherited: 0x38) struct UNiagaraPreviewAxis_InterpParamVector : public UNiagaraPreviewAxis_InterpParamBase { struct FVector Min; // 0x38(0x0c) struct FVector Max; // 0x44(0x0c) }; // Class Niagara.NiagaraPreviewAxis_InterpParamVector4 // Size: 0x60 (Inherited: 0x38) struct UNiagaraPreviewAxis_InterpParamVector4 : public UNiagaraPreviewAxis_InterpParamBase { char UnknownData_38[0x8]; // 0x38(0x08) struct FVector4 Min; // 0x40(0x10) struct FVector4 Max; // 0x50(0x10) }; // Class Niagara.NiagaraPreviewAxis_InterpParamLinearColor // Size: 0x58 (Inherited: 0x38) struct UNiagaraPreviewAxis_InterpParamLinearColor : public UNiagaraPreviewAxis_InterpParamBase { struct FLinearColor Min; // 0x38(0x10) struct FLinearColor Max; // 0x48(0x10) }; // Class Niagara.NiagaraPreviewGrid // Size: 0x270 (Inherited: 0x220) struct ANiagaraPreviewGrid : public AActor { struct UNiagaraSystem* System; // 0x220(0x08) enum class ENiagaraPreviewGridResetMode ResetMode; // 0x228(0x01) char UnknownData_229[0x7]; // 0x229(0x07) struct UNiagaraPreviewAxis* PreviewAxisX; // 0x230(0x08) struct UNiagaraPreviewAxis* PreviewAxisY; // 0x238(0x08) struct ANiagaraPreviewBase* PreviewClass; // 0x240(0x08) float SpacingX; // 0x248(0x04) float SpacingY; // 0x24c(0x04) int32_t NumX; // 0x250(0x04) int32_t NumY; // 0x254(0x04) struct TArray<struct UChildActorComponent*> PreviewComponents; // 0x258(0x10) char UnknownData_268[0x8]; // 0x268(0x08) void SetPaused(bool bPaused); // Function Niagara.NiagaraPreviewGrid.SetPaused void GetPreviews(struct TArray<struct UNiagaraComponent*> OutPreviews); // Function Niagara.NiagaraPreviewGrid.GetPreviews void DeactivatePreviews(); // Function Niagara.NiagaraPreviewGrid.DeactivatePreviews void ActivatePreviews(bool bReset); // Function Niagara.NiagaraPreviewGrid.ActivatePreviews }; // Class Niagara.NiagaraRibbonRendererProperties // Size: 0x760 (Inherited: 0x50) struct UNiagaraRibbonRendererProperties : public UNiagaraRendererProperties { struct UMaterialInterface* Material; // 0x50(0x08) struct FNiagaraUserParameterBinding MaterialUserParamBinding; // 0x58(0x28) enum class ENiagaraRibbonFacingMode FacingMode; // 0x80(0x01) char UnknownData_81[0x3]; // 0x81(0x03) float UV0TilingDistance; // 0x84(0x04) struct FVector2D UV0Scale; // 0x88(0x08) struct FVector2D UV0Offset; // 0x90(0x08) enum class ENiagaraRibbonAgeOffsetMode UV0AgeOffsetMode; // 0x98(0x01) char UnknownData_99[0x3]; // 0x99(0x03) float UV1TilingDistance; // 0x9c(0x04) struct FVector2D UV1Scale; // 0xa0(0x08) struct FVector2D UV1Offset; // 0xa8(0x08) enum class ENiagaraRibbonAgeOffsetMode UV1AgeOffsetMode; // 0xb0(0x01) enum class ENiagaraRibbonDrawDirection DrawDirection; // 0xb1(0x01) char UnknownData_B2[0x2]; // 0xb2(0x02) float CurveTension; // 0xb4(0x04) enum class ENiagaraRibbonTessellationMode TessellationMode; // 0xb8(0x01) char UnknownData_B9[0x3]; // 0xb9(0x03) int32_t TessellationFactor; // 0xbc(0x04) bool bUseConstantFactor; // 0xc0(0x01) char UnknownData_C1[0x3]; // 0xc1(0x03) float TessellationAngle; // 0xc4(0x04) bool bScreenSpaceTessellation; // 0xc8(0x01) char UnknownData_C9[0x7]; // 0xc9(0x07) struct FNiagaraVariableAttributeBinding PositionBinding; // 0xd0(0x78) struct FNiagaraVariableAttributeBinding ColorBinding; // 0x148(0x78) struct FNiagaraVariableAttributeBinding VelocityBinding; // 0x1c0(0x78) struct FNiagaraVariableAttributeBinding NormalizedAgeBinding; // 0x238(0x78) struct FNiagaraVariableAttributeBinding RibbonTwistBinding; // 0x2b0(0x78) struct FNiagaraVariableAttributeBinding RibbonWidthBinding; // 0x328(0x78) struct FNiagaraVariableAttributeBinding RibbonFacingBinding; // 0x3a0(0x78) struct FNiagaraVariableAttributeBinding RibbonIdBinding; // 0x418(0x78) struct FNiagaraVariableAttributeBinding RibbonLinkOrderBinding; // 0x490(0x78) struct FNiagaraVariableAttributeBinding MaterialRandomBinding; // 0x508(0x78) struct FNiagaraVariableAttributeBinding DynamicMaterialBinding; // 0x580(0x78) struct FNiagaraVariableAttributeBinding DynamicMaterial1Binding; // 0x5f8(0x78) struct FNiagaraVariableAttributeBinding DynamicMaterial2Binding; // 0x670(0x78) struct FNiagaraVariableAttributeBinding DynamicMaterial3Binding; // 0x6e8(0x78) }; // Class Niagara.NiagaraScript // Size: 0x520 (Inherited: 0x28) struct UNiagaraScript : public UObject { enum class ENiagaraScriptUsage Usage; // 0x28(0x01) char UnknownData_29[0x3]; // 0x29(0x03) int32_t UsageIndex; // 0x2c(0x04) struct FGuid UsageId; // 0x30(0x10) struct FNiagaraParameterStore RapidIterationParameters; // 0x40(0xb8) struct FNiagaraScriptExecutionParameterStore ScriptExecutionParamStore; // 0xf8(0xd8) struct TArray<struct FNiagaraBoundParameter> ScriptExecutionBoundParameters; // 0x1d0(0x10) struct FNiagaraVMExecutableDataId CachedScriptVMId; // 0x1e0(0x48) char UnknownData_228[0x1b0]; // 0x228(0x1b0) struct FNiagaraVMExecutableData CachedScriptVM; // 0x3d8(0x128) struct TArray<struct UNiagaraParameterCollection*> CachedParameterCollectionReferences; // 0x500(0x10) struct TArray<struct FNiagaraScriptDataInterfaceInfo> CachedDefaultDataInterfaces; // 0x510(0x10) void RaiseOnGPUCompilationComplete(); // Function Niagara.NiagaraScript.RaiseOnGPUCompilationComplete }; // Class Niagara.NiagaraScriptSourceBase // Size: 0x48 (Inherited: 0x28) struct UNiagaraScriptSourceBase : public UObject { char UnknownData_28[0x20]; // 0x28(0x20) }; // Class Niagara.NiagaraSettings // Size: 0x98 (Inherited: 0x38) struct UNiagaraSettings : public UDeveloperSettings { struct TArray<struct FSoftObjectPath> AdditionalParameterTypes; // 0x38(0x10) struct TArray<struct FSoftObjectPath> AdditionalPayloadTypes; // 0x48(0x10) struct TArray<struct FSoftObjectPath> AdditionalParameterEnums; // 0x58(0x10) struct FSoftObjectPath DefaultEffectType; // 0x68(0x18) struct TArray<struct FText> QualityLevels; // 0x80(0x10) struct UNiagaraEffectType* DefaultEffectTypePtr; // 0x90(0x08) }; // Class Niagara.NiagaraSimulationStageBase // Size: 0x38 (Inherited: 0x28) struct UNiagaraSimulationStageBase : public UNiagaraMergeable { struct UNiagaraScript* Script; // 0x28(0x08) struct FName SimulationStageName; // 0x30(0x08) }; // Class Niagara.NiagaraSimulationStageGeneric // Size: 0x70 (Inherited: 0x38) struct UNiagaraSimulationStageGeneric : public UNiagaraSimulationStageBase { enum class ENiagaraIterationSource IterationSource; // 0x38(0x01) char UnknownData_39[0x3]; // 0x39(0x03) int32_t Iterations; // 0x3c(0x04) char bSpawnOnly : 1; // 0x40(0x01) char UnknownData_40_1 : 7; // 0x40(0x01) char UnknownData_41[0x7]; // 0x41(0x07) struct FNiagaraVariableDataInterfaceBinding DataInterface; // 0x48(0x28) }; // Class Niagara.NiagaraSpriteRendererProperties // Size: 0x8b0 (Inherited: 0x50) struct UNiagaraSpriteRendererProperties : public UNiagaraRendererProperties { struct UMaterialInterface* Material; // 0x50(0x08) struct FNiagaraUserParameterBinding MaterialUserParamBinding; // 0x58(0x28) enum class ENiagaraSpriteAlignment Alignment; // 0x80(0x01) enum class ENiagaraSpriteFacingMode FacingMode; // 0x81(0x01) char UnknownData_82[0x2]; // 0x82(0x02) struct FVector2D PivotInUVSpace; // 0x84(0x08) enum class ENiagaraSortMode SortMode; // 0x8c(0x01) char UnknownData_8D[0x3]; // 0x8d(0x03) struct FVector2D SubImageSize; // 0x90(0x08) char bSubImageBlend : 1; // 0x98(0x01) char bRemoveHMDRollInVR : 1; // 0x98(0x01) char bSortOnlyWhenTranslucent : 1; // 0x98(0x01) char UnknownData_98_3 : 5; // 0x98(0x01) char UnknownData_99[0x3]; // 0x99(0x03) float MinFacingCameraBlendDistance; // 0x9c(0x04) float MaxFacingCameraBlendDistance; // 0xa0(0x04) char UnknownData_A4[0x4]; // 0xa4(0x04) struct FNiagaraVariableAttributeBinding PositionBinding; // 0xa8(0x78) struct FNiagaraVariableAttributeBinding ColorBinding; // 0x120(0x78) struct FNiagaraVariableAttributeBinding VelocityBinding; // 0x198(0x78) struct FNiagaraVariableAttributeBinding SpriteRotationBinding; // 0x210(0x78) struct FNiagaraVariableAttributeBinding SpriteSizeBinding; // 0x288(0x78) struct FNiagaraVariableAttributeBinding SpriteFacingBinding; // 0x300(0x78) struct FNiagaraVariableAttributeBinding SpriteAlignmentBinding; // 0x378(0x78) struct FNiagaraVariableAttributeBinding SubImageIndexBinding; // 0x3f0(0x78) struct FNiagaraVariableAttributeBinding DynamicMaterialBinding; // 0x468(0x78) struct FNiagaraVariableAttributeBinding DynamicMaterial1Binding; // 0x4e0(0x78) struct FNiagaraVariableAttributeBinding DynamicMaterial2Binding; // 0x558(0x78) struct FNiagaraVariableAttributeBinding DynamicMaterial3Binding; // 0x5d0(0x78) struct FNiagaraVariableAttributeBinding CameraOffsetBinding; // 0x648(0x78) struct FNiagaraVariableAttributeBinding UVScaleBinding; // 0x6c0(0x78) struct FNiagaraVariableAttributeBinding MaterialRandomBinding; // 0x738(0x78) struct FNiagaraVariableAttributeBinding CustomSortingBinding; // 0x7b0(0x78) struct FNiagaraVariableAttributeBinding NormalizedAgeBinding; // 0x828(0x78) char UnknownData_8A0[0x10]; // 0x8a0(0x10) }; // Class Niagara.NiagaraSystem // Size: 0x478 (Inherited: 0x30) struct UNiagaraSystem : public UFXSystemAsset { char UnknownData_30[0x1]; // 0x30(0x01) bool bDumpDebugSystemInfo; // 0x31(0x01) bool bDumpDebugEmitterInfo; // 0x32(0x01) char UnknownData_33[0x1]; // 0x33(0x01) char bFixedBounds : 1; // 0x34(0x01) char UnknownData_34_1 : 7; // 0x34(0x01) char UnknownData_35[0x3]; // 0x35(0x03) struct UNiagaraEffectType* EffectType; // 0x38(0x08) bool bOverrideScalabilitySettings; // 0x40(0x01) char UnknownData_41[0x7]; // 0x41(0x07) struct TArray<struct FNiagaraSystemScalabilityOverride> ScalabilityOverrides; // 0x48(0x10) struct FNiagaraSystemScalabilityOverrides SystemScalabilityOverrides; // 0x58(0x10) struct TArray<struct FNiagaraEmitterHandle> EmitterHandles; // 0x68(0x10) struct TArray<struct UNiagaraParameterCollectionInstance*> ParameterCollectionOverrides; // 0x78(0x10) struct UNiagaraScript* SystemSpawnScript; // 0x88(0x08) struct UNiagaraScript* SystemUpdateScript; // 0x90(0x08) char UnknownData_98[0x10]; // 0x98(0x10) struct FNiagaraSystemCompiledData SystemCompiledData; // 0xa8(0x258) struct FNiagaraUserRedirectionParameterStore ExposedParameters; // 0x300(0x108) struct FBox FixedBounds; // 0x408(0x1c) bool bAutoDeactivate; // 0x424(0x01) char UnknownData_425[0x3]; // 0x425(0x03) float WarmupTime; // 0x428(0x04) int32_t WarmupTickCount; // 0x42c(0x04) float WarmupTickDelta; // 0x430(0x04) bool bHasSystemScriptDIsWithPerInstanceData; // 0x434(0x01) char UnknownData_435[0x3]; // 0x435(0x03) struct TArray<struct FName> UserDINamesReadInSystemScripts; // 0x438(0x10) char UnknownData_448[0x30]; // 0x448(0x30) };
51.818538
203
0.809689
[ "object" ]
301dc6d478f2de65a6cb35ab2f4fea19f3867170
981
h
C
src/ufo/locations_f.h
fmahebert/ufo
2af9b91433553ca473c72fcd131400a01c3aabdb
[ "Apache-2.0" ]
4
2020-12-04T08:26:06.000Z
2021-11-20T01:18:47.000Z
src/ufo/locations_f.h
fmahebert/ufo
2af9b91433553ca473c72fcd131400a01c3aabdb
[ "Apache-2.0" ]
21
2020-10-30T08:57:16.000Z
2021-05-17T15:11:20.000Z
src/ufo/locations_f.h
fmahebert/ufo
2af9b91433553ca473c72fcd131400a01c3aabdb
[ "Apache-2.0" ]
31
2021-06-24T18:07:53.000Z
2021-10-08T15:40:39.000Z
/* * (C) Copyright 2020 UCAR * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. */ #ifndef UFO_LOCATIONS_F_H_ #define UFO_LOCATIONS_F_H_ #include <vector> #include "ufo/Locations.h" // ----------------------------------------------------------------------------- // These functions provide a Fortran-callable interface to Locations // ----------------------------------------------------------------------------- namespace ufo { extern "C" { std::size_t locations_get_nlocs_f(const Locations &); void locations_get_lons_f(const Locations &, const std::size_t &, double *); void locations_get_lats_f(const Locations &, const std::size_t &, double *); void locations_get_timemask_f(const Locations &, const util::DateTime &, const util::DateTime &, const std::size_t &, bool *); } } // namespace ufo #endif // UFO_LOCATIONS_F_H_
31.645161
85
0.590214
[ "vector" ]
301ff4dcd375e4aec0c92caa15aaa4a1cbea934a
1,695
h
C
PDxProjects/CharacterAnimation/Sample.h
bear1704/DX11_Portfolio
8ab70c793cf7f10eceaea34afb786264828c09a0
[ "Apache-2.0" ]
null
null
null
PDxProjects/CharacterAnimation/Sample.h
bear1704/DX11_Portfolio
8ab70c793cf7f10eceaea34afb786264828c09a0
[ "Apache-2.0" ]
null
null
null
PDxProjects/CharacterAnimation/Sample.h
bear1704/DX11_Portfolio
8ab70c793cf7f10eceaea34afb786264828c09a0
[ "Apache-2.0" ]
null
null
null
#pragma once #define _CRT_SECURE_NO_WARNINGS #include "PCore.h" #include "PTexture.h" #include "PShape.h" #include "PDxState.h" #include "PFreeCamera.h" #include "PDxRenderTarget.h" #include "PLightObj.h" #include "PKgcObj.h" #include "PSkmObj.h" #include "PMatObj.h" #if defined(DEBUG) || defined(_DEBUG) #pragma comment (lib, "PDxCoreLib64_D.lib") #else #pragma comment (lib, "PDxCoreLib64_R.lib") #endif #pragma comment (lib, "fmod_vc.lib") #pragma comment (lib, "winmm.lib") class PSCharacter { public: PSCharacter(); ~PSCharacter(); public: std::vector<PModel*> object_list_; multibyte_string character_name_; multibyte_string shader_name_; PMatObj* matrix_; }; struct CB_VS_ChangesEveryFrame { D3DXMATRIX mat_normal; D3DXVECTOR3 light_pos; float padding1; D3DXVECTOR3 camera_pos; float padding2; D3DXVECTOR3 vec_look; float padding3; }; struct CB_VS_NearlyNotChange { D3DXVECTOR4 cb_AmbientLightColor; D3DXVECTOR4 cb_DiffuseLightColor; D3DXVECTOR4 cb_SpecularLightColor; }; class Sample : public PCore { public: Sample(); ~Sample(); private: PParser parse_; PSCharacter character_; PCamera* main_camera_; PFreeCamera free_camera_; std::vector<PModel*> object_list_; PLightObj light_obj_; std::wstring object_file_texture_path_; float elapsed_time_; public: bool Init() override; bool Frame() override; bool Render() override; bool Release() override; public: void MessageProc(MSG msg) override; PModel* LoadSheetObject(multibyte_string filename, std::wstring vs_shader_path, std::string vs_func_name, std::wstring ps_shader_path, std::string ps_func_name, std::wstring texture_path = L""); }; PCORE_RUN(L"Animation Viewer", 0, 0, 800, 600);
19.709302
106
0.765192
[ "render", "vector" ]
302533ce1f7e9596ccbfd5666a46a34e0df24f4c
8,603
h
C
src/yb/yql/cql/ql/exec/exec_context.h
ananyaks/yugabyte-db
2a4fb09169da3a4c08740e88388576251312589a
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
src/yb/yql/cql/ql/exec/exec_context.h
ananyaks/yugabyte-db
2a4fb09169da3a4c08740e88388576251312589a
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
src/yb/yql/cql/ql/exec/exec_context.h
ananyaks/yugabyte-db
2a4fb09169da3a4c08740e88388576251312589a
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
//-------------------------------------------------------------------------------------------------- // Copyright (c) YugaByte, 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. // // // This class represents the context to execute a single statment. It contains the statement code // (parse tree) and the environment (parameters and session context) with which the code is to be // executed. //-------------------------------------------------------------------------------------------------- #ifndef YB_YQL_CQL_QL_EXEC_EXEC_CONTEXT_H_ #define YB_YQL_CQL_QL_EXEC_EXEC_CONTEXT_H_ #include "yb/yql/cql/ql/ptree/process_context.h" #include "yb/yql/cql/ql/util/ql_env.h" #include "yb/yql/cql/ql/util/statement_params.h" #include "yb/yql/cql/ql/util/statement_result.h" #include "yb/common/common.pb.h" #include "yb/client/client.h" namespace yb { namespace ql { class TnodeContext { public: explicit TnodeContext(const TreeNode* tnode); // Returns the tree node of the statement being executed. const TreeNode* tnode() const { return tnode_; } // Access function for start_time and end_time. const MonoTime& start_time() const { return start_time_; } const MonoTime& end_time() const { return end_time_; } void set_end_time(const MonoTime& end_time) { end_time_ = end_time; } MonoDelta execution_time() const { return end_time_ - start_time_; } // Access function for op. std::vector<client::YBqlOpPtr>& ops() { return ops_; } const std::vector<client::YBqlOpPtr>& ops() const { return ops_; } // Add an operation. void AddOperation(const client::YBqlOpPtr& op) { ops_.push_back(op); } // Does this statement have pending operations? bool HasPendingOperations() const; // Used for multi-partition selects (i.e. with 'IN' conditions on hash columns). // Called from Executor::FetchMoreRowsIfNeeded to check if request is finished. uint64_t UnreadPartitionsRemaining() const { return partitions_count_ - current_partition_index_; } // Used for multi-partition selects (i.e. with 'IN' conditions on hash columns). // Initializes the current partition index and sets the corresponding hashed column values in the // request object so that it references the appropriate partition. // Called from Executor::ExecPTNode for PTSelectStmt. // E.g. for a query "h1 = 1 and h2 in (2,3) and h3 in (4,5) and h4 = 6" start_position 0: // this will set req->hashed_column_values() to [1, 2, 4, 6]. void InitializePartition(QLReadRequestPB *req, uint64_t start_partition); // Used for multi-partition selects (i.e. with 'IN' conditions on hash columns). // Increments the current partition index and updates the corresponding hashed column values in // passed request object so that it references the appropriate partition. // Called from Executor::FetchMoreRowsIfNeeded. // E.g. for a query "h1 = 1 and h2 in (2,3) and h3 in (4,5) and h4 = 6" partition index 2: // this will do, index: 2 -> 3 and hashed_column_values: [1, 3, 4, 6] -> [1, 3, 5, 6]. void AdvanceToNextPartition(QLReadRequestPB *req); std::vector<std::vector<QLExpressionPB>>& hash_values_options() { if (!hash_values_options_) { hash_values_options_.emplace(); } return *hash_values_options_; } uint64_t current_partition_index() const { return current_partition_index_; } void set_partitions_count(const uint64_t count) { partitions_count_ = count; } private: // Tree node of the statement being executed. const TreeNode* tnode_ = nullptr; // Execution start and end time. const MonoTime start_time_; MonoTime end_time_; // Read/write operations to execute. std::vector<client::YBqlOpPtr> ops_; // For multi-partition selects (e.g. selects with 'IN' condition on hash cols) we hold the options // for each hash column (starting from first 'IN') as we iteratively query each partition. // e.g. for a query "h1 = 1 and h2 in (2,3) and h3 in (4,5) and h4 = 6". // hash_values_options_ = [[2, 3], [4, 5], [6]] // partitions_count_ = 4 (i.e. [2,4,6], [2,5,6], [3,4,6], [4,5,6]). // current_partition_index_ starts from 0 unless set in the paging state. boost::optional<std::vector<std::vector<QLExpressionPB>>> hash_values_options_; uint64_t partitions_count_ = 0; uint64_t current_partition_index_ = 0; }; // The context for execution of a statement. Inside the statement parse tree, there may be one or // more statement tnodes to be executed. class ExecContext : public ProcessContextBase { public: //------------------------------------------------------------------------------------------------ // Public types. typedef std::unique_ptr<ExecContext> UniPtr; typedef std::unique_ptr<const ExecContext> UniPtrConst; //------------------------------------------------------------------------------------------------ // Constructor & destructor. // Constructs an execution context to execute a statement. The context saves references to the // parse tree and parameters. ExecContext(const ParseTree& parse_tree, const StatementParameters& params); virtual ~ExecContext(); // Returns the statement string being executed. const std::string& stmt() const override { return parse_tree_.stmt(); } // Access function for parse_tree and params. const ParseTree& parse_tree() const { return parse_tree_; } const StatementParameters& params() const { return params_; } // Add a statement tree node to be executed. void AddTnode(const TreeNode *tnode) { tnode_contexts_.emplace_back(tnode); } // Returns the context for the current tree node being executed. TnodeContext& tnode_context(); // Return the tnode contexts being executed. std::list<TnodeContext>& tnode_contexts() { return tnode_contexts_; } //------------------------------------------------------------------------------------------------ // Start a distributed transaction. void StartTransaction(IsolationLevel isolation_level, QLEnv* ql_env); // Is a transaction currently in progress? bool HasTransaction() const { return transaction_ != nullptr; } // Returns the start time of the transaction. const MonoTime& transaction_start_time() const { return transaction_start_time_; } // Prepare a child distributed transaction. CHECKED_STATUS PrepareChildTransaction(ChildTransactionDataPB* data); // Apply the result of a child distributed transaction. CHECKED_STATUS ApplyChildTransactionResult(const ChildTransactionResultPB& result); // Commit the current distributed transaction. void CommitTransaction(client::CommitCallback callback); // Abort the current distributed transaction. void AbortTransaction(); // Return the transactional session of the statement. client::YBSessionPtr transactional_session() { DCHECK(transaction_ && transactional_session_) << "transaction missing in this statement"; return transactional_session_; } // Does this statement have pending operations? bool HasPendingOperations() const; //------------------------------------------------------------------------------------------------ client::Restart restart() const { return restart_; } int64_t num_retries() const { return num_retries_; } // Reset this ExecContext. void Reset(client::Restart restart); private: // Statement parse tree to execute and parameters to execute with. const ParseTree& parse_tree_; const StatementParameters& params_; // Should this statement be restarted? client::Restart restart_ = client::Restart::kFalse; // Contexts to execute statement tnodes. std::list<TnodeContext> tnode_contexts_; // Transaction and session to apply transactional write operations in and the start time. client::YBTransactionPtr transaction_; client::YBSessionPtr transactional_session_; MonoTime transaction_start_time_; // The number of times this statement has been retried. int64_t num_retries_ = 0; }; } // namespace ql } // namespace yb #endif // YB_YQL_CQL_QL_EXEC_EXEC_CONTEXT_H_
35.114286
100
0.680112
[ "object", "vector" ]
3027047840961f51754fa0b876c644334226d38d
5,924
c
C
src/Json/JsonValue.c
loachtech/tiny-core
d8c5e2f33ac5a37e7275b952f2546254301570af
[ "MIT" ]
null
null
null
src/Json/JsonValue.c
loachtech/tiny-core
d8c5e2f33ac5a37e7275b952f2546254301570af
[ "MIT" ]
null
null
null
src/Json/JsonValue.c
loachtech/tiny-core
d8c5e2f33ac5a37e7275b952f2546254301570af
[ "MIT" ]
null
null
null
/** * Copyright (C) 2013-2015 * * @author jxfengzi@gmail.com * @date 2013-11-19 * * @file JsonValue.c * * @remark * */ #include <tiny_malloc.h> #include <tiny_log.h> #include "JsonValue.h" #include "value/JsonString.h" #include "value/JsonNumber.h" #include "value/JsonBoolean.h" #include "JsonObject.h" #include "JsonArray.h" #define TAG "JsonValue" static TinyRet JsonValue_Construct(JsonValue *thiz) { memset(thiz, 0, sizeof(JsonValue)); thiz->type = JSON_UNDEFINED; return TINY_RET_OK; } JsonValue * JsonValue_New(void) { JsonValue * thiz = NULL; do { thiz = (JsonValue *) tiny_malloc(sizeof(JsonValue)); if (thiz == NULL) { break; } if (RET_FAILED(JsonValue_Construct(thiz))) { LOG_E(TAG, "JsonValue_Construct FAILED"); JsonValue_Delete(thiz); thiz = NULL; break; } } while (false); return thiz; } JsonValue * JsonValue_NewString(const char *value) { JsonValue * thiz = JsonValue_New(); if (thiz != NULL) { thiz->type = JSON_STRING; thiz->data.string = JsonString_New(value); if (thiz->data.string == NULL) { JsonValue_Delete(thiz); thiz = NULL; } } return thiz; } JsonValue * JsonValue_NewInteger(long value) { JsonValue * thiz = JsonValue_New(); if (thiz != NULL) { thiz->type = JSON_NUMBER; thiz->data.number = JsonNumber_NewInteger(value); if (thiz->data.number == NULL) { JsonValue_Delete(thiz); thiz = NULL; } } return thiz; } JsonValue * JsonValue_NewFloat(float value) { JsonValue * thiz = JsonValue_New(); if (thiz != NULL) { thiz->type = JSON_NUMBER; thiz->data.number = JsonNumber_NewFloat(value); if (thiz->data.number == NULL) { JsonValue_Delete(thiz); thiz = NULL; } } return thiz; } JsonValue * JsonValue_NewBoolean(bool value) { JsonValue * thiz = JsonValue_New(); if (thiz != NULL) { thiz->type = JSON_BOOLEAN; thiz->data.boolean = JsonBoolean_New(value); if (thiz->data.boolean == NULL) { JsonValue_Delete(thiz); thiz = NULL; } } return thiz; } JsonValue * JsonValue_NewNull() { JsonValue * thiz = JsonValue_New(); if (thiz != NULL) { thiz->type = JSON_NULL; } return thiz; } JsonValue * JsonValue_NewValue(JsonValueType type, void *value) { JsonValue * thiz = NULL; if (value != NULL) { thiz = JsonValue_New(); if (thiz != NULL) { thiz->type = type; switch (type) { case JSON_STRING: thiz->data.string = (JsonString *)value; break; case JSON_NUMBER: thiz->data.number = (JsonNumber *)value; break; case JSON_OBJECT: thiz->data.object = (JsonObject *)value; break; case JSON_ARRAY: thiz->data.array = (JsonArray *)value; break; case JSON_BOOLEAN: thiz->data.boolean = (JsonBoolean *)value; break; case JSON_NULL: case JSON_UNDEFINED: JsonValue_Delete(thiz); thiz = NULL; break; } } } return thiz; } JsonValue * JsonValue_NewFrom(JsonValue *other) { JsonValue * thiz = NULL; if (other != NULL) { switch (other->type) { case JSON_STRING: thiz = JsonValue_NewString(other->data.string->value); break; case JSON_NUMBER: if (other->data.number->type == JSON_NUMBER_INTEGER) { thiz = JsonValue_NewInteger(other->data.number->value.intValue); } else { thiz = JsonValue_NewFloat(other->data.number->value.floatValue); } break; case JSON_BOOLEAN: thiz = JsonValue_NewBoolean(other->data.boolean->value); break; case JSON_NULL: thiz = JsonValue_NewNull(); break; // case JSON_OBJECT: // break; // // case JSON_ARRAY: // break; // // case JSON_UNDEFINED: // break; default: LOG_D(TAG, "JsonValue_Copy failed, type(%d) not supported", other->type); break; } } return thiz; } void JsonValue_Delete(JsonValue *thiz) { switch (thiz->type) { case JSON_STRING: if (thiz->data.string != NULL) { JsonString_Delete(thiz->data.string); } break; case JSON_NUMBER: if (thiz->data.number != NULL) { JsonNumber_Delete(thiz->data.number); } break; case JSON_OBJECT: if (thiz->data.object != NULL) { JsonObject_Delete(thiz->data.object); } break; case JSON_ARRAY: if (thiz->data.array != NULL) { JsonArray_Delete(thiz->data.array); } break; case JSON_BOOLEAN: if (thiz->data.boolean != NULL) { JsonBoolean_Delete(thiz->data.boolean); } break; case JSON_UNDEFINED: case JSON_NULL: break; } tiny_free(thiz); }
20.785965
89
0.48582
[ "object" ]
302b0c49e8d1836a84e2132cdfc8fbe4b75fd34b
18,976
h
C
src/ctlinterfaces/exlvw/LegacyTestThumbnailCacheTask.h
TimoKunze/ShellBrowserControls
e1699dde8821a55f43274364410c3d6a3c867526
[ "MIT" ]
3
2020-02-03T12:58:10.000Z
2021-03-30T04:55:04.000Z
src/ctlinterfaces/exlvw/LegacyTestThumbnailCacheTask.h
TimoKunze/ShellBrowserControls
e1699dde8821a55f43274364410c3d6a3c867526
[ "MIT" ]
null
null
null
src/ctlinterfaces/exlvw/LegacyTestThumbnailCacheTask.h
TimoKunze/ShellBrowserControls
e1699dde8821a55f43274364410c3d6a3c867526
[ "MIT" ]
1
2021-12-09T18:23:05.000Z
2021-12-09T18:23:05.000Z
////////////////////////////////////////////////////////////////////// /// \class ShLvwLegacyTestThumbnailCacheTask /// \author Timo "TimoSoft" Kunze /// \brief <em>Specialization of \c RunnableTask for extracting a thumbnail</em> /// /// This class is a specialization of \c RunnableTask. It is used to create a new task that will extract /// the thumbnail either from the disk cache or from the shell. /// /// \sa RunnableTask ////////////////////////////////////////////////////////////////////// #pragma once #include "../../helpers.h" #include "../common.h" #include "../RunnableTask.h" #include "../IShellImageStore.h" #include "LegacyExtractThumbnailTask.h" #include "LegacyExtractThumbnailFromDiskCacheTask.h" // {9C46727A-4EAE-46e4-84DE-06F33E617251} DEFINE_GUID(CLSID_ShLvwLegacyTestThumbnailCacheTask, 0x9c46727a, 0x4eae, 0x46e4, 0x84, 0xde, 0x6, 0xf3, 0x3e, 0x61, 0x72, 0x51); class ShLvwLegacyTestThumbnailCacheTask : public CComCoClass<ShLvwLegacyTestThumbnailCacheTask, &CLSID_ShLvwLegacyTestThumbnailCacheTask>, public RunnableTask { public: /// \brief <em>The constructor of this class</em> /// /// Used for initialization. /// /// \sa Attach ShLvwLegacyTestThumbnailCacheTask(void); /// \brief <em>This is the last method that is called before the object is destroyed</em> /// /// \sa RunnableTask::FinalRelease void FinalRelease(); protected: #ifdef USE_STL /// \brief <em>Initializes the object</em> /// /// Used for initialization. /// /// \param[in] hWndShellUIParentWindow The window that is used as parent window for any UI that the /// shell may display. /// \param[in] hWndToNotify The window to which to send the extraction task. This window has to handle /// the \c WM_TRIGGER_ENQUEUETASK message. /// \param[in] pTasksToEnqueue A queue holding the created task until it is sent to the scheduler. /// Access to this object has to be synchronized using the critical section specified by /// \c pTasksToEnqueueCritSection. /// \param[in] pTasksToEnqueueCritSection The critical section that has to be used to synchronize /// access to \c pTasksToEnqueue. /// \param[in] pBackgroundThumbnailsQueue A queue holding the retrieved thumbnail information until the /// image list is updated. Access to this object has to be synchronized using the critical /// section specified by \c pBackgroundThumbnailsCritSection. /// \param[in] pBackgroundThumbnailsCritSection The critical section that has to be used to synchronize /// access to \c pBackgroundThumbnailsQueue. /// \param[in] pIDL The fully qualified pIDL of the item for which to retrieve the thumbnail. /// \param[in] itemID The item for which to extract the thumbnail. /// \param[in] itemIsFile Specifies whether the item, for which to extract the thumbnail, is a file. /// \param[in] pExtractImage The \c IExtractImage object used to retrieve the thumbnail. /// \param[in] useThumbnailDiskCache If \c TRUE, the thumbnail disk cache is used; otherwise not. /// \param[in] pThumbnailDiskCache The \c IShellImageStore object used to access the disk cache. /// \param[in] imageSize The size in pixels of the thumbnail to retrieve. /// \param[in] pThumbnailPath The path to the thumbnail to extract. /// \param[in] pItemPath The path to the item for which to retrieve the thumbnail. /// \param[in] dateStamp The date when the thumbnail to extract has been updated. /// \param[in] flags The \c IEIFLAG_* flags to use for extraction. /// \param[in] priority The priority to use for new background tasks. /// \param[in] asynchronousExtraction If \c TRUE, the extraction should be done in a background task. /// /// \return An \c HRESULT error code. /// /// \sa CreateInstance, WM_TRIGGER_ENQUEUETASK, IShellImageStore, /// <a href="https://msdn.microsoft.com/en-us/library/bb761848.aspx">IExtractImage</a>, /// <a href="https://msdn.microsoft.com/en-us/library/bb761846.aspx">IExtractImage::GetLocation</a> HRESULT Attach(HWND hWndShellUIParentWindow, HWND hWndToNotify, std::queue<LPSHCTLSBACKGROUNDTASKINFO>* pTasksToEnqueue, LPCRITICAL_SECTION pTasksToEnqueueCritSection, std::queue<LPSHLVWBACKGROUNDTHUMBNAILINFO>* pBackgroundThumbnailsQueue, LPCRITICAL_SECTION pBackgroundThumbnailsCritSection, __in PCIDLIST_ABSOLUTE pIDL, LONG itemID, BOOL itemIsFile, __in LPEXTRACTIMAGE pExtractImage, BOOL useThumbnailDiskCache, __in_opt LPSHELLIMAGESTORE pThumbnailDiskCache, SIZE imageSize, __in LPWSTR pThumbnailPath, __in LPWSTR pItemPath, FILETIME dateStamp, DWORD flags, DWORD priority, BOOL asynchronousExtraction); #else /// \brief <em>Initializes the object</em> /// /// Used for initialization. /// /// \param[in] hWndShellUIParentWindow The window that is used as parent window for any UI that the /// shell may display. /// \param[in] hWndToNotify The window to which to send the extraction task. This window has to handle /// the \c WM_TRIGGER_ENQUEUETASK message. /// \param[in] pTasksToEnqueue A queue holding the created task until it is sent to the scheduler. /// Access to this object has to be synchronized using the critical section specified by /// \c pTasksToEnqueueCritSection. /// \param[in] pTasksToEnqueueCritSection The critical section that has to be used to synchronize /// access to \c pTasksToEnqueue. /// \param[in] pBackgroundThumbnailsQueue A queue holding the retrieved thumbnail information until the /// image list is updated. Access to this object has to be synchronized using the critical /// section specified by \c pBackgroundThumbnailsCritSection. /// \param[in] pBackgroundThumbnailsCritSection The critical section that has to be used to synchronize /// access to \c pBackgroundThumbnailsQueue. /// \param[in] pIDL The fully qualified pIDL of the item for which to retrieve the thumbnail. /// \param[in] itemID The item for which to extract the thumbnail. /// \param[in] itemIsFile Specifies whether the item, for which to extract the thumbnail, is a file. /// \param[in] pExtractImage The \c IExtractImage object used to retrieve the thumbnail. /// \param[in] useThumbnailDiskCache If \c TRUE, the thumbnail disk cache is used; otherwise not. /// \param[in] pThumbnailDiskCache The \c IShellImageStore object used to access the disk cache. /// \param[in] imageSize The size in pixels of the thumbnail to retrieve. /// \param[in] pThumbnailPath The path to the thumbnail to extract. /// \param[in] pItemPath The path to the item for which to retrieve the thumbnail. /// \param[in] dateStamp The date when the thumbnail to extract has been updated. /// \param[in] flags The \c IEIFLAG_* flags to use for extraction. /// \param[in] priority The priority to use for new background tasks. /// \param[in] asynchronousExtraction If \c TRUE, the extraction should be done in a background task. /// /// \return An \c HRESULT error code. /// /// \sa CreateInstance, WM_TRIGGER_ENQUEUETASK, IShellImageStore, /// <a href="https://msdn.microsoft.com/en-us/library/bb761848.aspx">IExtractImage</a>, /// <a href="https://msdn.microsoft.com/en-us/library/bb761846.aspx">IExtractImage::GetLocation</a> HRESULT Attach(HWND hWndShellUIParentWindow, HWND hWndToNotify, CAtlList<LPSHCTLSBACKGROUNDTASKINFO>* pTasksToEnqueue, LPCRITICAL_SECTION pTasksToEnqueueCritSection, CAtlList<LPSHLVWBACKGROUNDTHUMBNAILINFO>* pBackgroundThumbnailsQueue, LPCRITICAL_SECTION pBackgroundThumbnailsCritSection, __in PCIDLIST_ABSOLUTE pIDL, LONG itemID, BOOL itemIsFile, __in LPEXTRACTIMAGE pExtractImage, BOOL useThumbnailDiskCache, __in_opt LPSHELLIMAGESTORE pThumbnailDiskCache, SIZE imageSize, __in LPWSTR pThumbnailPath, __in LPWSTR pItemPath, FILETIME dateStamp, DWORD flags, DWORD priority, BOOL asynchronousExtraction); #endif public: #ifdef USE_STL /// \brief <em>Creates a new instance of this class</em> /// /// \param[in] hWndShellUIParentWindow The window that is used as parent window for any UI that the /// shell may display. /// \param[in] hWndToNotify The window to which to send the extraction task. This window has to handle /// the \c WM_TRIGGER_ENQUEUETASK message. /// \param[in] pTasksToEnqueue A queue holding the created task until it is sent to the scheduler. /// Access to this object has to be synchronized using the critical section specified by /// \c pTasksToEnqueueCritSection. /// \param[in] pTasksToEnqueueCritSection The critical section that has to be used to synchronize /// access to \c pTasksToEnqueue. /// \param[in] pBackgroundThumbnailsQueue A queue holding the retrieved thumbnail information until the /// image list is updated. Access to this object has to be synchronized using the critical /// section specified by \c pBackgroundThumbnailsCritSection. /// \param[in] pBackgroundThumbnailsCritSection The critical section that has to be used to synchronize /// access to \c pBackgroundThumbnailsQueue. /// \param[in] pIDL The fully qualified pIDL of the item for which to retrieve the thumbnail. /// \param[in] itemID The item for which to extract the thumbnail. /// \param[in] itemIsFile Specifies whether the item, for which to extract the thumbnail, is a file. /// \param[in] pExtractImage The \c IExtractImage object used to retrieve the thumbnail. /// \param[in] useThumbnailDiskCache If \c TRUE, the thumbnail disk cache is used; otherwise not. /// \param[in] pThumbnailDiskCache The \c IShellImageStore object used to access the disk cache. /// \param[in] imageSize The size in pixels of the thumbnail to retrieve. /// \param[in] pThumbnailPath The path to the thumbnail to extract. /// \param[in] pItemPath The path to the item for which to retrieve the thumbnail. /// \param[in] dateStamp The date when the thumbnail to extract has been updated. /// \param[in] flags The \c IEIFLAG_* flags to use for extraction. /// \param[in] priority The priority to use for new background tasks. /// \param[in] asynchronousExtraction If \c TRUE, the extraction should be done in a background task. /// \param[out] ppTask Receives the task object's implementation of the \c IRunnableTask interface. /// /// \return An \c HRESULT error code. /// /// \sa Attach, WM_TRIGGER_ENQUEUETASK, IShellImageStore, /// <a href="https://msdn.microsoft.com/en-us/library/bb761848.aspx">IExtractImage</a>, /// <a href="https://msdn.microsoft.com/en-us/library/bb761846.aspx">IExtractImage::GetLocation</a>, /// <a href="https://msdn.microsoft.com/en-us/library/bb775201.aspx">IRunnableTask</a> static HRESULT CreateInstance(HWND hWndShellUIParentWindow, HWND hWndToNotify, std::queue<LPSHCTLSBACKGROUNDTASKINFO>* pTasksToEnqueue, LPCRITICAL_SECTION pTasksToEnqueueCritSection, std::queue<LPSHLVWBACKGROUNDTHUMBNAILINFO>* pBackgroundThumbnailsQueue, LPCRITICAL_SECTION pBackgroundThumbnailsCritSection, __in PCIDLIST_ABSOLUTE pIDL, LONG itemID, BOOL itemIsFile, __in LPEXTRACTIMAGE pExtractImage, BOOL useThumbnailDiskCache, __in_opt LPSHELLIMAGESTORE pThumbnailDiskCache, SIZE imageSize, __in LPWSTR pThumbnailPath, __in LPWSTR pItemPath, FILETIME dateStamp, DWORD flags, DWORD priority, BOOL asynchronousExtraction, __deref_out IRunnableTask** ppTask); #else /// \brief <em>Creates a new instance of this class</em> /// /// \param[in] hWndShellUIParentWindow The window that is used as parent window for any UI that the /// shell may display. /// \param[in] hWndToNotify The window to which to send the extraction task. This window has to handle /// the \c WM_TRIGGER_ENQUEUETASK message. /// \param[in] pTasksToEnqueue A queue holding the created task until it is sent to the scheduler. /// Access to this object has to be synchronized using the critical section specified by /// \c pTasksToEnqueueCritSection. /// \param[in] pTasksToEnqueueCritSection The critical section that has to be used to synchronize /// access to \c pTasksToEnqueue. /// \param[in] pBackgroundThumbnailsQueue A queue holding the retrieved thumbnail information until the /// image list is updated. Access to this object has to be synchronized using the critical /// section specified by \c pBackgroundThumbnailsCritSection. /// \param[in] pBackgroundThumbnailsCritSection The critical section that has to be used to synchronize /// access to \c pBackgroundThumbnailsQueue. /// \param[in] pIDL The fully qualified pIDL of the item for which to retrieve the thumbnail. /// \param[in] itemID The item for which to extract the thumbnail. /// \param[in] itemIsFile Specifies whether the item, for which to extract the thumbnail, is a file. /// \param[in] pExtractImage The \c IExtractImage object used to retrieve the thumbnail. /// \param[in] useThumbnailDiskCache If \c TRUE, the thumbnail disk cache is used; otherwise not. /// \param[in] pThumbnailDiskCache The \c IShellImageStore object used to access the disk cache. /// \param[in] imageSize The size in pixels of the thumbnail to retrieve. /// \param[in] pThumbnailPath The path to the thumbnail to extract. /// \param[in] pItemPath The path to the item for which to retrieve the thumbnail. /// \param[in] dateStamp The date when the thumbnail to extract has been updated. /// \param[in] flags The \c IEIFLAG_* flags to use for extraction. /// \param[in] priority The priority to use for new background tasks. /// \param[in] asynchronousExtraction If \c TRUE, the extraction should be done in a background task. /// \param[out] ppTask Receives the task object's implementation of the \c IRunnableTask interface. /// /// \return An \c HRESULT error code. /// /// \sa Attach, WM_TRIGGER_ENQUEUETASK, IShellImageStore, /// <a href="https://msdn.microsoft.com/en-us/library/bb761848.aspx">IExtractImage</a>, /// <a href="https://msdn.microsoft.com/en-us/library/bb761846.aspx">IExtractImage::GetLocation</a>, /// <a href="https://msdn.microsoft.com/en-us/library/bb775201.aspx">IRunnableTask</a> static HRESULT CreateInstance(HWND hWndShellUIParentWindow, HWND hWndToNotify, CAtlList<LPSHCTLSBACKGROUNDTASKINFO>* pTasksToEnqueue, LPCRITICAL_SECTION pTasksToEnqueueCritSection, CAtlList<LPSHLVWBACKGROUNDTHUMBNAILINFO>* pBackgroundThumbnailsQueue, LPCRITICAL_SECTION pBackgroundThumbnailsCritSection, __in PCIDLIST_ABSOLUTE pIDL, LONG itemID, BOOL itemIsFile, __in LPEXTRACTIMAGE pExtractImage, BOOL useThumbnailDiskCache, __in_opt LPSHELLIMAGESTORE pThumbnailDiskCache, SIZE imageSize, __in LPWSTR pThumbnailPath, __in LPWSTR pItemPath, FILETIME dateStamp, DWORD flags, DWORD priority, BOOL asynchronousExtraction, __deref_out IRunnableTask** ppTask); #endif /// \brief <em>Does the real work</em> /// /// \return An \c HRESULT error code. /// /// \sa RunnableTask::DoRun STDMETHODIMP DoRun(void); protected: /// \brief <em>Holds the object's properties</em> struct Properties { /// \brief <em>Specifies the window that is used as parent window for any UI that the shell may display</em> HWND hWndShellUIParentWindow; /// \brief <em>Specifies the window that the result is posted to</em> /// /// Specifies the window to which to send the extraction task. This window must handle the /// \c WM_TRIGGER_ENQUEUETASK message. /// /// \sa WM_TRIGGER_ENQUEUETASK HWND hWndToNotify; /// \brief <em>Holds the fully qualified pIDL of the item for which to extract the thumbnail</em> PIDLIST_ABSOLUTE pIDL; /// \brief <em>Specifies the item for which to extract the thumbnail</em> LONG itemID; /// \brief <em>If \c TRUE, the item, for which to extract the thumbnail, is a file</em> BOOL itemIsFile; /// \brief <em>The \c IExtractImage object used to retrieve the thumbnail</em> /// /// \sa <a href="https://msdn.microsoft.com/en-us/library/bb761848.aspx">IExtractImage</a> LPEXTRACTIMAGE pExtractImage; /// \brief <em>If \c TRUE, the thumbnail disk cache is used; otherwise not</em> BOOL useThumbnailDiskCache; /// \brief <em>The \c IShellImageStore object used to access the disk cache</em> /// /// \sa IShellImageStore LPSHELLIMAGESTORE pThumbnailDiskCache; /// \brief <em>Specifies the size in pixels of the thumbnail to extract</em> SIZE imageSize; /// \brief <em>Holds the path to the thumbnail to extract</em> WCHAR pThumbnailPath[1024]; /// \brief <em>Holds the path to the item for which to retrieve the thumbnail</em> WCHAR pItemPath[1024]; /// \brief <em>Holds the thumbnail's date stamp</em> /// /// \sa <a href="https://msdn.microsoft.com/en-us/library/ms724284.aspx">FILETIME</a> FILETIME dateStamp; /// \brief <em>The \c IEIFLAG_* flags to use for extraction</em> /// /// \sa <a href="https://msdn.microsoft.com/en-us/library/bb761846.aspx">IExtractImage::GetLocation</a> DWORD flags; /// \brief <em>The priority to use for new background tasks</em> DWORD priority; /// \brief <em>If \c TRUE, the extraction should be done in a background task</em> BOOL asynchronousExtraction; #ifdef USE_STL /// \brief <em>Buffers the created task until it is sent to the scheduler</em> /// /// \sa pTasksToEnqueueCritSection, pTaskToEnqueue, SHCTLSBACKGROUNDTASKINFO std::queue<LPSHCTLSBACKGROUNDTASKINFO>* pTasksToEnqueue; /// \brief <em>Buffers the thumbnail information retrieved by the background thread until the image list is updated</em> /// /// \sa pBackgroundThumbnailsCritSection, SHLVWBACKGROUNDTHUMBNAILINFO std::queue<LPSHLVWBACKGROUNDTHUMBNAILINFO>* pBackgroundThumbnailsQueue; #else /// \brief <em>Buffers the created task until it is sent to the scheduler</em> /// /// \sa pTasksToEnqueueCritSection, pTaskToEnqueue, SHCTLSBACKGROUNDTASKINFO CAtlList<LPSHCTLSBACKGROUNDTASKINFO>* pTasksToEnqueue; /// \brief <em>Buffers the thumbnail information retrieved by the background thread until the image list is updated</em> /// /// \sa pBackgroundThumbnailsCritSection, SHLVWBACKGROUNDTHUMBNAILINFO CAtlList<LPSHLVWBACKGROUNDTHUMBNAILINFO>* pBackgroundThumbnailsQueue; #endif /// \brief <em>Holds the created task until it is inserted into the \c pTasksToEnqueue queue</em> /// /// \sa pTasksToEnqueue, SHCTLSBACKGROUNDTASKINFO LPSHCTLSBACKGROUNDTASKINFO pTaskToEnqueue; /// \brief <em>The critical section used to synchronize access to \c pTasksToEnqueue</em> /// /// \sa pTasksToEnqueue LPCRITICAL_SECTION pTasksToEnqueueCritSection; /// \brief <em>The critical section used to synchronize access to \c pBackgroundThumbnailsQueue</em> /// /// \sa pBackgroundThumbnailsQueue LPCRITICAL_SECTION pBackgroundThumbnailsCritSection; } properties; };
65.434483
661
0.733347
[ "object" ]
302cdf860f9ccfa45b35e2e5127eac849ddc6e53
8,257
h
C
cegui/include/CEGUI/NamedElement.h
bolry/cegui
58b776a157409cb13092b77d68ab2618cf5c6e05
[ "MIT" ]
1
2021-04-28T03:29:17.000Z
2021-04-28T03:29:17.000Z
cegui/include/CEGUI/NamedElement.h
bolry/cegui
58b776a157409cb13092b77d68ab2618cf5c6e05
[ "MIT" ]
null
null
null
cegui/include/CEGUI/NamedElement.h
bolry/cegui
58b776a157409cb13092b77d68ab2618cf5c6e05
[ "MIT" ]
1
2020-07-21T00:03:01.000Z
2020-07-21T00:03:01.000Z
/*********************************************************************** created: 30/10/2011 author: Martin Preisler purpose: Adds naming and name path traversal to Element *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team * * 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 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 _CEGUINamedElement_h_ #define _CEGUINamedElement_h_ #include "CEGUI/Element.h" #if defined(_MSC_VER) # pragma warning(push) # pragma warning(disable : 4251) #endif // Start of CEGUI namespace section namespace CEGUI { /*! \brief EventArgs based class that is used for objects passed to handlers triggered for events concerning some NamedElement object. */ class CEGUIEXPORT NamedElementEventArgs : public EventArgs { public: NamedElementEventArgs(NamedElement* element): element(element) {} //! pointer to an Element object of relevance to the event. NamedElement* element; }; /*! \brief Adds name to the Element class, including name path traversal \par Name path A name path is a string that describes a path down the element hierarchy using names and the forward slash '/' as a separator. For example, if this element has a child attached to it named "Panel" which has its own children attached named "Okay" and "Cancel", you can check for the element "Okay" from this element by using the name path "Panel/Okay". To check for "Panel", you would simply pass the name "Panel". \see Element */ class CEGUIEXPORT NamedElement : public Element { public: //! Namespace for global events static const String EventNamespace; // generated internally by NamedElement /** Event fired when the Element name has changed. * Handlers are passed a const NamedElementEventArgs reference with * NamedElementEventArgs::element set to the Element whose name was changed. */ static const String EventNameChanged; /*! \brief Constructor \param name The initial name this element will have */ NamedElement(const String& name = ""); /*! \brief Destructor */ virtual ~NamedElement(); /*! \brief Renames the element. \param name String object holding the new name for the element. \exception AlreadyExistsException thrown if an element named \a name already exists in the parent of this element. */ virtual void setName(const String& name); /*! \brief Return a String object holding the name of this Element. */ inline const String& getName() const { return d_name; } /** \brief Return a String object that describes the name path for this Element. */ String getNamePath() const; using Element::isChild; /*! \brief Checks whether given name path references a NamedElement that is attached to this Element. \param name_path String object holding the name path of the child element to test. \return - true if the element referenced by \a name_path is attached. - false if the element referenced by \a name_path is not attached. */ bool isChild(const String& name_path) const; /*! \brief returns whether at least one window with the given name is attached to this Window or any of it's children as a child. \note WARNING! This function can be very expensive and should only be used when you have no other option available. If you decide to use it anyway, make sure the window hierarchy from the entry point is small. \param name Name of the child to look for. \return - true if at least one child window was found with the name \a name - false if no child window was found with the name \a name. */ bool isChildRecursive(const String& name) const; using Element::isAncestor; /*! \brief Return true if the specified element name is a name of some ancestor of this Element \param name String object holding the name to check for. \return - true if an element named \a name is an ancestor (parent, or parent of parent, etc) of this element. - false if an element named \a name is in no way an ancestor of this element. */ bool isAncestor(const String& name) const; /*! \brief Return the attached child element that the given name path references. \param name_path String object holding the name path of the child element to return. \return the NamedElement object referenced by \a name_path. \exception UnknownObjectException thrown if \a name_path does not reference an Element attached to this Element. */ NamedElement* getChildElement(const String& name_path) const; /*! \brief Find the first child with the given name, recursively and breadth-first. \param name String object holding the name of the child element to find. \return Pointer to the (first) Element object attached to this Element that has the name \a name */ NamedElement* getChildElementRecursive(const String& name) const; using Element::removeChild; /*! \brief Remove the Element referenced by the given name path from this Element's child list. \param name_path String the name path that references the the Element to be removed. If the Element specified is not attached to this Window, UnknownObjectException is thrown */ void removeChild(const String& name_path); protected: //! \copydoc Element::addChild_impl void addChild_impl(Element* element) override; /*! \brief Retrieves a child at \a name_path or 0 if none such exists */ virtual NamedElement* getChildByNamePath_impl(const String& name_path) const; /*! \brief Finds a child by \a name or 0 if none such exists */ virtual NamedElement* getChildByNameRecursive_impl(const String& name) const; /*! \brief Add standard CEGUI::NamedElement properties. */ void addNamedElementProperties(); /*! \brief Handler called when the element's name changes. \param e NamedElementEventArgs object whose 'element' pointer field is set to the element that triggered the event. For this event the trigger element is always 'this'. */ virtual void onNameChanged(NamedElementEventArgs& e); //! The name of the element, unique in the parent of this element String d_name; private: /************************************************************************* May not copy or assign Element objects *************************************************************************/ NamedElement(const Element&) {} NamedElement& operator=(const NamedElement&) {return *this;} }; } // End of CEGUI namespace section #if defined(_MSC_VER) # pragma warning(pop) #endif #endif // end of guard _CEGUINamedElement_h_
31.880309
101
0.655565
[ "object" ]
302d40874cc29f3cfd97f844ee76393b7e44e1c6
5,021
h
C
Sources/Elastos/Frameworks/Droid/Base/Services/Server/inc/elastos/droid/server/wm/DimLayer.h
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Services/Server/inc/elastos/droid/server/wm/DimLayer.h
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Services/Server/inc/elastos/droid/server/wm/DimLayer.h
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos 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 __ELASTOS_DROID_SERVER_WM_DIMLAYER_H__ #define __ELASTOS_DROID_SERVER_WM_DIMLAYER_H__ #include "_Elastos.Droid.Server.h" #include <Elastos.CoreLibrary.IO.h> #include <elastos/core/Object.h> using Elastos::IO::IPrintWriter; using Elastos::Droid::Graphics::IRect; using Elastos::Droid::View::ISurfaceControl; namespace Elastos { namespace Droid { namespace Server { namespace Wm { class CWindowManagerService; class DisplayContent; class TaskStack; class DimLayer : public Object { public: DimLayer( /* [in] */ CWindowManagerService* service, /* [in] */ TaskStack* taskStack, /* [in] */ DisplayContent* displayContent); /** Return true if dim layer is showing */ CARAPI_(Boolean) IsDimming(); /** Return true if in a transition period */ CARAPI_(Boolean) IsAnimating(); CARAPI_(Float) GetTargetAlpha(); CARAPI_(void) SetLayer( /* [in] */ Int32 layer); CARAPI_(Int32) GetLayer(); /** * @param layer The new layer value. * @param inTransaction Whether the call is made within a surface transaction. */ CARAPI_(void) AdjustSurface( /* [in] */ Int32 layer, /* [in] */ Boolean inTransaction); // Assumes that surface transactions are currently closed. CARAPI_(void) SetBounds( /* [in] */ IRect* bounds); /** Jump to the end of the animation. * NOTE: Must be called with Surface transaction open. */ CARAPI_(void) Show(); /** * Begin an animation to a new dim value. * NOTE: Must be called with Surface transaction open. * * @param layer The layer to set the surface to. * @param alpha The dim value to end at. * @param duration How long to take to get there in milliseconds. */ CARAPI_(void) Show( /* [in] */ Int32 layer, /* [in] */ Float alpha, /* [in] */ Int64 duration); /** Immediate hide. * NOTE: Must be called with Surface transaction open. */ CARAPI_(void) Hide(); /** * Gradually fade to transparent. * NOTE: Must be called with Surface transaction open. * * @param duration Time to fade in milliseconds. */ CARAPI_(void) Hide( /* [in] */ Int64 duration); /** * Advance the dimming per the last #show(int, float, long) call. * NOTE: Must be called with Surface transaction open. * * @return True if animation is still required after this step. */ CARAPI_(Boolean) StepAnimation(); /** Cleanup */ CARAPI_(void) DestroySurface(); CARAPI_(void) PrintTo( /* [in] */ const String& prefix, /* [in] */ IPrintWriter* pw); private: CARAPI_(void) SetAlpha( /* [in] */ Float alpha); /** * @param duration The time to test. * @return True if the duration would lead to an earlier end to the current animation. */ CARAPI_(Boolean) DurationEndsEarlier( /* [in] */ Int64 duration); public: /** Reference to the owner of this object. */ AutoPtr<DisplayContent> mDisplayContent; /** Actual surface that dims */ AutoPtr<ISurfaceControl> mDimSurface; /** Last value passed to mDimSurface.setAlpha() */ Float mAlpha; /** Last value passed to mDimSurface.setLayer() */ Int32 mLayer; /** Next values to pass to mDimSurface.setPosition() and mDimSurface.setSize() */ AutoPtr<IRect> mBounds; /** Last values passed to mDimSurface.setPosition() and mDimSurface.setSize() */ AutoPtr<IRect> mLastBounds; /** Value of mAlpha when beginning transition to mTargetAlpha */ Float mStartAlpha; /** Final value of mAlpha following transition */ Float mTargetAlpha; /** Time in units of SystemClock.uptimeMillis() at which the current transition started */ Int64 mStartTime; /** Time in milliseconds to take to transition from mStartAlpha to mTargetAlpha */ Int64 mDuration; /** Owning stack */ TaskStack* mStack; private: static const String TAG; static const Boolean DEBUG = FALSE; /** True after mDimSurface.show() has been called, false after mDimSurface.hide(). */ Boolean mShowing; }; } // Wm } // Server } // Droid } // Elastos #endif //__ELASTOS_DROID_SERVER_WM_DIMLAYER_H__
28.856322
94
0.639315
[ "object" ]
302ebf4e057629115ffdf8e951d89642da274401
18,858
h
C
hardware/chip/smarth_rv64/include/drv_usart.h
wstong999/AliOS-Things
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
[ "Apache-2.0" ]
null
null
null
hardware/chip/smarth_rv64/include/drv_usart.h
wstong999/AliOS-Things
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
[ "Apache-2.0" ]
null
null
null
hardware/chip/smarth_rv64/include/drv_usart.h
wstong999/AliOS-Things
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2017-2019 Alibaba Group Holding Limited * * License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /****************************************************************************** * @file drv_usart.h * @brief header file for usart driver * @version V1.0 * @date 02. June 2017 * @model usart ******************************************************************************/ #ifndef _CSI_USART_H_ #define _CSI_USART_H_ #include <drv_common.h> #ifdef __cplusplus extern "C" { #endif /// definition for usart handle. typedef void *usart_handle_t; /****** USART specific error codes *****/ typedef enum { USART_ERROR_MODE = (DRV_ERROR_SPECIFIC + 1), ///< Specified Mode not supported USART_ERROR_BAUDRATE, ///< Specified baudrate not supported USART_ERROR_DATA_BITS, ///< Specified number of Data bits not supported USART_ERROR_PARITY, ///< Specified Parity not supported USART_ERROR_STOP_BITS, ///< Specified number of Stop bits not supported USART_ERROR_FLOW_CONTROL, ///< Specified Flow Control not supported USART_ERROR_CPOL, ///< Specified Clock Polarity not supported USART_ERROR_CPHA ///< Specified Clock Phase not supported } usart_error_e; /*----- USART Control Codes: Mode -----*/ typedef enum { USART_MODE_ASYNCHRONOUS = 0, ///< USART (Asynchronous) USART_MODE_SYNCHRONOUS_MASTER, ///< Synchronous Master USART_MODE_SYNCHRONOUS_SLAVE, ///< Synchronous Slave (external clock signal) USART_MODE_SINGLE_WIRE, ///< USART Single-wire (half-duplex) USART_MODE_SINGLE_IRDA, ///< UART IrDA USART_MODE_SINGLE_SMART_CARD, ///< UART Smart Card } usart_mode_e; /*----- USART Control Codes: Mode Parameters: Data Bits -----*/ typedef enum { USART_DATA_BITS_5 = 0, ///< 5 Data bits USART_DATA_BITS_6, ///< 6 Data bit USART_DATA_BITS_7, ///< 7 Data bits USART_DATA_BITS_8, ///< 8 Data bits (default) USART_DATA_BITS_9 ///< 9 Data bits } usart_data_bits_e; /*----- USART Control Codes: Mode Parameters: Parity -----*/ typedef enum { USART_PARITY_NONE = 0, ///< No Parity (default) USART_PARITY_EVEN, ///< Even Parity USART_PARITY_ODD, ///< Odd Parity USART_PARITY_1, ///< Parity forced to 1 USART_PARITY_0 ///< Parity forced to 0 } usart_parity_e; /*----- USART Control Codes: Mode Parameters: Stop Bits -----*/ typedef enum { USART_STOP_BITS_1 = 0, ///< 1 Stop bit (default) USART_STOP_BITS_2, ///< 2 Stop bits USART_STOP_BITS_1_5, ///< 1.5 Stop bits USART_STOP_BITS_0_5 ///< 0.5 Stop bits } usart_stop_bits_e; /*----- USART Control Codes: Mode Parameters: Clock Polarity (Synchronous mode) -----*/ typedef enum { USART_CPOL0 = 0, ///< CPOL = 0 (default). data are captured on rising edge (low->high transition) USART_CPOL1 ///< CPOL = 1. data are captured on falling edge (high->lowh transition) } usart_cpol_e; /*----- USART Control Codes: Mode Parameters: Clock Phase (Synchronous mode) -----*/ typedef enum { USART_CPHA0 = 0, ///< CPHA = 0 (default). sample on first (leading) edge USART_CPHA1 ///< CPHA = 1. sample on second (trailing) edge } usart_cpha_e; /*----- USART Control Codes: flush data type-----*/ typedef enum { USART_FLUSH_WRITE, USART_FLUSH_READ } usart_flush_type_e; /*----- USART Control Codes: flow control type-----*/ typedef enum { USART_FLOWCTRL_NONE, USART_FLOWCTRL_CTS, USART_FLOWCTRL_RTS, USART_FLOWCTRL_CTS_RTS } usart_flowctrl_type_e; /*----- USART Modem Control -----*/ typedef enum { USART_RTS_CLEAR, ///< Deactivate RTS USART_RTS_SET, ///< Activate RTS USART_DTR_CLEAR, ///< Deactivate DTR USART_DTR_SET ///< Activate DTR } usart_modem_ctrl_e; /*----- USART Modem Status -----*/ typedef struct { uint32_t cts : 1; ///< CTS state: 1=Active, 0=Inactive uint32_t dsr : 1; ///< DSR state: 1=Active, 0=Inactive uint32_t dcd : 1; ///< DCD state: 1=Active, 0=Inactive uint32_t ri : 1; ///< RI state: 1=Active, 0=Inactive } usart_modem_stat_t; /*----- USART Control Codes: on-off intrrupte type-----*/ typedef enum { USART_INTR_WRITE, USART_INTR_READ } usart_intr_type_e; /** \brief USART Status */ typedef struct { uint32_t tx_busy : 1; ///< Transmitter busy flag uint32_t rx_busy : 1; ///< Receiver busy flag uint32_t tx_underflow : 1; ///< Transmit data underflow detected (cleared on start of next send operation)(Synchronous Slave) uint32_t rx_overflow : 1; ///< Receive data overflow detected (cleared on start of next receive operation) uint32_t rx_break : 1; ///< Break detected on receive (cleared on start of next receive operation) uint32_t rx_framing_error : 1; ///< Framing error detected on receive (cleared on start of next receive operation) uint32_t rx_parity_error : 1; ///< Parity error detected on receive (cleared on start of next receive operation) uint32_t tx_enable : 1; ///< Transmitter enable flag uint32_t rx_enable : 1; ///< Receiver enbale flag } usart_status_t; /****** USART Event *****/ typedef enum { USART_EVENT_SEND_COMPLETE = 0, ///< Send completed; however USART may still transmit data USART_EVENT_RECEIVE_COMPLETE = 1, ///< Receive completed USART_EVENT_TRANSFER_COMPLETE = 2, ///< Transfer completed USART_EVENT_TX_COMPLETE = 3, ///< Transmit completed (optional) USART_EVENT_TX_UNDERFLOW = 4, ///< Transmit data not available (Synchronous Slave) USART_EVENT_RX_OVERFLOW = 5, ///< Receive data overflow USART_EVENT_RX_TIMEOUT = 6, ///< Receive character timeout (optional) USART_EVENT_RX_BREAK = 7, ///< Break detected on receive USART_EVENT_RX_FRAMING_ERROR = 8, ///< Framing error detected on receive USART_EVENT_RX_PARITY_ERROR = 9, ///< Parity error detected on receive USART_EVENT_CTS = 10, ///< CTS state changed (optional) USART_EVENT_DSR = 11, ///< DSR state changed (optional) USART_EVENT_DCD = 12, ///< DCD state changed (optional) USART_EVENT_RI = 13, ///< RI state changed (optional) USART_EVENT_RECEIVED = 14, ///< Data Received, only in usart fifo, call receive()/transfer() get the data } usart_event_e; typedef void (*usart_event_cb_t)(int32_t idx, usart_event_e event); ///< Pointer to \ref usart_event_cb_t : USART Event call back. /** \brief USART Driver Capabilities. */ typedef struct { uint32_t asynchronous : 1; ///< supports UART (Asynchronous) mode uint32_t synchronous_master : 1; ///< supports Synchronous Master mode uint32_t synchronous_slave : 1; ///< supports Synchronous Slave mode uint32_t single_wire : 1; ///< supports UART Single-wire mode uint32_t irda : 1; ///< supports UART IrDA mode uint32_t smart_card : 1; ///< supports UART Smart Card mode uint32_t smart_card_clock : 1; ///< Smart Card Clock generator available uint32_t flow_control_rts : 1; ///< RTS Flow Control available uint32_t flow_control_cts : 1; ///< CTS Flow Control available uint32_t event_tx_complete : 1; ///< Transmit completed event: \ref USART_EVENT_TX_COMPLETE uint32_t event_rx_timeout : 1; ///< Signal receive character timeout event: \ref USART_EVENT_RX_TIMEOUT uint32_t rts : 1; ///< RTS Line: 0=not available, 1=available uint32_t cts : 1; ///< CTS Line: 0=not available, 1=available uint32_t dtr : 1; ///< DTR Line: 0=not available, 1=available uint32_t dsr : 1; ///< DSR Line: 0=not available, 1=available uint32_t dcd : 1; ///< DCD Line: 0=not available, 1=available uint32_t ri : 1; ///< RI Line: 0=not available, 1=available uint32_t event_cts : 1; ///< Signal CTS change event: \ref USART_EVENT_CTS uint32_t event_dsr : 1; ///< Signal DSR change event: \ref USART_EVENT_DSR uint32_t event_dcd : 1; ///< Signal DCD change event: \ref USART_EVENT_DCD uint32_t event_ri : 1; ///< Signal RI change event: \ref USART_EVENT_RI } usart_capabilities_t; /** \brief Initialize USART Interface. 1. Initializes the resources needed for the USART interface 2.registers event callback function \param[in] idx usart index \param[in] cb_event event call back function \ref usart_event_cb_t \return return usart handle if success */ usart_handle_t csi_usart_initialize(int32_t idx, usart_event_cb_t cb_event); /** \brief De-initialize USART Interface. stops operation and releases the software resources used by the interface \param[in] handle usart handle to operate. \return error code */ int32_t csi_usart_uninitialize(usart_handle_t handle); /** \brief Get driver capabilities. \param[in] idx usart index \return \ref usart_capabilities_t */ usart_capabilities_t csi_usart_get_capabilities(int32_t idx); /** \brief config usart mode. \param[in] handle usart handle to operate. \param[in] baud baud rate. \param[in] mode \ref usart_mode_e . \param[in] parity \ref usart_parity_e . \param[in] stopbits \ref usart_stop_bits_e . \param[in] bits \ref usart_data_bits_e . \return error code */ int32_t csi_usart_config(usart_handle_t handle, uint32_t baud, usart_mode_e mode, usart_parity_e parity, usart_stop_bits_e stopbits, usart_data_bits_e bits); /** \brief Start sending data to USART transmitter,(received data is ignored). This function is non-blocking,\ref usart_event_e is signaled when operation completes or error happens. \ref csi_usart_get_status can get operation status. \param[in] handle usart handle to operate. \param[in] data Pointer to buffer with data to send to USART transmitter. data_type is : uint8_t for 5..8 data bits, uint16_t for 9 data bits \param[in] num Number of data items to send \return error code */ int32_t csi_usart_send(usart_handle_t handle, const void *data, uint32_t num); /** \brief Abort Send data to USART transmitter \param[in] handle usart handle to operate. \return error code */ int32_t csi_usart_abort_send(usart_handle_t handle); /** \brief Start receiving data from USART receiver. \n This function is non-blocking,\ref usart_event_e is signaled when operation completes or error happens. \ref csi_usart_get_status can get operation status. \param[in] handle usart handle to operate. \param[out] data Pointer to buffer for data to receive from USART receiver.data_type is : uint8_t for 5..8 data bits, uint16_t for 9 data bits \param[in] num Number of data items to receive \return error code */ int32_t csi_usart_receive(usart_handle_t handle, void *data, uint32_t num); /** \brief query data from UART receiver FIFO. \param[in] handle usart handle to operate. \param[out] data Pointer to buffer for data to receive from UART receiver \param[in] num Number of data items to receive \return fifo data num to receive */ int32_t csi_usart_receive_query(usart_handle_t handle, void *data, uint32_t num); /** \brief Abort Receive data from USART receiver \param[in] handle usart handle to operate. \return error code */ int32_t csi_usart_abort_receive(usart_handle_t handle); /** \brief Start synchronously sends data to the USART transmitter and receives data from the USART receiver. used in synchronous mode This function is non-blocking,\ref usart_event_e is signaled when operation completes or error happens. \ref csi_usart_get_status can get operation status. \param[in] handle usart handle to operate. \param[in] data_out Pointer to buffer with data to send to USART transmitter.data_type is : uint8_t for 5..8 data bits, uint16_t for 9 data bits \param[out] data_in Pointer to buffer for data to receive from USART receiver.data_type is : uint8_t for 5..8 data bits, uint16_t for 9 data bits \param[in] num Number of data items to transfer \return error code */ int32_t csi_usart_transfer(usart_handle_t handle, const void *data_out, void *data_in, uint32_t num); /** \brief abort sending/receiving data to/from USART transmitter/receiver. \param[in] handle usart handle to operate. \return error code */ int32_t csi_usart_abort_transfer(usart_handle_t handle); /** \brief Get USART status. \param[in] handle usart handle to operate. \return USART status \ref usart_status_t */ usart_status_t csi_usart_get_status(usart_handle_t handle); /** \brief flush receive/send data. \param[in] handle usart handle to operate. \param[in] type \ref usart_flush_type_e . \return error code */ int32_t csi_usart_flush(usart_handle_t handle, usart_flush_type_e type); /** \brief set interrupt mode. \param[in] handle usart handle to operate. \param[in] type \ref usart_intr_type_e. \param[in] flag 0-OFF, 1-ON. \return error code */ int32_t csi_usart_set_interrupt(usart_handle_t handle, usart_intr_type_e type, int32_t flag); /** \brief set the baud rate of usart. \param[in] baud usart base to operate. \param[in] baudrate baud rate \return error code */ int32_t csi_usart_config_baudrate(usart_handle_t handle, uint32_t baud); /** \brief config usart mode. \param[in] handle usart handle to operate. \param[in] mode \ref usart_mode_e \return error code */ int32_t csi_usart_config_mode(usart_handle_t handle, usart_mode_e mode); /** \brief config usart parity. \param[in] handle usart handle to operate. \param[in] parity \ref usart_parity_e \return error code */ int32_t csi_usart_config_parity(usart_handle_t handle, usart_parity_e parity); /** \brief config usart stop bit number. \param[in] handle usart handle to operate. \param[in] stopbits \ref usart_stop_bits_e \return error code */ int32_t csi_usart_config_stopbits(usart_handle_t handle, usart_stop_bits_e stopbit); /** \brief config usart data length. \param[in] handle usart handle to operate. \param[in] databits \ref usart_data_bits_e \return error code */ int32_t csi_usart_config_databits(usart_handle_t handle, usart_data_bits_e databits); /** \brief get character in query mode. \param[in] handle usart handle to operate. \param[out] ch the pointer to the received character. \return error code */ int32_t csi_usart_getchar(usart_handle_t handle, uint8_t *ch); /** \brief transmit character in query mode. \param[in] handle usart handle to operate. \param[in] ch the input character \return error code */ int32_t csi_usart_putchar(usart_handle_t handle, uint8_t ch); /** \brief Get usart send data count. \param[in] handle usart handle to operate. \return number of currently transmitted data bytes */ uint32_t csi_usart_get_tx_count(usart_handle_t handle); /** \brief Get usart received data count. \param[in] handle usart handle to operate. \return number of currently received data bytes */ uint32_t csi_usart_get_rx_count(usart_handle_t handle); /** \brief control usart power. \param[in] handle usart handle to operate. \param[in] state power state.\ref csi_power_stat_e. \return error code */ int32_t csi_usart_power_control(usart_handle_t handle, csi_power_stat_e state); /** \brief config usart flow control type. \param[in] handle usart handle to operate. \param[in] flowctrl_type flow control type.\ref usart_flowctrl_type_e. \return error code */ int32_t csi_usart_config_flowctrl(usart_handle_t handle, usart_flowctrl_type_e flowctrl_type); /** \brief config usart clock Polarity and Phase. \param[in] handle usart handle to operate. \param[in] cpol Clock Polarity.\ref usart_cpol_e. \param[in] cpha Clock Phase.\ref usart_cpha_e. \return error code */ int32_t csi_usart_config_clock(usart_handle_t handle, usart_cpol_e cpol, usart_cpha_e cpha); /** \brief control the transmitter. \param[in] handle usart handle to operate. \param[in] enable 1 - enable the transmitter. 0 - disable the transmitter \return error code */ int32_t csi_usart_control_tx(usart_handle_t handle, uint32_t enable); /** \brief control the receiver. \param[in] handle usart handle to operate. \param[in] enable 1 - enable the receiver. 0 - disable the receiver \return error code */ int32_t csi_usart_control_rx(usart_handle_t handle, uint32_t enable); /** \brief control the break. \param[in] handle usart handle to operate. \param[in] enable 1- Enable continuous Break transmission,0 - disable continuous Break transmission \return error code */ int32_t csi_usart_control_break(usart_handle_t handle, uint32_t enable); #ifdef __cplusplus } #endif #endif /* _CSI_USART_H_ */
41.813747
150
0.646357
[ "model" ]
3031e5707d916ec6c7c5bdf11e7622459825c45b
3,987
c
C
insts/std/convolve/fft.c
jwmatthys/RTcmix
c9ba0c5bee2cd5e091c81333cf819d267008635b
[ "Apache-2.0" ]
40
2015-01-14T20:52:42.000Z
2022-03-09T00:50:45.000Z
insts/std/convolve/fft.c
jwmatthys/RTcmix
c9ba0c5bee2cd5e091c81333cf819d267008635b
[ "Apache-2.0" ]
20
2015-01-26T19:02:59.000Z
2022-01-30T18:00:39.000Z
insts/std/convolve/fft.c
jwmatthys/RTcmix
c9ba0c5bee2cd5e091c81333cf819d267008635b
[ "Apache-2.0" ]
14
2015-01-14T20:52:43.000Z
2021-09-24T02:24:32.000Z
#include "fft.h" /* float PI; */ float TWOPI; void cfft(float x[], int NC, int forward); void bitreverse(float x[], int N); /* * If forward is true, rfft replaces 2*N real data points in x with * N complex values representing the positive frequency half of their * Fourier spectrum, with x[1] replaced with the real part of the Nyquist * frequency value. If forward is false, rfft expects x to contain a * positive frequency spectrum arranged as before, and replaces it with * 2*N real values. N MUST be a power of 2. */ void rfft(float x[], int N, int forward) { float c1, c2, h1r, h1i, h2r, h2i, wr, wi, wpr, wpi, temp, theta; float xr, xi; int i, i1, i2, i3, i4, N2p1; static int first = 1; if (first) { /* PI = 4.*atan( 1. ) ; */ TWOPI = 8. * atan(1.); first = 0; } theta = PI / N; wr = 1.; wi = 0.; c1 = 0.5; if (forward) { c2 = -0.5; cfft(x, N, forward); xr = x[0]; xi = x[1]; } else { c2 = 0.5; theta = -theta; xr = x[1]; xi = 0.; x[1] = 0.; } wpr = -2. * pow(sin(0.5 * theta), 2.); wpi = sin(theta); N2p1 = (N << 1) + 1; for (i = 0; i <= N >> 1; i++) { i1 = i << 1; i2 = i1 + 1; i3 = N2p1 - i2; i4 = i3 + 1; if (i == 0) { h1r = c1 * (x[i1] + xr); h1i = c1 * (x[i2] - xi); h2r = -c2 * (x[i2] + xi); h2i = c2 * (x[i1] - xr); x[i1] = h1r + wr * h2r - wi * h2i; x[i2] = h1i + wr * h2i + wi * h2r; xr = h1r - wr * h2r + wi * h2i; xi = -h1i + wr * h2i + wi * h2r; } else { h1r = c1 * (x[i1] + x[i3]); h1i = c1 * (x[i2] - x[i4]); h2r = -c2 * (x[i2] + x[i4]); h2i = c2 * (x[i1] - x[i3]); x[i1] = h1r + wr * h2r - wi * h2i; x[i2] = h1i + wr * h2i + wi * h2r; x[i3] = h1r - wr * h2r + wi * h2i; x[i4] = -h1i + wr * h2i + wi * h2r; } wr = (temp = wr) * wpr - wi * wpi + wr; wi = wi * wpr + temp * wpi + wi; } if (forward) x[1] = xr; else cfft(x, N, forward); } /* * cfft replaces float array x containing NC complex values * (2*NC float values alternating real, imagininary, etc.) * by its Fourier transform if forward is true, or by its * inverse Fourier transform if forward is false, using a * recursive Fast Fourier transform method due to Danielson * and Lanczos. NC MUST be a power of 2. */ void cfft(float x[], int NC, int forward) { float wr, wi, wpr, wpi, theta, scale; int mmax, ND, m, i, j, delta; ND = NC << 1; bitreverse(x, ND); for (mmax = 2; mmax < ND; mmax = delta) { delta = mmax << 1; theta = TWOPI / (forward ? mmax : -mmax); wpr = -2. * pow(sin(0.5 * theta), 2.); wpi = sin(theta); wr = 1.; wi = 0.; for (m = 0; m < mmax; m += 2) { register float rtemp, itemp; for (i = m; i < ND; i += delta) { j = i + mmax; rtemp = wr * x[j] - wi * x[j + 1]; itemp = wr * x[j + 1] + wi * x[j]; x[j] = x[i] - rtemp; x[j + 1] = x[i + 1] - itemp; x[i] += rtemp; x[i + 1] += itemp; } wr = (rtemp = wr) * wpr - wi * wpi + wr; wi = wi * wpr + rtemp * wpi + wi; } } /* * scale output */ scale = forward ? 1. / ND : 2.; { register float *xi = x, *xe = x + ND; while (xi < xe) *xi++ *= scale; } } /* * bitreverse places float array x containing N/2 complex values * into bit-reversed order */ void bitreverse(float x[], int N) { float rtemp, itemp; int i, j, m; for (i = j = 0; i < N; i += 2, j += m) { if (j > i) { rtemp = x[j]; itemp = x[j + 1]; /* complex exchange */ x[j] = x[i]; x[j + 1] = x[i + 1]; x[i] = rtemp; x[i + 1] = itemp; } for (m = N >> 1; m >= 2 && j >= m; m >>= 1) j -= m; } }
26.058824
73
0.453474
[ "transform" ]
30332ccd19307911365fcd5e105c7057c8ba904a
10,109
h
C
xavier/simdutils.h
camaclean/bella
c80c012cda05bc15b69db7fd54424823f75b5a21
[ "BSD-3-Clause-LBNL" ]
null
null
null
xavier/simdutils.h
camaclean/bella
c80c012cda05bc15b69db7fd54424823f75b5a21
[ "BSD-3-Clause-LBNL" ]
null
null
null
xavier/simdutils.h
camaclean/bella
c80c012cda05bc15b69db7fd54424823f75b5a21
[ "BSD-3-Clause-LBNL" ]
null
null
null
//=========================================================================== // Title: Xavier: High-Performance X-Drop Adaptive Banded Pairwise Alignment // Author: G. Guidi, E. Younis // Date: 30 April 2019 //=========================================================================== #ifndef SIMD_UTILS_H #define SIMD_UTILS_H #include <cstdint> #include "score.h" #include "utils.h" //====================================================================================== // GLOBAL FUNCTION DECLARATION //====================================================================================== #ifndef __AVX2__ #define __AVX2__ #endif #ifdef __AVX2__ // Compile flag: -mavx2 #define VECTORWIDTH (32) #define LOGICALWIDTH (VECTORWIDTH - 1) #define vectorType __m256i #define addOp _mm256_adds_epi8 // saturated arithmetic #define subOp _mm256_subs_epi8 // saturated arithmetic #define maxOp _mm256_max_epi8 // max #define setOp _mm256_set1_epi8 // set1 operation #define blendvOp _mm256_blendv_epi8 // blending operation #define cmpeqOp _mm256_cmpeq_epi8 // compare equality operation #elif __SSE4_2__ // Compile flag: -msse4.2 #define VECTORWIDTH (8) #define LOGICALWIDTH (VECTORWIDTH - 1) #define vectorType __m128i #define addOp _mm_adds_epi16 // saturated arithmetic #define subOp _mm_subs_epi16 // saturated arithmetic #define maxOp _mm_max_epi16 // max #define setOp _mm_set1_epi16 // set1 operation #define blendvOp _mm_blendv_epi8 // blending operation #define cmpeqOp _mm_cmpeq_epi16 // compare equality operation #endif //====================================================================================== // GLOBAL VARIABLE DEFINITION //====================================================================================== #define NINF (std::numeric_limits<int8_t>::min()) #define goRIGHT (0) #define goDOWN (1) #define MIDDLE (LOGICALWIDTH / 2) #define CUTOFF (std::numeric_limits<int8_t>::max() - 25) #ifdef DEBUG #define myLog( var ) do { std::cerr << "LOG: " << __FILE__ << "(" << __LINE__ << ") " << #var << " = " << (var) << std::endl; } while(0) #else #define myLog( var ) #endif //====================================================================================== // SIMD UTILS //====================================================================================== typedef int8_t elementType; typedef union { vectorType simd; elementType elem[VECTORWIDTH]; } vectorUnionType; void printVectorC(vectorType a) { vectorUnionType tmp; tmp.simd = a; printf("{"); for (int i = 0; i < VECTORWIDTH-1; ++i) printf("%c,", tmp.elem[i]); printf("%c}\n", tmp.elem[VECTORWIDTH-1]); } void printVectorD(vectorType a) { vectorUnionType tmp; tmp.simd = a; printf("{"); for (int i = 0; i < VECTORWIDTH-1; ++i) printf("%d,", tmp.elem[i]); printf("%d}\n", tmp.elem[VECTORWIDTH-1]); } enum ExtDirectionL { XAVIER_EXTEND_NONE = 0, XAVIER_EXTEND_LEFT = 1, XAVIER_EXTEND_RIGHT = 2, XAVIER_EXTEND_BOTH = 3 }; #ifdef __AVX2__ inline vectorUnionType shiftLeft (const vectorType& _a) { // this work for avx2 vectorUnionType a; a.simd = _a; vectorUnionType b; // https://stackoverflow.com/questions/25248766/emulating-shifts-on-32-bytes-with-avx b.simd = _mm256_alignr_epi8(_mm256_permute2x128_si256(a.simd, a.simd, _MM_SHUFFLE(2, 0, 0, 1)), a.simd, 1); b.elem[VECTORWIDTH - 1] = NINF; return b; } inline vectorUnionType shiftRight (const vectorType& _a) { // this work for avx2 vectorUnionType a; a.simd = _a; vectorUnionType b; // https://stackoverflow.com/questions/25248766/emulating-shifts-on-32-bytes-with-avx b.simd = _mm256_alignr_epi8(a.simd, _mm256_permute2x128_si256(a.simd, a.simd, _MM_SHUFFLE(0, 0, 2, 0)), 16 - 1); b.elem[0] = NINF; return b; } #elif __SSE4_2__ inline vectorUnionType shiftLeft(const vectorType& _a) { // this work for avx2 vectorUnionType a; a.simd = _a; vectorUnionType b; // https://stackoverflow.com/questions/25248766/emulating-shifts-on-32-bytes-with-avx b.simd = _mm256_alignr_epi8(_mm256_permute2x128_si256(a.simd, a.simd, _MM_SHUFFLE(2, 0, 0, 1)), a.simd, 2); b.elem[VECTORWIDTH - 1] = NINF; return b; } inline vectorUnionType shiftRight(const vectorType& _a) { // this work for avx2 vectorUnionType a; a.simd = _a; vectorUnionType b; // https://stackoverflow.com/questions/25248766/emulating-shifts-on-32-bytes-with-avx b.simd = _mm256_alignr_epi8(a.simd, _mm256_permute2x128_si256(a.simd, a.simd, _MM_SHUFFLE(0, 0, 2, 0)), 16 - 2); b.elem[0] = NINF; return b; } #endif class XavierState { public: XavierState ( SeedX& _seed, std::string const& hseq, std::string const& vseq, ScoringSchemeX& scoringScheme, int64_t const &_scoreDropOff ) { seed = _seed; hlength = hseq.length() + 1; // + VECTORWIDTH; vlength = vseq.length() + 1; // + VECTORWIDTH; if (hlength < VECTORWIDTH || vlength < VECTORWIDTH) { setEndPositionH(seed, hlength); setEndPositionV(seed, vlength); // GG: main function takes care of this // return; } // Convert from string to int array // This is the entire sequences queryh = new int8_t[hlength + VECTORWIDTH]; queryv = new int8_t[vlength + VECTORWIDTH]; std::copy(hseq.begin(), hseq.begin() + hlength, queryh); std::copy(vseq.begin(), vseq.begin() + vlength, queryv); std::fill(queryh + hlength, queryh + hlength + VECTORWIDTH, NINF); std::fill(queryv + vlength, queryv + vlength + VECTORWIDTH, NINF); matchCost = scoreMatch(scoringScheme ); mismatchCost = scoreMismatch(scoringScheme); gapCost = scoreGap(scoringScheme ); vmatchCost = setOp (matchCost ); vmismatchCost = setOp (mismatchCost); vgapCost = setOp (gapCost ); vzeros = _mm256_setzero_si256(); hoffset = LOGICALWIDTH+1; voffset = LOGICALWIDTH+1; bestScore = 0; currScore = 0; scoreOffset = 0; scoreDropOff = _scoreDropOff; xDropCond = false; } ~XavierState() { delete [] queryh; delete [] queryv; } // i think this can be smaller than 64bit int64_t get_score_offset ( void ) { return scoreOffset; } int64_t get_best_score ( void ) { return bestScore; } int64_t get_curr_score ( void ) { return currScore; } int64_t get_score_dropoff ( void ) { return scoreDropOff; } void set_score_offset ( int64_t _scoreOffset ) { scoreOffset = _scoreOffset; } void set_best_score ( int64_t _bestScore ) { bestScore = _bestScore; } void set_curr_score ( int64_t _currScore ) { currScore = _currScore; } int8_t get_match_cost ( void ) { return matchCost; } int8_t get_mismatch_cost ( void ) { return mismatchCost; } int8_t get_gap_cost ( void ) { return gapCost; } vectorType get_vqueryh ( void ) { return vqueryh.simd; } vectorType get_vqueryv ( void ) { return vqueryv.simd; } vectorType get_antiDiag1 ( void ) { return antiDiag1.simd; } vectorType get_antiDiag2 ( void ) { return antiDiag2.simd; } vectorType get_antiDiag3 ( void ) { return antiDiag3.simd; } vectorType get_vmatchCost ( void ) { return vmatchCost; } vectorType get_vmismatchCost ( void ) { return vmismatchCost; } vectorType get_vgapCost ( void ) { return vgapCost; } vectorType get_vzeros ( void ) { return vzeros; } void update_vqueryh ( uint8_t idx, int8_t value ) { vqueryh.elem[idx] = value; } void update_vqueryv ( uint8_t idx, int8_t value ) { vqueryv.elem[idx] = value; } void update_antiDiag1 ( uint8_t idx, int8_t value ) { antiDiag1.elem[idx] = value; } void update_antiDiag2 ( uint8_t idx, int8_t value ) { antiDiag2.elem[idx] = value; } void update_antiDiag3 ( uint8_t idx, int8_t value ) { antiDiag3.elem[idx] = value; } void broadcast_antiDiag1 ( int8_t value ) { antiDiag1.simd = setOp( value ); } void broadcast_antiDiag2 ( int8_t value ) { antiDiag2.simd = setOp( value ); } void broadcast_antiDiag3 ( int8_t value ) { antiDiag3.simd = setOp( value ); } void set_antiDiag1 ( vectorType vector ) { antiDiag1.simd = vector; } void set_antiDiag2 ( vectorType vector ) { antiDiag2.simd = vector; } void set_antiDiag3 ( vectorType vector ) { antiDiag3.simd = vector; } void moveRight (void) { // (a) shift to the left on query horizontal vqueryh = shiftLeft( vqueryh.simd ); vqueryh.elem[LOGICALWIDTH - 1] = queryh[hoffset++]; // (b) shift left on updated vector 1 // this places the right-aligned vector 2 as a left-aligned vector 1 antiDiag1.simd = antiDiag2.simd; antiDiag1 = shiftLeft(antiDiag1.simd); antiDiag2.simd = antiDiag3.simd; } void moveDown (void) { // (a) shift to the right on query vertical vqueryv = shiftRight(vqueryv.simd); // ==50054==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60600062b0e0 at pc // 0x0001019b50f1 bp 0x70000678ba30 sp 0x70000678ba28 READ of size 1 at 0x60600062b0e0 thread T6 vqueryv.elem[0] = queryv[voffset++]; // (b) shift to the right on updated vector 2 // this places the left-aligned vector 3 as a right-aligned vector 2 antiDiag1.simd = antiDiag2.simd; antiDiag2.simd = antiDiag3.simd; antiDiag2 = shiftRight( antiDiag2.simd ); } // Seed position (define starting position and need to be updated when exiting) SeedX seed; // Sequence Lengths unsigned int hlength; unsigned int vlength; // Sequences as ints int8_t* queryh; int8_t* queryv; // Sequence pointers int hoffset; int voffset; // Constant Scoring Values int8_t matchCost; int8_t mismatchCost; int8_t gapCost; // Constant Scoring Vectors vectorType vmatchCost; vectorType vmismatchCost; vectorType vgapCost; vectorType vzeros; // Computation Vectors vectorUnionType antiDiag1; vectorUnionType antiDiag2; vectorUnionType antiDiag3; vectorUnionType vqueryh; vectorUnionType vqueryv; // X-Drop Variables int64_t bestScore; int64_t currScore; int64_t scoreOffset; int64_t scoreDropOff; bool xDropCond; }; void operator+=(XavierState& state1, const XavierState& state2) { state1.bestScore = state1.bestScore + state2.bestScore; state1.currScore = state1.currScore + state2.currScore; } #endif
29.732353
137
0.659412
[ "vector" ]
3036694050bf61a55312d9ce19735b71a84669f3
54,555
c
C
src/client/rspamc.c
CAPSLOCK2000/rspamd
c10763c03c302aff28a2e0d1ce1108b0ba49593a
[ "Apache-2.0" ]
null
null
null
src/client/rspamc.c
CAPSLOCK2000/rspamd
c10763c03c302aff28a2e0d1ce1108b0ba49593a
[ "Apache-2.0" ]
null
null
null
src/client/rspamc.c
CAPSLOCK2000/rspamd
c10763c03c302aff28a2e0d1ce1108b0ba49593a
[ "Apache-2.0" ]
null
null
null
/*- * Copyright 2016 Vsevolod Stakhov * * 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 "config.h" #include "libutil/util.h" #include "libutil/http_connection.h" #include "libutil/http_private.h" #include "rspamdclient.h" #include "utlist.h" #include "unix-std.h" #ifdef HAVE_SYS_WAIT_H #include <sys/wait.h> #endif #define DEFAULT_PORT 11333 #define DEFAULT_CONTROL_PORT 11334 static gchar *connect_str = "localhost"; static gchar *password = NULL; static gchar *ip = NULL; static gchar *from = NULL; static gchar *deliver_to = NULL; static gchar **rcpts = NULL; static gchar *user = NULL; static gchar *helo = NULL; static gchar *hostname = NULL; static gchar *classifier = NULL; static gchar *local_addr = NULL; static gchar *execute = NULL; static gchar *sort = NULL; static gchar **http_headers = NULL; static gchar **exclude_patterns = NULL; static gint weight = 0; static gint flag = 0; static gchar *fuzzy_symbol = NULL; static gchar *dictionary = NULL; static gint max_requests = 8; static gdouble timeout = 10.0; static gboolean pass_all; static gboolean tty = FALSE; static gboolean verbose = FALSE; static gboolean print_commands = FALSE; static gboolean json = FALSE; static gboolean compact = FALSE; static gboolean headers = FALSE; static gboolean raw = FALSE; static gboolean extended_urls = FALSE; static gboolean mime_output = FALSE; static gboolean empty_input = FALSE; static gboolean compressed = FALSE; static gboolean profile = FALSE; static gboolean skip_images = FALSE; static gboolean skip_attachments = FALSE; static gchar *key = NULL; static gchar *user_agent = "rspamc"; static GList *children; static GPatternSpec **exclude_compiled = NULL; static struct rspamd_http_context *http_ctx; static gint retcode = EXIT_SUCCESS; #define ADD_CLIENT_HEADER(o, n, v) do { \ struct rspamd_http_client_header *nh; \ nh = g_malloc (sizeof (*nh)); \ nh->name = g_strdup (n); \ nh->value = g_strdup (v); \ g_queue_push_tail ((o), nh); \ } while (0) #define ADD_CLIENT_FLAG(str, n) do { \ g_string_append ((str), n ","); \ } while (0) static gboolean rspamc_password_callback (const gchar *option_name, const gchar *value, gpointer data, GError **error); static GOptionEntry entries[] = { { "connect", 'h', 0, G_OPTION_ARG_STRING, &connect_str, "Specify host and port", NULL }, { "password", 'P', G_OPTION_FLAG_OPTIONAL_ARG, G_OPTION_ARG_CALLBACK, &rspamc_password_callback, "Specify control password", NULL }, { "classifier", 'c', 0, G_OPTION_ARG_STRING, &classifier, "Classifier to learn spam or ham", NULL }, { "weight", 'w', 0, G_OPTION_ARG_INT, &weight, "Weight for fuzzy operations", NULL }, { "flag", 'f', 0, G_OPTION_ARG_INT, &flag, "Flag for fuzzy operations", NULL }, { "pass-all", 'p', 0, G_OPTION_ARG_NONE, &pass_all, "Pass all filters", NULL }, { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "More verbose output", NULL }, { "ip", 'i', 0, G_OPTION_ARG_STRING, &ip, "Emulate that message was received from specified ip address", NULL }, { "user", 'u', 0, G_OPTION_ARG_STRING, &user, "Emulate that message was received from specified authenticated user", NULL }, { "deliver", 'd', 0, G_OPTION_ARG_STRING, &deliver_to, "Emulate that message is delivered to specified user (for LDA/statistics)", NULL }, { "from", 'F', 0, G_OPTION_ARG_STRING, &from, "Emulate that message has specified SMTP FROM address", NULL }, { "rcpt", 'r', 0, G_OPTION_ARG_STRING_ARRAY, &rcpts, "Emulate that message has specified SMTP RCPT address", NULL }, { "helo", 0, 0, G_OPTION_ARG_STRING, &helo, "Imitate SMTP HELO passing from MTA", NULL }, { "hostname", 0, 0, G_OPTION_ARG_STRING, &hostname, "Imitate hostname passing from MTA", NULL }, { "timeout", 't', 0, G_OPTION_ARG_DOUBLE, &timeout, "Time in seconds to wait for a reply", NULL }, { "bind", 'b', 0, G_OPTION_ARG_STRING, &local_addr, "Bind to specified ip address", NULL }, { "commands", 0, 0, G_OPTION_ARG_NONE, &print_commands, "List available commands", NULL }, { "json", 'j', 0, G_OPTION_ARG_NONE, &json, "Output json reply", NULL }, { "compact", '\0', 0, G_OPTION_ARG_NONE, &compact, "Output compact json reply", NULL}, { "headers", 0, 0, G_OPTION_ARG_NONE, &headers, "Output HTTP headers", NULL }, { "raw", 0, 0, G_OPTION_ARG_NONE, &raw, "Output raw reply from rspamd", NULL }, { "ucl", 0, 0, G_OPTION_ARG_NONE, &raw, "Output ucl reply from rspamd", NULL }, { "max-requests", 'n', 0, G_OPTION_ARG_INT, &max_requests, "Maximum count of parallel requests to rspamd", NULL }, { "extended-urls", 0, 0, G_OPTION_ARG_NONE, &extended_urls, "Output urls in extended format", NULL }, { "key", 0, 0, G_OPTION_ARG_STRING, &key, "Use specified pubkey to encrypt request", NULL }, { "exec", 'e', 0, G_OPTION_ARG_STRING, &execute, "Execute the specified command and pass output to it", NULL }, { "mime", 'm', 0, G_OPTION_ARG_NONE, &mime_output, "Write mime body of message with headers instead of just a scan's result", NULL }, {"header", 0, 0, G_OPTION_ARG_STRING_ARRAY, &http_headers, "Add custom HTTP header to query (can be repeated)", NULL}, {"exclude", 0, 0, G_OPTION_ARG_STRING_ARRAY, &exclude_patterns, "Exclude specific glob patterns in file names (can be repeated)", NULL}, {"sort", 0, 0, G_OPTION_ARG_STRING, &sort, "Sort output in a specific order (name, weight, frequency, hits)", NULL}, { "empty", 'E', 0, G_OPTION_ARG_NONE, &empty_input, "Allow empty input instead of reading from stdin", NULL }, { "fuzzy-symbol", 'S', 0, G_OPTION_ARG_STRING, &fuzzy_symbol, "Learn the specified fuzzy symbol", NULL }, { "compressed", 'z', 0, G_OPTION_ARG_NONE, &compressed, "Enable zstd compression", NULL }, { "profile", '\0', 0, G_OPTION_ARG_NONE, &profile, "Profile symbols execution time", NULL }, { "dictionary", 'D', 0, G_OPTION_ARG_FILENAME, &dictionary, "Use dictionary to compress data", NULL }, { "skip-images", '\0', 0, G_OPTION_ARG_NONE, &skip_images, "Skip images when learning/unlearning fuzzy", NULL }, { "skip-attachments", '\0', 0, G_OPTION_ARG_NONE, &skip_attachments, "Skip attachments when learning/unlearning fuzzy", NULL }, { "user-agent", 'U', 0, G_OPTION_ARG_STRING, &user_agent, "Use specific User-Agent instead of \"rspamc\"", NULL }, { NULL, 0, 0, G_OPTION_ARG_NONE, NULL, NULL, NULL } }; /* Copy to avoid linking with librspamdserver */ enum rspamd_action_type { METRIC_ACTION_REJECT = 0, METRIC_ACTION_SOFT_REJECT, METRIC_ACTION_REWRITE_SUBJECT, METRIC_ACTION_ADD_HEADER, METRIC_ACTION_GREYLIST, METRIC_ACTION_NOACTION, METRIC_ACTION_MAX }; static void rspamc_symbols_output (FILE *out, ucl_object_t *obj); static void rspamc_uptime_output (FILE *out, ucl_object_t *obj); static void rspamc_counters_output (FILE *out, ucl_object_t *obj); static void rspamc_stat_output (FILE *out, ucl_object_t *obj); enum rspamc_command_type { RSPAMC_COMMAND_UNKNOWN = 0, RSPAMC_COMMAND_CHECK, RSPAMC_COMMAND_SYMBOLS, RSPAMC_COMMAND_LEARN_SPAM, RSPAMC_COMMAND_LEARN_HAM, RSPAMC_COMMAND_FUZZY_ADD, RSPAMC_COMMAND_FUZZY_DEL, RSPAMC_COMMAND_FUZZY_DELHASH, RSPAMC_COMMAND_STAT, RSPAMC_COMMAND_STAT_RESET, RSPAMC_COMMAND_COUNTERS, RSPAMC_COMMAND_UPTIME, RSPAMC_COMMAND_ADD_SYMBOL, RSPAMC_COMMAND_ADD_ACTION }; struct rspamc_command { enum rspamc_command_type cmd; const char *name; const char *description; const char *path; gboolean is_controller; gboolean is_privileged; gboolean need_input; void (*command_output_func)(FILE *, ucl_object_t *obj); } rspamc_commands[] = { { .cmd = RSPAMC_COMMAND_SYMBOLS, .name = "symbols", .path = "checkv2", .description = "scan message and show symbols (default command)", .is_controller = FALSE, .is_privileged = FALSE, .need_input = TRUE, .command_output_func = rspamc_symbols_output }, { .cmd = RSPAMC_COMMAND_LEARN_SPAM, .name = "learn_spam", .path = "learnspam", .description = "learn message as spam", .is_controller = TRUE, .is_privileged = TRUE, .need_input = TRUE, .command_output_func = NULL }, { .cmd = RSPAMC_COMMAND_LEARN_HAM, .name = "learn_ham", .path = "learnham", .description = "learn message as ham", .is_controller = TRUE, .is_privileged = TRUE, .need_input = TRUE, .command_output_func = NULL }, { .cmd = RSPAMC_COMMAND_FUZZY_ADD, .name = "fuzzy_add", .path = "fuzzyadd", .description = "add hashes from a message to the fuzzy storage (check -f and -w options for this command)", .is_controller = TRUE, .is_privileged = TRUE, .need_input = TRUE, .command_output_func = NULL }, { .cmd = RSPAMC_COMMAND_FUZZY_DEL, .name = "fuzzy_del", .path = "fuzzydel", .description = "delete hashes from a message from the fuzzy storage (check -f option for this command)", .is_controller = TRUE, .is_privileged = TRUE, .need_input = TRUE, .command_output_func = NULL }, { .cmd = RSPAMC_COMMAND_FUZZY_DELHASH, .name = "fuzzy_delhash", .path = "fuzzydelhash", .description = "delete a hash from fuzzy storage (check -f option for this command)", .is_controller = TRUE, .is_privileged = TRUE, .need_input = FALSE, .command_output_func = NULL }, { .cmd = RSPAMC_COMMAND_STAT, .name = "stat", .path = "stat", .description = "show rspamd statistics", .is_controller = TRUE, .is_privileged = FALSE, .need_input = FALSE, .command_output_func = rspamc_stat_output, }, { .cmd = RSPAMC_COMMAND_STAT_RESET, .name = "stat_reset", .path = "statreset", .description = "show and reset rspamd statistics (useful for graphs)", .is_controller = TRUE, .is_privileged = TRUE, .need_input = FALSE, .command_output_func = rspamc_stat_output }, { .cmd = RSPAMC_COMMAND_COUNTERS, .name = "counters", .path = "counters", .description = "display rspamd symbols statistics", .is_controller = TRUE, .is_privileged = FALSE, .need_input = FALSE, .command_output_func = rspamc_counters_output }, { .cmd = RSPAMC_COMMAND_UPTIME, .name = "uptime", .path = "auth", .description = "show rspamd uptime", .is_controller = TRUE, .is_privileged = FALSE, .need_input = FALSE, .command_output_func = rspamc_uptime_output }, { .cmd = RSPAMC_COMMAND_ADD_SYMBOL, .name = "add_symbol", .path = "addsymbol", .description = "add or modify symbol settings in rspamd", .is_controller = TRUE, .is_privileged = TRUE, .need_input = FALSE, .command_output_func = NULL }, { .cmd = RSPAMC_COMMAND_ADD_ACTION, .name = "add_action", .path = "addaction", .description = "add or modify action settings", .is_controller = TRUE, .is_privileged = TRUE, .need_input = FALSE, .command_output_func = NULL } }; struct rspamc_callback_data { struct rspamc_command *cmd; gchar *filename; }; gboolean rspamc_password_callback (const gchar *option_name, const gchar *value, gpointer data, GError **error) { guint plen = 8192; guint8 *map, *end; gsize sz; if (value != NULL) { if (value[0] == '/' || value[0] == '.') { /* Try to open file */ map = rspamd_file_xmap (value, PROT_READ, &sz, 0); if (map == NULL) { /* Just use it as a string */ password = g_strdup (value); } else { /* Strip trailing spaces */ g_assert (sz > 0); end = map + sz - 1; while (g_ascii_isspace (*end) && end > map) { end --; } end ++; password = g_malloc (end - map + 1); rspamd_strlcpy (password, map, end - map + 1); munmap (map, sz); } } else { password = g_strdup (value); } } else { /* Read password from console */ password = g_malloc0 (plen); plen = rspamd_read_passphrase (password, plen, 0, NULL); } if (plen == 0) { rspamd_fprintf (stderr, "Invalid password\n"); exit (EXIT_FAILURE); } return TRUE; } /* * Parse command line */ static void read_cmd_line (gint *argc, gchar ***argv) { GError *error = NULL; GOptionContext *context; /* Prepare parser */ context = g_option_context_new ("- run rspamc client"); g_option_context_set_summary (context, "Summary:\n Rspamd client version " RVERSION "\n Release id: " RID); g_option_context_add_main_entries (context, entries, NULL); /* Parse options */ if (!g_option_context_parse (context, argc, argv, &error)) { fprintf (stderr, "option parsing failed: %s\n", error->message); exit (EXIT_FAILURE); } if (json || compact) { raw = TRUE; } /* Argc and argv are shifted after this function */ } static gboolean rspamd_action_from_str_rspamc (const gchar *data, gint *result) { if (strcmp (data, "reject") == 0) { *result = METRIC_ACTION_REJECT; } else if (strcmp (data, "greylist") == 0) { *result = METRIC_ACTION_GREYLIST; } else if (strcmp (data, "add_header") == 0) { *result = METRIC_ACTION_ADD_HEADER; } else if (strcmp (data, "rewrite_subject") == 0) { *result = METRIC_ACTION_REWRITE_SUBJECT; } else if (strcmp (data, "add header") == 0) { *result = METRIC_ACTION_ADD_HEADER; } else if (strcmp (data, "rewrite subject") == 0) { *result = METRIC_ACTION_REWRITE_SUBJECT; } else if (strcmp (data, "soft_reject") == 0) { *result = METRIC_ACTION_SOFT_REJECT; } else if (strcmp (data, "soft reject") == 0) { *result = METRIC_ACTION_SOFT_REJECT; } else if (strcmp (data, "no_action") == 0) { *result = METRIC_ACTION_NOACTION; } else if (strcmp (data, "no action") == 0) { *result = METRIC_ACTION_NOACTION; } else { return FALSE; } return TRUE; } /* * Check rspamc command from string (used for arguments parsing) */ static struct rspamc_command * check_rspamc_command (const gchar *cmd) { enum rspamc_command_type ct = 0; guint i; if (g_ascii_strcasecmp (cmd, "SYMBOLS") == 0 || g_ascii_strcasecmp (cmd, "CHECK") == 0 || g_ascii_strcasecmp (cmd, "REPORT") == 0) { /* These all are symbols, don't use other commands */ ct = RSPAMC_COMMAND_SYMBOLS; } else if (g_ascii_strcasecmp (cmd, "LEARN_SPAM") == 0) { ct = RSPAMC_COMMAND_LEARN_SPAM; } else if (g_ascii_strcasecmp (cmd, "LEARN_HAM") == 0) { ct = RSPAMC_COMMAND_LEARN_HAM; } else if (g_ascii_strcasecmp (cmd, "FUZZY_ADD") == 0) { ct = RSPAMC_COMMAND_FUZZY_ADD; } else if (g_ascii_strcasecmp (cmd, "FUZZY_DEL") == 0) { ct = RSPAMC_COMMAND_FUZZY_DEL; } else if (g_ascii_strcasecmp (cmd, "FUZZY_DELHASH") == 0) { ct = RSPAMC_COMMAND_FUZZY_DELHASH; } else if (g_ascii_strcasecmp (cmd, "STAT") == 0) { ct = RSPAMC_COMMAND_STAT; } else if (g_ascii_strcasecmp (cmd, "STAT_RESET") == 0) { ct = RSPAMC_COMMAND_STAT_RESET; } else if (g_ascii_strcasecmp (cmd, "COUNTERS") == 0) { ct = RSPAMC_COMMAND_COUNTERS; } else if (g_ascii_strcasecmp (cmd, "UPTIME") == 0) { ct = RSPAMC_COMMAND_UPTIME; } else if (g_ascii_strcasecmp (cmd, "ADD_SYMBOL") == 0) { ct = RSPAMC_COMMAND_ADD_SYMBOL; } else if (g_ascii_strcasecmp (cmd, "ADD_ACTION") == 0) { ct = RSPAMC_COMMAND_ADD_ACTION; } for (i = 0; i < G_N_ELEMENTS (rspamc_commands); i++) { if (rspamc_commands[i].cmd == ct) { return &rspamc_commands[i]; } } return NULL; } static void print_commands_list (void) { guint i; guint cmd_len = 0; gchar fmt_str[32]; rspamd_fprintf (stdout, "Rspamc commands summary:\n"); for (i = 0; i < G_N_ELEMENTS (rspamc_commands); i++) { gsize clen = strlen (rspamc_commands[i].name); if (clen > cmd_len) { cmd_len = clen; } } rspamd_snprintf (fmt_str, sizeof (fmt_str), " %%%ds (%%7s%%1s)\t%%s\n", cmd_len); for (i = 0; i < G_N_ELEMENTS (rspamc_commands); i++) { fprintf (stdout, fmt_str, rspamc_commands[i].name, rspamc_commands[i].is_controller ? "control" : "normal", rspamc_commands[i].is_privileged ? "*" : "", rspamc_commands[i].description); } rspamd_fprintf (stdout, "\n* is for privileged commands that may need password (see -P option)\n"); rspamd_fprintf (stdout, "control commands use port 11334 while normal use 11333 by default (see -h option)\n"); } static void add_options (GQueue *opts) { GString *numbuf; gchar **hdr, **rcpt; GString *flagbuf = g_string_new (NULL); if (ip != NULL) { rspamd_inet_addr_t *addr = NULL; if (!rspamd_parse_inet_address (&addr, ip, strlen (ip))) { /* Try to resolve */ struct addrinfo hints, *res, *cur; gint r; memset (&hints, 0, sizeof (hints)); hints.ai_socktype = SOCK_STREAM; /* Type of the socket */ #ifdef AI_IDN hints.ai_flags = AI_NUMERICSERV|AI_IDN; #else hints.ai_flags = AI_NUMERICSERV; #endif hints.ai_family = AF_UNSPEC; if ((r = getaddrinfo (ip, "25", &hints, &res)) == 0) { cur = res; while (cur) { addr = rspamd_inet_address_from_sa (cur->ai_addr, cur->ai_addrlen); if (addr != NULL) { ip = g_strdup (rspamd_inet_address_to_string (addr)); rspamd_inet_address_free (addr); break; } cur = cur->ai_next; } freeaddrinfo (res); } else { rspamd_fprintf (stderr, "address resolution for %s failed: %s\n", ip, gai_strerror (r)); } } else { rspamd_inet_address_free (addr); } ADD_CLIENT_HEADER (opts, "Ip", ip); } if (from != NULL) { ADD_CLIENT_HEADER (opts, "From", from); } if (user != NULL) { ADD_CLIENT_HEADER (opts, "User", user); } if (rcpts != NULL) { for (rcpt = rcpts; *rcpt != NULL; rcpt ++) { ADD_CLIENT_HEADER (opts, "Rcpt", *rcpt); } } if (deliver_to != NULL) { ADD_CLIENT_HEADER (opts, "Deliver-To", deliver_to); } if (helo != NULL) { ADD_CLIENT_HEADER (opts, "Helo", helo); } if (hostname != NULL) { ADD_CLIENT_HEADER (opts, "Hostname", hostname); } if (password != NULL) { ADD_CLIENT_HEADER (opts, "Password", password); } if (pass_all) { ADD_CLIENT_FLAG (flagbuf, "pass_all"); } if (classifier) { ADD_CLIENT_HEADER (opts, "Classifier", classifier); } if (weight != 0) { numbuf = g_string_sized_new (8); rspamd_printf_gstring (numbuf, "%d", weight); ADD_CLIENT_HEADER (opts, "Weight", numbuf->str); g_string_free (numbuf, TRUE); } if (fuzzy_symbol != NULL) { ADD_CLIENT_HEADER (opts, "Symbol", fuzzy_symbol); } if (flag != 0) { numbuf = g_string_sized_new (8); rspamd_printf_gstring (numbuf, "%d", flag); ADD_CLIENT_HEADER (opts, "Flag", numbuf->str); g_string_free (numbuf, TRUE); } if (extended_urls) { ADD_CLIENT_HEADER (opts, "URL-Format", "extended"); } if (profile) { ADD_CLIENT_FLAG (flagbuf, "profile"); } ADD_CLIENT_FLAG (flagbuf, "body_block"); if (skip_images) { ADD_CLIENT_HEADER (opts, "Skip-Images", "true"); } if (skip_attachments) { ADD_CLIENT_HEADER (opts, "Skip-Attachments", "true"); } hdr = http_headers; while (hdr != NULL && *hdr != NULL) { gchar **kv = g_strsplit_set (*hdr, ":=", 2); if (kv == NULL || kv[1] == NULL) { ADD_CLIENT_HEADER (opts, *hdr, ""); } else { ADD_CLIENT_HEADER (opts, kv[0], kv[1]); } if (kv) { g_strfreev (kv); } hdr ++; } if (flagbuf->len > 0) { goffset last = flagbuf->len - 1; if (flagbuf->str[last] == ',') { flagbuf->str[last] = '\0'; flagbuf->len --; } ADD_CLIENT_HEADER (opts, "Flags", flagbuf->str); } g_string_free (flagbuf, TRUE); } static void rspamc_symbol_output (FILE *out, const ucl_object_t *obj) { const ucl_object_t *val, *cur; ucl_object_iter_t it = NULL; gboolean first = TRUE; rspamd_fprintf (out, "Symbol: %s ", ucl_object_key (obj)); val = ucl_object_lookup (obj, "score"); if (val != NULL) { rspamd_fprintf (out, "(%.2f)", ucl_object_todouble (val)); } val = ucl_object_lookup (obj, "options"); if (val != NULL && val->type == UCL_ARRAY) { rspamd_fprintf (out, "["); while ((cur = ucl_object_iterate (val, &it, TRUE)) != NULL) { if (first) { rspamd_fprintf (out, "%s", ucl_object_tostring (cur)); first = FALSE; } else { rspamd_fprintf (out, ", %s", ucl_object_tostring (cur)); } } rspamd_fprintf (out, "]"); } rspamd_fprintf (out, "\n"); } static gint rspamc_symbols_sort_func (gconstpointer a, gconstpointer b) { ucl_object_t * const *ua = a, * const *ub = b; return strcmp (ucl_object_key (*ua), ucl_object_key (*ub)); } #define PRINT_PROTOCOL_STRING(ucl_name, output_message) do { \ elt = ucl_object_lookup (obj, (ucl_name)); \ if (elt) { \ rspamd_fprintf (out, output_message ": %s\n", ucl_object_tostring (elt)); \ } \ } while (0) static void rspamc_metric_output (FILE *out, const ucl_object_t *obj) { ucl_object_iter_t it = NULL; const ucl_object_t *cur, *elt; gdouble score = 0, required_score = 0; gint got_scores = 0, action = METRIC_ACTION_MAX; GPtrArray *sym_ptr; guint i; sym_ptr = g_ptr_array_new (); rspamd_fprintf (out, "[Metric: default]\n"); elt = ucl_object_lookup (obj, "required_score"); if (elt) { required_score = ucl_object_todouble (elt); got_scores++; } elt = ucl_object_lookup (obj, "score"); if (elt) { score = ucl_object_todouble (elt); got_scores++; } PRINT_PROTOCOL_STRING ("action", "Action"); /* Defined by previous macro */ if (elt && rspamd_action_from_str_rspamc (ucl_object_tostring (elt), &action)) { rspamd_fprintf (out, "Spam: %s\n", action < METRIC_ACTION_GREYLIST ? "true" : "false"); } PRINT_PROTOCOL_STRING ("subject", "Subject"); if (got_scores == 2) { rspamd_fprintf (out, "Score: %.2f / %.2f\n", score, required_score); } elt = ucl_object_lookup (obj, "symbols"); while (elt && (cur = ucl_object_iterate (elt, &it, true)) != NULL) { if (cur->type == UCL_OBJECT) { g_ptr_array_add (sym_ptr, (void *)cur); } } g_ptr_array_sort (sym_ptr, rspamc_symbols_sort_func); for (i = 0; i < sym_ptr->len; i ++) { cur = (const ucl_object_t *)g_ptr_array_index (sym_ptr, i); rspamc_symbol_output (out, cur); } g_ptr_array_free (sym_ptr, TRUE); } static gint rspamc_profile_sort_func (gconstpointer a, gconstpointer b) { ucl_object_t * const *ua = a, * const *ub = b; return ucl_object_compare (*ua, *ub); } static void rspamc_profile_output (FILE *out, const ucl_object_t *obj) { ucl_object_iter_t it = NULL; const ucl_object_t *cur; guint i; GPtrArray *ar; ar = g_ptr_array_sized_new (obj->len); while ((cur = ucl_object_iterate (obj, &it, true)) != NULL) { g_ptr_array_add (ar, (void *)cur); } g_ptr_array_sort (ar, rspamc_profile_sort_func); for (i = 0; i < ar->len; i ++) { cur = (const ucl_object_t *)g_ptr_array_index (ar, i); rspamd_fprintf (out, "\t%s: %.3f usec\n", ucl_object_key (cur), ucl_object_todouble (cur)); } g_ptr_array_free (ar, TRUE); } static void rspamc_symbols_output (FILE *out, ucl_object_t *obj) { ucl_object_iter_t mit = NULL; const ucl_object_t *cmesg, *elt; gchar *emitted; rspamc_metric_output (out, obj); PRINT_PROTOCOL_STRING ("message-id", "Message-ID"); PRINT_PROTOCOL_STRING ("queue-id", "Queue-ID"); elt = ucl_object_lookup (obj, "urls"); if (elt) { if (!extended_urls || compact) { emitted = ucl_object_emit (elt, UCL_EMIT_JSON_COMPACT); } else { emitted = ucl_object_emit (elt, UCL_EMIT_JSON); } rspamd_fprintf (out, "Urls: %s\n", emitted); free (emitted); } elt = ucl_object_lookup (obj, "emails"); if (elt) { if (!extended_urls || compact) { emitted = ucl_object_emit (elt, UCL_EMIT_JSON_COMPACT); } else { emitted = ucl_object_emit (elt, UCL_EMIT_JSON); } rspamd_fprintf (out, "Emails: %s\n", emitted); free (emitted); } PRINT_PROTOCOL_STRING ("error", "Scan error"); elt = ucl_object_lookup (obj, "messages"); if (elt && elt->type == UCL_OBJECT) { mit = NULL; while ((cmesg = ucl_object_iterate (elt, &mit, true)) != NULL) { rspamd_fprintf (out, "Message - %s: %s\n", ucl_object_key (cmesg), ucl_object_tostring (cmesg)); } } elt = ucl_object_lookup (obj, "dkim-signature"); if (elt && elt->type == UCL_STRING) { rspamd_fprintf (out, "DKIM-Signature: %s\n", ucl_object_tostring (elt)); } else if (elt && elt->type == UCL_ARRAY) { mit = NULL; while ((cmesg = ucl_object_iterate (elt, &mit, true)) != NULL) { rspamd_fprintf (out, "DKIM-Signature: %s\n", ucl_object_tostring (cmesg)); } } elt = ucl_object_lookup (obj, "profile"); if (elt) { rspamd_fprintf (out, "Profile data:\n"); rspamc_profile_output (out, elt); } } static void rspamc_uptime_output (FILE *out, ucl_object_t *obj) { const ucl_object_t *elt; int64_t seconds, days, hours, minutes; elt = ucl_object_lookup (obj, "version"); if (elt != NULL) { rspamd_fprintf (out, "Rspamd version: %s\n", ucl_object_tostring ( elt)); } elt = ucl_object_lookup (obj, "uptime"); if (elt != NULL) { rspamd_printf ("Uptime: "); seconds = ucl_object_toint (elt); if (seconds >= 2 * 3600) { days = seconds / 86400; hours = seconds / 3600 - days * 24; minutes = seconds / 60 - hours * 60 - days * 1440; rspamd_printf ("%L day%s %L hour%s %L minute%s\n", days, days > 1 ? "s" : "", hours, hours > 1 ? "s" : "", minutes, minutes > 1 ? "s" : ""); } /* If uptime is less than 1 minute print only seconds */ else if (seconds / 60 == 0) { rspamd_printf ("%L second%s\n", seconds, (gint)seconds > 1 ? "s" : ""); } /* Else print the minutes and seconds. */ else { hours = seconds / 3600; minutes = seconds / 60 - hours * 60; seconds -= hours * 3600 + minutes * 60; rspamd_printf ("%L hour %L minute%s %L second%s\n", hours, minutes, minutes > 1 ? "s" : "", seconds, seconds > 1 ? "s" : ""); } } } static gint rspamc_counters_sort (const ucl_object_t **o1, const ucl_object_t **o2) { gint order1 = 0, order2 = 0, c; const ucl_object_t *elt1, *elt2; gboolean inverse = FALSE; gchar **args; if (sort != NULL) { args = g_strsplit_set (sort, ":", 2); if (args && args[0]) { if (args[1] && g_ascii_strcasecmp (args[1], "desc") == 0) { inverse = TRUE; } if (g_ascii_strcasecmp (args[0], "name") == 0) { elt1 = ucl_object_lookup (*o1, "symbol"); elt2 = ucl_object_lookup (*o2, "symbol"); if (elt1 && elt2) { c = strcmp (ucl_object_tostring (elt1), ucl_object_tostring (elt2)); order1 = c > 0 ? 1 : 0; order2 = c < 0 ? 1 : 0; } } else if (g_ascii_strcasecmp (args[0], "weight") == 0) { elt1 = ucl_object_lookup (*o1, "weight"); elt2 = ucl_object_lookup (*o2, "weight"); if (elt1 && elt2) { order1 = ucl_object_todouble (elt1) * 1000.0; order2 = ucl_object_todouble (elt2) * 1000.0; } } else if (g_ascii_strcasecmp (args[0], "frequency") == 0) { elt1 = ucl_object_lookup (*o1, "frequency"); elt2 = ucl_object_lookup (*o2, "frequency"); if (elt1 && elt2) { order1 = ucl_object_todouble (elt1) * 100000; order2 = ucl_object_todouble (elt2) * 100000; } } else if (g_ascii_strcasecmp (args[0], "time") == 0) { elt1 = ucl_object_lookup (*o1, "time"); elt2 = ucl_object_lookup (*o2, "time"); if (elt1 && elt2) { order1 = ucl_object_todouble (elt1) * 1000000; order2 = ucl_object_todouble (elt2) * 1000000; } } else if (g_ascii_strcasecmp (args[0], "hits") == 0) { elt1 = ucl_object_lookup (*o1, "hits"); elt2 = ucl_object_lookup (*o2, "hits"); if (elt1 && elt2) { order1 = ucl_object_toint (elt1); order2 = ucl_object_toint (elt2); } } } g_strfreev (args); } return (inverse ? (order2 - order1) : (order1 - order2)); } static void rspamc_counters_output (FILE *out, ucl_object_t *obj) { const ucl_object_t *cur, *sym, *weight, *freq, *freq_dev, *nhits; ucl_object_iter_t iter = NULL; gchar fmt_buf[64], dash_buf[82], sym_buf[82]; gint l, max_len = INT_MIN, i; static const gint dashes = 44; if (obj->type != UCL_ARRAY) { rspamd_printf ("Bad output\n"); return; } /* Sort symbols by their order */ if (sort != NULL) { ucl_object_array_sort (obj, rspamc_counters_sort); } /* Find maximum width of symbol's name */ while ((cur = ucl_object_iterate (obj, &iter, true)) != NULL) { sym = ucl_object_lookup (cur, "symbol"); if (sym != NULL) { l = sym->len; if (l > max_len) { max_len = MIN (sizeof (dash_buf) - dashes - 1, l); } } } rspamd_snprintf (fmt_buf, sizeof (fmt_buf), "| %%3s | %%%ds | %%7s | %%13s | %%7s |\n", max_len); memset (dash_buf, '-', dashes + max_len); dash_buf[dashes + max_len] = '\0'; printf ("Symbols cache\n"); printf (" %s \n", dash_buf); if (tty) { printf ("\033[1m"); } printf (fmt_buf, "Pri", "Symbol", "Weight", "Frequency", "Hits"); printf (" %s \n", dash_buf); printf (fmt_buf, "", "", "", "hits/min", ""); if (tty) { printf ("\033[0m"); } rspamd_snprintf (fmt_buf, sizeof (fmt_buf), "| %%3d | %%%ds | %%7.1f | %%6.3f(%%5.3f) | %%7ju |\n", max_len); iter = NULL; i = 0; while ((cur = ucl_object_iterate (obj, &iter, true)) != NULL) { printf (" %s \n", dash_buf); sym = ucl_object_lookup (cur, "symbol"); weight = ucl_object_lookup (cur, "weight"); freq = ucl_object_lookup (cur, "frequency"); freq_dev = ucl_object_lookup (cur, "frequency_stddev"); nhits = ucl_object_lookup (cur, "hits"); if (sym && weight && freq && nhits) { const gchar *sym_name; if (sym->len > max_len) { rspamd_snprintf (sym_buf, sizeof (sym_buf), "%*s...", (max_len - 3), ucl_object_tostring (sym)); sym_name = sym_buf; } else { sym_name = ucl_object_tostring (sym); } printf (fmt_buf, i, sym_name, ucl_object_todouble (weight), ucl_object_todouble (freq) * 60.0, ucl_object_todouble (freq_dev) * 60.0, (uintmax_t)ucl_object_toint (nhits)); } i++; } printf (" %s \n", dash_buf); } static void rspamc_stat_actions (ucl_object_t *obj, GString *out, gint64 scanned) { const ucl_object_t *actions = ucl_object_lookup (obj, "actions"), *cur; ucl_object_iter_t iter = NULL; gint64 spam, ham; if (actions && ucl_object_type (actions) == UCL_OBJECT) { while ((cur = ucl_object_iterate (actions, &iter, true)) != NULL) { gint64 cnt = ucl_object_toint (cur); rspamd_printf_gstring (out, "Messages with action %s: %L" ", %.2f%%\n", ucl_object_key (cur), cnt, ((gdouble)cnt / (gdouble)scanned) * 100.); } } spam = ucl_object_toint (ucl_object_lookup (obj, "spam_count")); ham = ucl_object_toint (ucl_object_lookup (obj, "ham_count")); rspamd_printf_gstring (out, "Messages treated as spam: %L, %.2f%%\n", spam, ((gdouble)spam / (gdouble)scanned) * 100.); rspamd_printf_gstring (out, "Messages treated as ham: %L, %.2f%%\n", ham, ((gdouble)ham / (gdouble)scanned) * 100.); } static void rspamc_stat_statfile (const ucl_object_t *obj, GString *out) { gint64 version, size, blocks, used_blocks, nlanguages, nusers; const gchar *label, *symbol, *type; version = ucl_object_toint (ucl_object_lookup (obj, "revision")); size = ucl_object_toint (ucl_object_lookup (obj, "size")); blocks = ucl_object_toint (ucl_object_lookup (obj, "total")); used_blocks = ucl_object_toint (ucl_object_lookup (obj, "used")); label = ucl_object_tostring (ucl_object_lookup (obj, "label")); symbol = ucl_object_tostring (ucl_object_lookup (obj, "symbol")); type = ucl_object_tostring (ucl_object_lookup (obj, "type")); nlanguages = ucl_object_toint (ucl_object_lookup (obj, "languages")); nusers = ucl_object_toint (ucl_object_lookup (obj, "users")); if (label) { rspamd_printf_gstring (out, "Statfile: %s <%s> type: %s; ", symbol, label, type); } else { rspamd_printf_gstring (out, "Statfile: %s type: %s; ", symbol, type); } rspamd_printf_gstring (out, "length: %hL; free blocks: %hL; total blocks: %hL; " "free: %.2f%%; learned: %L; users: %L; languages: %L\n", size, blocks - used_blocks, blocks, blocks > 0 ? (blocks - used_blocks) * 100.0 / (gdouble)blocks : 0, version, nusers, nlanguages); } static void rspamc_stat_output (FILE *out, ucl_object_t *obj) { GString *out_str; ucl_object_iter_t iter = NULL; const ucl_object_t *st, *cur; gint64 scanned; out_str = g_string_sized_new (BUFSIZ); scanned = ucl_object_toint (ucl_object_lookup (obj, "scanned")); rspamd_printf_gstring (out_str, "Messages scanned: %L\n", scanned); if (scanned > 0) { rspamc_stat_actions (obj, out_str, scanned); } rspamd_printf_gstring (out_str, "Messages learned: %L\n", ucl_object_toint (ucl_object_lookup (obj, "learned"))); rspamd_printf_gstring (out_str, "Connections count: %L\n", ucl_object_toint (ucl_object_lookup (obj, "connections"))); rspamd_printf_gstring (out_str, "Control connections count: %L\n", ucl_object_toint (ucl_object_lookup (obj, "control_connections"))); /* Pools */ rspamd_printf_gstring (out_str, "Pools allocated: %L\n", ucl_object_toint (ucl_object_lookup (obj, "pools_allocated"))); rspamd_printf_gstring (out_str, "Pools freed: %L\n", ucl_object_toint (ucl_object_lookup (obj, "pools_freed"))); rspamd_printf_gstring (out_str, "Bytes allocated: %HL\n", ucl_object_toint (ucl_object_lookup (obj, "bytes_allocated"))); rspamd_printf_gstring (out_str, "Memory chunks allocated: %L\n", ucl_object_toint (ucl_object_lookup (obj, "chunks_allocated"))); rspamd_printf_gstring (out_str, "Shared chunks allocated: %L\n", ucl_object_toint (ucl_object_lookup (obj, "shared_chunks_allocated"))); rspamd_printf_gstring (out_str, "Chunks freed: %L\n", ucl_object_toint (ucl_object_lookup (obj, "chunks_freed"))); rspamd_printf_gstring (out_str, "Oversized chunks: %L\n", ucl_object_toint (ucl_object_lookup (obj, "chunks_oversized"))); /* Fuzzy */ st = ucl_object_lookup (obj, "fuzzy_hashes"); if (st) { ucl_object_iter_t it = NULL; const ucl_object_t *cur; gint64 stored = 0; while ((cur = ucl_iterate_object (st, &it, true)) != NULL) { rspamd_printf_gstring (out_str, "Fuzzy hashes in storage \"%s\": %L\n", ucl_object_key (cur), ucl_object_toint (cur)); stored += ucl_object_toint (cur); } rspamd_printf_gstring (out_str, "Fuzzy hashes stored: %L\n", stored); } st = ucl_object_lookup (obj, "fuzzy_checked"); if (st != NULL && ucl_object_type (st) == UCL_ARRAY) { rspamd_printf_gstring (out_str, "Fuzzy hashes checked: "); iter = NULL; while ((cur = ucl_object_iterate (st, &iter, true)) != NULL) { rspamd_printf_gstring (out_str, "%hL ", ucl_object_toint (cur)); } rspamd_printf_gstring (out_str, "\n"); } st = ucl_object_lookup (obj, "fuzzy_found"); if (st != NULL && ucl_object_type (st) == UCL_ARRAY) { rspamd_printf_gstring (out_str, "Fuzzy hashes found: "); iter = NULL; while ((cur = ucl_object_iterate (st, &iter, true)) != NULL) { rspamd_printf_gstring (out_str, "%hL ", ucl_object_toint (cur)); } rspamd_printf_gstring (out_str, "\n"); } st = ucl_object_lookup (obj, "statfiles"); if (st != NULL && ucl_object_type (st) == UCL_ARRAY) { iter = NULL; while ((cur = ucl_object_iterate (st, &iter, true)) != NULL) { rspamc_stat_statfile (cur, out_str); } } rspamd_printf_gstring (out_str, "Total learns: %L\n", ucl_object_toint (ucl_object_lookup (obj, "total_learns"))); rspamd_fprintf (out, "%v", out_str); } static void rspamc_output_headers (FILE *out, struct rspamd_http_message *msg) { struct rspamd_http_header *h, *htmp; HASH_ITER (hh, msg->headers, h, htmp) { rspamd_fprintf (out, "%T: %T\n", &h->name, &h->value); } rspamd_fprintf (out, "\n"); } static void rspamc_mime_output (FILE *out, ucl_object_t *result, GString *input, gdouble time, GError *err) { const ucl_object_t *cur, *res, *syms; ucl_object_iter_t it = NULL; const gchar *action = "no action", *line_end = "\r\n", *p; gchar scorebuf[32]; GString *symbuf, *folded_symbuf, *added_headers; gint act = 0; goffset headers_pos; gdouble score = 0.0, required_score = 0.0; gboolean is_spam = FALSE; gchar *json_header, *json_header_encoded, *sc; enum rspamd_newlines_type nl_type = RSPAMD_TASK_NEWLINES_CRLF; headers_pos = rspamd_string_find_eoh (input, NULL); if (headers_pos == -1) { rspamd_fprintf (stderr,"cannot find end of headers position"); return; } p = input->str + headers_pos; if (headers_pos > 1 && *(p - 1) == '\n') { if (headers_pos > 2 && *(p - 2) == '\r') { line_end = "\r\n"; nl_type = RSPAMD_TASK_NEWLINES_CRLF; } else { line_end = "\n"; nl_type = RSPAMD_TASK_NEWLINES_LF; } } else if (headers_pos > 1 && *(p - 1) == '\r') { line_end = "\r"; nl_type = RSPAMD_TASK_NEWLINES_CR; } added_headers = g_string_sized_new (127); if (result) { res = ucl_object_lookup (result, "action"); if (res) { action = ucl_object_tostring (res); } res = ucl_object_lookup (result, "score"); if (res) { score = ucl_object_todouble (res); } res = ucl_object_lookup (result, "required_score"); if (res) { required_score = ucl_object_todouble (res); } rspamd_action_from_str_rspamc (action, &act); if (act < METRIC_ACTION_GREYLIST) { is_spam = TRUE; } rspamd_printf_gstring (added_headers, "X-Spam-Scanner: %s%s", "rspamc " RVERSION, line_end); rspamd_printf_gstring (added_headers, "X-Spam-Scan-Time: %.3f%s", time, line_end); /* * TODO: add rmilter_headers support here */ if (is_spam) { rspamd_printf_gstring (added_headers, "X-Spam: yes%s", line_end); } rspamd_printf_gstring (added_headers, "X-Spam-Action: %s%s", action, line_end); rspamd_printf_gstring (added_headers, "X-Spam-Score: %.2f / %.2f%s", score, required_score, line_end); /* SA style stars header */ for (sc = scorebuf; sc < scorebuf + sizeof (scorebuf) - 1 && score > 0; sc ++, score -= 1.0) { *sc = '*'; } *sc = '\0'; rspamd_printf_gstring (added_headers, "X-Spam-Level: %s%s", scorebuf, line_end); /* Short description of all symbols */ symbuf = g_string_sized_new (64); syms = ucl_object_lookup (result, "symbols"); while (syms && (cur = ucl_object_iterate (syms, &it, true)) != NULL) { if (ucl_object_type (cur) == UCL_OBJECT) { rspamd_printf_gstring (symbuf, "%s,", ucl_object_key (cur)); } } /* Trim the last comma */ if (symbuf->str[symbuf->len - 1] == ',') { g_string_erase (symbuf, symbuf->len - 1, 1); } folded_symbuf = rspamd_header_value_fold ("X-Spam-Symbols", symbuf->str, 0, nl_type, ","); rspamd_printf_gstring (added_headers, "X-Spam-Symbols: %v%s", folded_symbuf, line_end); g_string_free (folded_symbuf, TRUE); g_string_free (symbuf, TRUE); res = ucl_object_lookup (result, "dkim-signature"); if (res && res->type == UCL_STRING) { rspamd_printf_gstring (added_headers, "DKIM-Signature: %s%s", ucl_object_tostring (res), line_end); } else if (res && res->type == UCL_ARRAY) { it = NULL; while ((cur = ucl_object_iterate (res, &it, true)) != NULL) { rspamd_printf_gstring (added_headers, "DKIM-Signature: %s%s", ucl_object_tostring (cur), line_end); } } if (json || raw || compact) { /* We also append json data as a specific header */ if (json) { json_header = ucl_object_emit (result, compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_JSON); } else { json_header = ucl_object_emit (result, compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_CONFIG); } json_header_encoded = rspamd_encode_base64_fold (json_header, strlen (json_header), 60, NULL, nl_type); free (json_header); rspamd_printf_gstring (added_headers, "X-Spam-Result: %s%s", json_header_encoded, line_end); g_free (json_header_encoded); } ucl_object_unref (result); } else { rspamd_printf_gstring (added_headers, "X-Spam-Scanner: %s%s", "rspamc " RVERSION, line_end); rspamd_printf_gstring (added_headers, "X-Spam-Scan-Time: %.3f%s", time, line_end); rspamd_printf_gstring (added_headers, "X-Spam-Error: %e%s", err, line_end); } /* Write message */ if (rspamd_fprintf (out, "%*s", (gint)headers_pos, input->str) == headers_pos) { if (rspamd_fprintf (out, "%v", added_headers) == (gint)added_headers->len) { rspamd_fprintf (out, "%s", input->str + headers_pos); } } g_string_free (added_headers, TRUE); } static void rspamc_client_execute_cmd (struct rspamc_command *cmd, ucl_object_t *result, GString *input, gdouble time, GError *err) { gchar **eargv; gint eargc, infd, outfd, errfd; GError *exec_err = NULL; GPid cld; FILE *out; gchar *ucl_out; if (!g_shell_parse_argv (execute, &eargc, &eargv, &err)) { rspamd_fprintf (stderr, "Cannot execute %s: %e", execute, err); g_error_free (err); return; } if (!g_spawn_async_with_pipes (NULL, eargv, NULL, G_SPAWN_SEARCH_PATH|G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL, &cld, &infd, &outfd, &errfd, &exec_err)) { rspamd_fprintf (stderr, "Cannot execute %s: %e", execute, exec_err); g_error_free (exec_err); exit (EXIT_FAILURE); } else { children = g_list_prepend (children, GSIZE_TO_POINTER (cld)); out = fdopen (infd, "w"); if (cmd->cmd == RSPAMC_COMMAND_SYMBOLS && mime_output && input) { rspamc_mime_output (out, result, input, time, err); } else if (result) { if (raw || cmd->command_output_func == NULL) { if (json) { ucl_out = ucl_object_emit (result, compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_JSON); } else { ucl_out = ucl_object_emit (result, compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_CONFIG); } rspamd_fprintf (out, "%s", ucl_out); free (ucl_out); } else { cmd->command_output_func (out, result); } ucl_object_unref (result); } else { rspamd_fprintf (out, "%e\n", err); } fflush (out); fclose (out); } g_strfreev (eargv); } static void rspamc_client_cb (struct rspamd_client_connection *conn, struct rspamd_http_message *msg, const gchar *name, ucl_object_t *result, GString *input, gpointer ud, gdouble start_time, gdouble send_time, const gchar *body, gsize bodylen, GError *err) { gchar *ucl_out; struct rspamc_callback_data *cbdata = (struct rspamc_callback_data *)ud; struct rspamc_command *cmd; FILE *out = stdout; gdouble finish = rspamd_get_ticks (FALSE), diff; cmd = cbdata->cmd; if (send_time > 0) { diff = finish - send_time; } else { diff = finish - start_time; } if (execute) { /* Pass all to the external command */ rspamc_client_execute_cmd (cmd, result, input, diff, err); } else { if (cmd->cmd == RSPAMC_COMMAND_SYMBOLS && mime_output && input) { if (body) { GString tmp; tmp.str = (char *)body; tmp.len = bodylen; rspamc_mime_output (out, result, &tmp, diff, err); } else { rspamc_mime_output (out, result, input, diff, err); } } else { if (cmd->need_input) { if (!compact) { rspamd_fprintf (out, "Results for file: %s (%.3f seconds)\n", cbdata->filename, diff); } } else { if (!compact) { rspamd_fprintf (out, "Results for command: %s (%.3f seconds)\n", cmd->name, diff); } } if (result != NULL) { if (headers && msg != NULL) { rspamc_output_headers (out, msg); } if (raw || cmd->command_output_func == NULL) { if (cmd->need_input) { ucl_object_insert_key (result, ucl_object_fromstring (cbdata->filename), "filename", 0, false); } ucl_object_insert_key (result, ucl_object_fromdouble (diff), "scan_time", 0, false); if (json) { ucl_out = ucl_object_emit (result, compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_JSON); } else { ucl_out = ucl_object_emit (result, compact ? UCL_EMIT_JSON_COMPACT : UCL_EMIT_CONFIG); } rspamd_fprintf (out, "%s", ucl_out); free (ucl_out); } else { cmd->command_output_func (out, result); } if (body) { rspamd_fprintf (out, "\nNew body:\n%*s\n", (int)bodylen, body); } ucl_object_unref (result); } else if (err != NULL) { rspamd_fprintf (out, "%s\n", err->message); if (json && msg != NULL) { const gchar *raw; gsize rawlen; raw = rspamd_http_message_get_body (msg, &rawlen); if (raw) { /* We can also output the resulting json */ rspamd_fprintf (out, "%*s\n", (gint)(rawlen - bodylen), raw); } } } rspamd_fprintf (out, "\n"); } fflush (out); } rspamd_client_destroy (conn); g_free (cbdata->filename); g_free (cbdata); if (err) { retcode = EXIT_FAILURE; } } static void rspamc_process_input (struct ev_loop *ev_base, struct rspamc_command *cmd, FILE *in, const gchar *name, GQueue *attrs) { struct rspamd_client_connection *conn; gchar *hostbuf = NULL, *p; guint16 port; GError *err = NULL; struct rspamc_callback_data *cbdata; if (connect_str[0] == '[') { p = strrchr (connect_str, ']'); if (p != NULL) { hostbuf = g_malloc (p - connect_str); rspamd_strlcpy (hostbuf, connect_str + 1, p - connect_str); p ++; } else { p = connect_str; } } else { p = connect_str; } p = strrchr (p, ':'); if (!hostbuf) { if (p != NULL) { hostbuf = g_malloc (p - connect_str + 1); rspamd_strlcpy (hostbuf, connect_str, p - connect_str + 1); } else { hostbuf = g_strdup (connect_str); } } if (p != NULL) { port = strtoul (p + 1, NULL, 10); } else { /* * If we connect to localhost, 127.0.0.1 or ::1, then try controller * port first */ if (strcmp (hostbuf, "localhost") == 0 || strcmp (hostbuf, "127.0.0.1") == 0 || strcmp (hostbuf, "::1") == 0 || strcmp (hostbuf, "[::1]") == 0) { port = DEFAULT_CONTROL_PORT; } else { port = cmd->is_controller ? DEFAULT_CONTROL_PORT : DEFAULT_PORT; } } conn = rspamd_client_init (http_ctx, ev_base, hostbuf, port, timeout, key); if (conn != NULL) { cbdata = g_malloc0 (sizeof (struct rspamc_callback_data)); cbdata->cmd = cmd; if (name) { cbdata->filename = g_strdup (name); } if (cmd->need_input) { rspamd_client_command (conn, cmd->path, attrs, in, rspamc_client_cb, cbdata, compressed, dictionary, cbdata->filename, &err); } else { rspamd_client_command (conn, cmd->path, attrs, NULL, rspamc_client_cb, cbdata, compressed, dictionary, cbdata->filename, &err); } } else { rspamd_fprintf (stderr, "cannot connect to %s\n", connect_str); exit (EXIT_FAILURE); } g_free (hostbuf); } static gsize rspamd_dirent_size (DIR * dirp) { goffset name_max; gsize name_end; #if defined(HAVE_FPATHCONF) && defined(HAVE_DIRFD) \ && defined(_PC_NAME_MAX) name_max = fpathconf (dirfd (dirp), _PC_NAME_MAX); # if defined(NAME_MAX) if (name_max == -1) { name_max = (NAME_MAX > 255) ? NAME_MAX : 255; } # else if (name_max == -1) { return (size_t)(-1); } # endif #else # if defined(NAME_MAX) name_max = (NAME_MAX > 255) ? NAME_MAX : 255; # else # error "buffer size for readdir_r cannot be determined" # endif #endif name_end = G_STRUCT_OFFSET (struct dirent, d_name) + name_max + 1; return (name_end > sizeof (struct dirent) ? name_end : sizeof(struct dirent)); } static void rspamc_process_dir (struct ev_loop *ev_base, struct rspamc_command *cmd, const gchar *name, GQueue *attrs) { DIR *d; GPatternSpec **ex; struct dirent *pentry; gint cur_req = 0, r; gchar fpath[PATH_MAX]; FILE *in; struct stat st; gboolean is_reg, is_dir, skip; d = opendir (name); if (d != NULL) { while ((pentry = readdir (d))!= NULL) { if (pentry->d_name[0] == '.') { continue; } r = rspamd_snprintf (fpath, sizeof (fpath), "%s%c%s", name, G_DIR_SEPARATOR, pentry->d_name); /* Check exclude */ ex = exclude_compiled; skip = FALSE; while (ex != NULL && *ex != NULL) { if (g_pattern_match (*ex, r, fpath, NULL)) { skip = TRUE; break; } ex ++; } if (skip) { continue; } is_reg = FALSE; is_dir = FALSE; #if (defined(_DIRENT_HAVE_D_TYPE) || defined(__APPLE__)) && defined(DT_UNKNOWN) if (pentry->d_type == DT_UNKNOWN) { /* Fallback to lstat */ if (lstat (fpath, &st) == -1) { rspamd_fprintf (stderr, "cannot stat file %s: %s\n", fpath, strerror (errno)); continue; } is_dir = S_ISDIR (st.st_mode); is_reg = S_ISREG (st.st_mode); } else { if (pentry->d_type == DT_REG) { is_reg = TRUE; } else if (pentry->d_type == DT_DIR) { is_dir = TRUE; } } #else if (lstat (fpath, &st) == -1) { rspamd_fprintf (stderr, "cannot stat file %s: %s\n", fpath, strerror (errno)); continue; } is_dir = S_ISDIR (st.st_mode); is_reg = S_ISREG (st.st_mode); #endif if (is_dir) { rspamc_process_dir (ev_base, cmd, fpath, attrs); continue; } else if (is_reg) { in = fopen (fpath, "r"); if (in == NULL) { rspamd_fprintf (stderr, "cannot open file %s: %s\n", fpath, strerror (errno)); continue; } rspamc_process_input (ev_base, cmd, in, fpath, attrs); cur_req++; fclose (in); if (cur_req >= max_requests) { cur_req = 0; /* Wait for completion */ ev_loop (ev_base, 0); } } } } else { fprintf (stderr, "cannot open directory %s: %s\n", name, strerror (errno)); exit (EXIT_FAILURE); } closedir (d); ev_loop (ev_base, 0); } static void rspamc_kwattr_free (gpointer p) { struct rspamd_http_client_header *h = (struct rspamd_http_client_header *)p; g_free (h->value); g_free (h->name); g_free (h); } gint main (gint argc, gchar **argv, gchar **env) { gint i, start_argc, cur_req = 0, res, ret, npatterns; GQueue *kwattrs; GList *cur; GPid cld; struct rspamc_command *cmd; FILE *in = NULL; struct ev_loop *event_loop; struct stat st; struct sigaction sigpipe_act; gchar **exclude_pattern; kwattrs = g_queue_new (); read_cmd_line (&argc, &argv); tty = isatty (STDOUT_FILENO); if (print_commands) { print_commands_list (); exit (EXIT_SUCCESS); } /* Deal with exclude patterns */ exclude_pattern = exclude_patterns; npatterns = 0; while (exclude_pattern && *exclude_pattern) { exclude_pattern ++; npatterns ++; } if (npatterns > 0) { exclude_compiled = g_malloc0 (sizeof (*exclude_compiled) * (npatterns + 1)); for (i = 0; i < npatterns; i ++) { exclude_compiled[i] = g_pattern_spec_new (exclude_patterns[i]); if (exclude_compiled[i] == NULL) { rspamd_fprintf (stderr, "Invalid glob pattern: %s\n", exclude_patterns[i]); exit (EXIT_FAILURE); } } } rspamd_init_libs (); event_loop = ev_loop_new (EVFLAG_SIGNALFD|EVBACKEND_ALL); struct rspamd_http_context_cfg http_config; memset (&http_config, 0, sizeof (http_config)); http_config.kp_cache_size_client = 32; http_config.kp_cache_size_server = 0; http_config.user_agent = user_agent; http_ctx = rspamd_http_context_create_config (&http_config, event_loop, NULL); /* Ignore sigpipe */ sigemptyset (&sigpipe_act.sa_mask); sigaddset (&sigpipe_act.sa_mask, SIGPIPE); sigpipe_act.sa_handler = SIG_IGN; sigpipe_act.sa_flags = 0; sigaction (SIGPIPE, &sigpipe_act, NULL); /* Now read other args from argc and argv */ if (argc == 1) { start_argc = argc; in = stdin; cmd = check_rspamc_command ("symbols"); } else if (argc == 2) { /* One argument is whether command or filename */ if ((cmd = check_rspamc_command (argv[1])) != NULL) { start_argc = argc; in = stdin; } else { cmd = check_rspamc_command ("symbols"); /* Symbols command */ start_argc = 1; } } else { if ((cmd = check_rspamc_command (argv[1])) != NULL) { /* In case of command read arguments starting from 2 */ if (cmd->cmd == RSPAMC_COMMAND_ADD_SYMBOL || cmd->cmd == RSPAMC_COMMAND_ADD_ACTION) { if (argc < 4 || argc > 5) { fprintf (stderr, "invalid arguments\n"); exit (EXIT_FAILURE); } if (argc == 5) { ADD_CLIENT_HEADER (kwattrs, "metric", argv[2]); ADD_CLIENT_HEADER (kwattrs, "name", argv[3]); ADD_CLIENT_HEADER (kwattrs, "value", argv[4]); } else { ADD_CLIENT_HEADER (kwattrs, "name", argv[2]); ADD_CLIENT_HEADER (kwattrs, "value", argv[3]); } start_argc = argc; } else { start_argc = 2; } } else { cmd = check_rspamc_command ("symbols"); start_argc = 1; } } add_options (kwattrs); if (start_argc == argc) { /* Do command without input or with stdin */ if (empty_input) { rspamc_process_input (event_loop, cmd, NULL, "empty", kwattrs); } else { rspamc_process_input (event_loop, cmd, in, "stdin", kwattrs); } } else { for (i = start_argc; i < argc; i++) { if (cmd->cmd == RSPAMC_COMMAND_FUZZY_DELHASH) { ADD_CLIENT_HEADER (kwattrs, "Hash", argv[i]); } else { if (stat (argv[i], &st) == -1) { fprintf (stderr, "cannot stat file %s\n", argv[i]); exit (EXIT_FAILURE); } if (S_ISDIR (st.st_mode)) { /* Directories are processed with a separate limit */ rspamc_process_dir (event_loop, cmd, argv[i], kwattrs); cur_req = 0; } else { in = fopen (argv[i], "r"); if (in == NULL) { fprintf (stderr, "cannot open file %s\n", argv[i]); exit (EXIT_FAILURE); } rspamc_process_input (event_loop, cmd, in, argv[i], kwattrs); cur_req++; fclose (in); } if (cur_req >= max_requests) { cur_req = 0; /* Wait for completion */ ev_loop (event_loop, 0); } } } if (cmd->cmd == RSPAMC_COMMAND_FUZZY_DELHASH) { rspamc_process_input (event_loop, cmd, NULL, "hashes", kwattrs); } } ev_loop (event_loop, 0); g_queue_free_full (kwattrs, rspamc_kwattr_free); /* Wait for children processes */ cur = children ? g_list_first (children) : NULL; ret = 0; while (cur) { cld = GPOINTER_TO_SIZE (cur->data); if (waitpid (cld, &res, 0) == -1) { fprintf (stderr, "Cannot wait for %d: %s", (gint)cld, strerror (errno)); ret = errno; } if (ret == 0) { /* Check return code */ if (WIFSIGNALED (res)) { ret = WTERMSIG (res); } else if (WIFEXITED (res)) { ret = WEXITSTATUS (res); } } cur = g_list_next (cur); } if (children != NULL) { g_list_free (children); } for (i = 0; i < npatterns; i ++) { g_pattern_spec_free (exclude_compiled[i]); } /* Mix retcode (return from Rspamd side) and ret (return from subprocess) */ return ret | retcode; }
25.990948
95
0.654184
[ "3d" ]
303874306d77c8ee34fb3c2e8c2018bebaa9dce5
1,625
h
C
Classes/SloppySwiper.h
jimmychenletstalk/SloppySwiper
37b824604cf37b154751ee64d9c0bbb908bed854
[ "MIT" ]
null
null
null
Classes/SloppySwiper.h
jimmychenletstalk/SloppySwiper
37b824604cf37b154751ee64d9c0bbb908bed854
[ "MIT" ]
null
null
null
Classes/SloppySwiper.h
jimmychenletstalk/SloppySwiper
37b824604cf37b154751ee64d9c0bbb908bed854
[ "MIT" ]
null
null
null
// // SloppySwiper.h // // Created by Arkadiusz Holko http://holko.pl on 29-05-14. // #import <UIKit/UIKit.h> /** * `SloppySwiperDelegate` is a protocol for treaking the behavior of the * `SloppySwiper` object. */ @class SloppySwiper; @protocol SloppySwiperDelegate <NSObject> @optional // Return NO when you don't want the TabBar to animate during swiping. (Default YES) - (BOOL)sloppySwiperShouldAnimateTabBar:(SloppySwiper *)swiper; // 0.0 means no dimming, 1.0 means pure black. Default is 0.1 - (CGFloat)sloppySwiperTransitionDimAmount:(SloppySwiper *)swiper;; @end #define D_NOTIFICATION_ADD_NO_SWIPER @"D_NOTIFICATION_ADD_NO_SWIPER" #define D_NOTIFICATION_REMOVE_NO_SWIPER @"D_NOTIFICATION_REMOVE_NO_SWIPER" @interface NoSwiperInfo:NSObject @property (nonatomic, strong) NSString *className; @property (nonatomic) CGRect viewRect; + (CGRect)defaultIgnoreFrameByView:(UIView *)view; @end /** * `SloppySwiper` is a class conforming to `UINavigationControllerDelegate` protocol that allows pan back gesture to be started from anywhere on the screen (not only from the left edge). */ @interface SloppySwiper : NSObject <UINavigationControllerDelegate> /// Gesture recognizer used to recognize swiping to the right. @property (weak, readonly, nonatomic) UIPanGestureRecognizer *panRecognizer; @property (nonatomic, weak) id<SloppySwiperDelegate> delegate; /// Designated initializer if the class isn't used from the Interface Builder. - (instancetype)initWithNavigationController:(UINavigationController *)navigationController; @property BOOL smallLocationCheck; @property BOOL disablePopCheck; @end
30.660377
187
0.786462
[ "object" ]
303a069ebead3c47fe4ca8c76ab1241c165c10db
865
h
C
GUI/Master/RootItem.h
jwillemsen/sidecar
941d9f3b84d05ca405df1444d4d9fd0bde03887f
[ "MIT" ]
null
null
null
GUI/Master/RootItem.h
jwillemsen/sidecar
941d9f3b84d05ca405df1444d4d9fd0bde03887f
[ "MIT" ]
null
null
null
GUI/Master/RootItem.h
jwillemsen/sidecar
941d9f3b84d05ca405df1444d4d9fd0bde03887f
[ "MIT" ]
null
null
null
#ifndef SIDECAR_GUI_ROOTITEM_H // -*- C++ -*- #define SIDECAR_GUI_ROOTITEM_H #include "CollectionItem.h" namespace SideCar { namespace GUI { namespace Master { class ConfigurationItem; /** The root item of a QTreeView view. A RootItem object has no parent, and all children are of class ConfigurationItem. */ class RootItem : public CollectionItem { Q_OBJECT using Super = CollectionItem; public: /** Constructor. */ RootItem() : Super() {} /** Locate a child item by its name. \param name the name to look forward \return found child or NULL if not found */ ConfigurationItem* find(const QString& name) const; ConfigurationItem* getChild(int index) const; private: void updateChildren() {} }; } // end namespace Master } // end namespace GUI } // end namespace SideCar /** \file */ #endif
18.804348
101
0.676301
[ "object" ]