content
stringlengths
12
2.72M
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef WEBKIT_GLUE_FLING_ANIMATOR_IMPL_ANDROID_H_ #define WEBKIT_GLUE_FLING_ANIMATOR_IMPL_ANDROID_H_ #include "base/android/scoped_java_ref.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebFloatPoint.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebGestureCurve.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebSize.h" #include "ui/gfx/point.h" #include "ui/gfx/point_f.h" namespace WebKit { class WebGestureCurveTarget; } namespace webkit_glue { class FlingAnimatorImpl : public WebKit::WebGestureCurve { public: FlingAnimatorImpl(); virtual ~FlingAnimatorImpl(); static FlingAnimatorImpl* CreateAndroidGestureCurve( const WebKit::WebFloatPoint& velocity, const WebKit::WebSize&); virtual bool apply(double time, WebKit::WebGestureCurveTarget* target); private: void StartFling(const gfx::PointF& velocity); // Returns true if the animation is not yet finished. bool UpdatePosition(); gfx::Point GetCurrentPosition(); virtual void CancelFling(); bool is_active_; // Java OverScroller instance and methods. base::android::ScopedJavaGlobalRef<jobject> java_scroller_; jmethodID fling_method_id_; jmethodID abort_method_id_; jmethodID compute_method_id_; jmethodID getX_method_id_; jmethodID getY_method_id_; gfx::Point last_position_; DISALLOW_COPY_AND_ASSIGN(FlingAnimatorImpl); }; } // namespace webkit_glue #endif // WEBKIT_GLUE_FLING_ANIMATOR_IMPL_ANDROID_H_
<gh_stars>1-10 #include <pack.h> int set_bindtype_idx(T_PkgType *tp,int bindtype,const char *choose,int cols,char *idx) { char *p,buf[100],*p1; int i=0; if(!tp) return -1; if(!choose) { T_PkgType *typ; for(typ=tp;typ->type>-1;typ++) { typ->bindtype = bindtype; i++; } } else { p=(char *)choose; while(*p) { int n; p=stptok(p,buf,sizeof(buf),",|"); if(*p) p++; p1=skipblk(buf); TRIM(p1); n=index_col(idx,cols,p1,tp); if(n>-1) { tp[n].bindtype = bindtype; i++; } } } return i; }
#pragma once #include <memory> #include "decoders/Decoder.h" class ChipSim; class DecodeVGM : public Decoder { #pragma pack(push, 1) struct Header { uint32_t ident; // "Vgm " uint32_t eofOffset; uint32_t version; uint32_t sn76489Clock; uint32_t ym2413Clock; uint32_t gd3Offset; uint32_t totalSamples; uint32_t loopOffset; uint32_t loopSamples; uint32_t rate; uint16_t sn76489Feedback; uint16_t sn76489ShiftReg; uint32_t ym2612Clock; uint32_t ym2151Clock; uint32_t vgmDataOffset; uint32_t segaPcmClock; uint32_t spcmInterface; uint32_t rf5c68Clock; uint32_t ym2203Clock; uint32_t ym2608Clock; uint32_t ym2610bClock; uint32_t ym3812Clock; uint32_t ym3526Clock; uint32_t y8950Clock; uint32_t ymf262Clock; uint32_t ymf278bClock; uint32_t ymf271Clock; uint32_t ymz280bClock; uint32_t rf5c164Clock; uint32_t pwmClock; uint32_t ay8910Clock; uint8_t ay8910Type; uint8_t ay8910Flags; uint8_t ym2203ay8910Flags; uint8_t ym2608ay8910Flags; uint8_t volumeModifier; uint8_t reserved1; uint8_t loopBase; uint8_t loopModifier; uint32_t gbDmgClock; uint32_t nesApuClock; uint32_t multiPcmClock; uint32_t upd7759Clock; uint32_t okim6258Clock; uint8_t okim6258Flags; uint8_t k054539Flags; uint8_t c140Flags; uint8_t reserved2; uint32_t oki6295Clock; uint32_t k051649Clock; uint32_t k054539Clock; uint32_t huc6280Clock; uint32_t c140Clock; uint32_t k053260Clock; uint32_t pokeyClock; uint32_t qsoundClock; uint32_t scspClock; uint32_t extraHeaderOffset; uint32_t wswanClock; uint32_t vsuClock; uint32_t saa1090Clock; uint32_t es5503Clock; uint32_t es5506Clock; uint8_t es5503Channels; uint8_t es5506Channels; uint8_t c352ClockDivider; uint8_t reserved3; uint32_t x1010Clock; uint32_t c352Clock; uint32_t ga20Clock; uint8_t reserved4[7 * 4]; }; #pragma pack(pop) public: bool Open(Stream& stream) override; bool Decode(Frame& frame) override; void Close(Stream& stream) override; private: int DecodeBlock(); private: uint8_t* m_data; uint8_t* m_dataPtr; int m_loop; int m_samplesPerFrame; int m_processedSamples; std::shared_ptr<ChipSim> m_chip; bool m_isTS; };
<filename>Source/RenderPasses/PhotonMapperHash/PhotonMapperHash.h /*************************************************************************** # Copyright (c) 2015-21, 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 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. **************************************************************************/ #pragma once #include "Falcor.h" #include "Utils/Sampling/SampleGenerator.h" #include <chrono> using namespace Falcor; class PhotonMapperHash : public RenderPass { public: using SharedPtr = std::shared_ptr<PhotonMapperHash>; static const Info kInfo; /** Create a new render pass object. \param[in] pRenderContext The render context. \param[in] dict Dictionary of serialized parameters. \return A new object, or an exception is thrown if creation failed. */ static SharedPtr create(RenderContext* pRenderContext = nullptr, const Dictionary& dict = {}); virtual Dictionary getScriptingDictionary() override; virtual RenderPassReflection reflect(const CompileData& compileData) override; virtual void compile(RenderContext* pContext, const CompileData& compileData) override; virtual void execute(RenderContext* pRenderContext, const RenderData& renderData) override; virtual void renderUI(Gui::Widgets& widget) override; virtual void setScene(RenderContext* pRenderContext, const Scene::SharedPtr& pScene) override; virtual bool onMouseEvent(const MouseEvent& mouseEvent) override { return false; } virtual bool onKeyEvent(const KeyboardEvent& keyEvent) override { return false; } enum class TextureFormat { _8Bit = 0u, _16Bit = 1u, _32Bit = 2u }; enum LightTexMode : uint32_t { power = 0u, area = 1u }; private: PhotonMapperHash(); /** Prepares Program Variables and binds the sample generator */ void prepareVars(); /** Prepares the hash buffers */ void prepareHashBuffer(); /** Prepares all buffers neede for the generate photon pass */ bool preparePhotonBuffers(); /** Prepares the info textures. Is called inside of preparePhotonBuffers. Can be called seperate for format changes */ void preparePhotonInfoTexture(); /** Creates the photon counter for caustic and global photon buffers */ void preparePhotonCounters(); /** Resets buffer and runtime vars. Used for scene change or number of photons change */ void resetPhotonMapper(); /** Applies the changes to the number of photons */ void changeNumPhotons(); /** Copies the photon counter to a cpu buffer */ void copyPhotonCounter(RenderContext* pRenderContext); /** Creates the Generate Photon pass, where the photons are shot through the scene and saved in an AABB and information buffer */ void generatePhotons(RenderContext* pRenderContext, const RenderData& renderData); /** Pass that collect the photons. It will shoot a infinit small ray at the current camera position and collect all photons. * The needed position etc. has to be provided by a gBuffer */ void collectPhotons(RenderContext* pRenderContext, const RenderData& renderData); /** Prepares the buffer that holds the seeds for the SampleGenerator */ void prepareRandomSeedBuffer(const uint2 screenDimensions); /** Prepares a light sample texture for the photon generate pass */ void createLightSampleTexture(RenderContext* pRenderContext); /** Gets the active emissive triangles from the light collection. * This is analogous to the function from LightCollection. It is here to prevent changes to the core of Falcor. * As this is done once it has no impact on performance and only a minimal impact on CPU-Memory */ void getActiveEmissiveTriangles(RenderContext* pRenderContext); /** Checks the timer. This is to stop the renderer for performance tests */ void checkTimer(); // Internal state Scene::SharedPtr mpScene; ///< Current scene. SampleGenerator::SharedPtr mpSampleGenerator; ///< GPU sample generator. //Constants const float kMinPhotonRadius = 0.0001f; ///< At radius 0.0001 Photons are still visible const float kCollectTMin = 0.000001f; ///<non configurable constant for collection for now const float kCollectTMax = 0.000002f; ///< non configurable constant for collection for now const uint kInfoTexHeight = 512; ///< Height of the info tex as it is too big for 1D tex //*************************************************************************** // Configuration //*************************************************************************** bool mUseStatisticProgressivePM = true; ///< Activate Statistically Progressive Photon Mapping(SPPM) float mSPPMAlphaGlobal = 0.7f; ///< Global Alpha for SPPM float mSPPMAlphaCaustic = 0.7f; ///< Caustic Alpha for SPPM float mCausticRadiusStart = 0.01f; ///< Start value for the caustic Radius float mGlobalRadiusStart = 0.05f; ///< Start value for the caustic Radius float mCausticRadius = 1.f; ///< Current Radius for caustic Photons float mGlobalRadius = 1.f; ///< Current Radius for global Photons float mSpecRoughCutoff = 0.5f; ///< If rougness is over this value interpret the material as diffuse bool mResetIterations = false; ///<Resets the iterations counter once bool mAlwaysResetIterations = false; ///<Resets the iteration counter every frame bool mNumPhotonsChanged = false; ///<If true buffers needs to be restarted and Number of photons needs to be changed bool mFitBuffersToPhotonShot = false; ///<Changes the buffer size to be around the number of photons shot bool mUseAlphaTest = true; ///<Uses alpha test (Generate) bool mAdjustShadingNormals = true; ///<Adjusts the shading normals (Generate) uint mNumBucketBits = 20; ///< 2^NumBucketBits is the total amount of possible buckets uint mNumPhotonsPerBucket = 12; ///< Max Photons per hash grid. uint mQuadraticProbeIterations = 10; ///< Number of quadartic probe iteratons per hash. // Generate only uint mMaxBounces = 10; ///< Depth of recursion (0 = none). float mRussianRoulette = 0.3f; ///< Probabilty that a Global photon is saved uint mNumPhotons = 2000000; ///< Number of Photons shot uint mNumPhotonsUI = mNumPhotons; ///< For UI. It is decopled from the runtime var because changes have to be confirmed uint mGlobalBufferSizeUI = mNumPhotons / 2; ///< Size of the Global Photon Buffer uint mCausticBufferSizeUI = mNumPhotons / 4; ///< Size of the Caustic Photon Buffer float mIntensityScalar = 1.0f; ///<Scales the intensity of emissive light sources // Collect only bool mDisableGlobalCollection = false; ///<Disabled the collection of global photons bool mDisableCausticCollection = false; ///<Disabled the collection of caustic photons bool mEnableStochasticCollection = true; ///<Enables/Disables Stochasic collection float mStochasticCollectProbability = 0.33f; ///< Probability for collection //******************************************************* // Runtime data //******************************************************* uint mFrameCount = 0; ///< Frame count since last Reset std::vector<uint> mPhotonCount = { 0,0 }; bool mOptionsChanged = false; bool mResetCS = true; bool mSetConstantBuffers = true; bool mResizePhotonBuffers = true; ///< If true resize the Photon Buffers bool mPhotonInfoFormatChanged = false; bool mRebuildAS = false; uint mInfoTexFormat = 1; uint mNumBuckets = 0; //Light std::vector<uint> mActiveEmissiveTriangles; bool mRebuildLightTex = false; LightTexMode mLightTexMode = LightTexMode::power; Texture::SharedPtr mLightSampleTex; Buffer::SharedPtr mPhotonsPerTriangle; const uint mMaxDispatchY = 512; uint mPGDispatchX = 0; uint mAnalyticEndIndex = 0; uint mNumLights = 0; float mAnalyticInvPdf = 0.0f; //Clock/Timer bool mUseTimer = false; //<Activates the timer bool mResetTimer = false; //<Resets the timer bool mTimerStopRenderer = false; //<Stops rendering (via return) double mTimerDurationSec = 60.0; //<How long the timer is running uint mTimerMaxIterations = 0; //< Stop at certain iterations double mCurrentElapsedTime = 0.0; //<Elapsed time for UI std::chrono::time_point<std::chrono::steady_clock> mTimerStartTime; //<Start time for the timer // Ray tracing program. struct RayTraceProgramHelper { RtProgram::SharedPtr pProgram; RtBindingTable::SharedPtr pBindingTable; RtProgramVars::SharedPtr pVars; static const RayTraceProgramHelper create() { RayTraceProgramHelper r; r.pProgram = nullptr; r.pBindingTable = nullptr; r.pVars = nullptr; return r; } }; ComputePass::SharedPtr mpCSCollect; ///<Collect pass collects the photons that where shot RayTraceProgramHelper mTracerGenerate; ///<Description for the Generate Photon pass // //Photon Buffers // //Struct for the buffers that are needed for global and caustic photons bool mPhotonBuffersReady = false; bool mTestInit = false; struct { Buffer::SharedPtr counter; Buffer::SharedPtr reset; Buffer::SharedPtr cpuCopy; }mPhotonCounterBuffer; struct PhotonBuffers { uint maxSize = 0; Texture::SharedPtr position; Texture::SharedPtr infoFlux; Texture::SharedPtr infoDir; }; Buffer::SharedPtr mpGlobalBuckets; Buffer::SharedPtr mpCausticBuckets; PhotonBuffers mCausticBuffers; ///< Buffers for the caustic photons PhotonBuffers mGlobalBuffers; ///< Buffers for the global photons Texture::SharedPtr mRandNumSeedBuffer; ///< Buffer for the random seeds };
#ifndef CIRCLE_H #define CIRCLE_H #include "./Shape.h" //定义派生类Circle - 圆形 - 公有方式继承自Shape class Circle: public Shape { private: double radius;//半径 public: Circle(double radius);//构造函数 virtual ~Circle();//析构函数 virtual double area() const;//定义虚函数,,相当于接口,求圆面积 }; #endif
#pragma once // RichODBC.h: interface for the RichODBC class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_RichODBC_H__9820EFEA_1038_4AB4_AB7E_997758F992C7__INCLUDED_) #define AFX_RichODBC_H__9820EFEA_1038_4AB4_AB7E_997758F992C7__INCLUDED_ #include <windows.h> #include <Sqltypes.h> #include <sql.h> #include <sqlext.h> #include <stdio.h> #include <time.h> #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #define MAX_QUERY_SIZE 3072 typedef VOID ( *pExternErrorHandler )( CHAR *pszQuery, LONG siParam1 ); class RichODBC { public: RichODBC(); ~RichODBC(); void InitODBC(); void ReleaseODBC(); VOID SetParam(int siParamNo, int siType, void *pData, int siDatasize, SQLSMALLINT siParamType = SQL_PARAM_INPUT, bool bNull = false); int GetData(int iColNo, int iType, void *pvData, long siDataSize); int GetData(int iColNo, void *pvData, long siDataSize); public: VOID GetResult(VOID *pvResult, long siDatasize); const INT64 GetRowcount(); const RETCODE GetRetcode() { return m_retcode; } VOID SetPooling(BOOL data) { IsPooling = data; } private: BOOL bReconnectStat; BOOL bCanFetchRow; BOOL bIsConnected; public: void inline SetReconnect(BOOL bStat) { bReconnectStat = bStat; } BOOL inline GetReconnectStat() { return bReconnectStat; } BOOL Connect(char *cDriver, char *cServer, char *cDatabase, char *cUserID, char *cPasswd); BOOL ConnectProcess(); BOOL Reconnect(); int Disconnect(); VOID Prepare(); int ExecSQL(); bool FetchData(); bool NextRecordSet(); int SetQuery(char *pszQuery); ////////////////////////////////////////////////////////// void BeginSP(char *pszQuery); void EndSP(); void SetParam(int siType, void *pData, int siDatasize, SQLSMALLINT siParamType = SQL_PARAM_INPUT, bool bNull = false); int GetData(void *pvData, long siDataSize = 0); /////////////////////////////////////////////////////////*/ BOOL CheckMDAC(wchar_t *cRequire); BOOL CheckError(SQLSMALLINT hType, SQLHANDLE handle,char* hint=NULL, HWND hwnd = NULL); BOOL IsSuccess(void); int m_siParamNo; int m_sicount; INT64 m_siParamSize; //protected: SQLHDBC m_hdbc; SQLHSTMT m_hstmt; SQLHENV m_henv; INT64 m_siRowcount; INT64 m_siNTS, m_siZero; INT64 m_siNULL; char m_cConnectionString[1024]; char *m_pszQuery; time_t m_tBEGINSP; time_t m_tEXECSP; time_t m_tFETCH; time_t m_tNEXTRECORDSET; pExternErrorHandler m_pExternErrorHandler; VOID SetExternErrorHandler( pExternErrorHandler pexternerrorhandler ); private: RETCODE m_retcode; long m_lbytes; BOOL IsPooling; private: FILE *m_Queryfp; char m_cErrQuery[8192]; void PrintErrMsg(char *msg); void PrintQuery(char *msg); void PrintParam(char *msg); void WriteQuery(); void WriteMSG(char* msg, size_t length); public: void MakeTime( TIMESTAMP_STRUCT& src, time_t& dest ); void MakeTIMESTAMP_STRUCT( time_t& src, TIMESTAMP_STRUCT& dest ); }; class XDBException { public: int code; char msg[4096]; XDBException():code(0) { msg[0]='\0'; }; XDBException(int c,const char * m):code(0) { UNREFERENCED_PARAMETER(c); strncpy_s( msg, m, sizeof(msg) ); //#ifndef TEST // Log & log=*Log::Instance(); // log("XDBException:(%d:%s)\n",code,msg); //#endif }; }; #endif // !defined(AFX_RichODBC_H__9820EFEA_1038_4AB4_AB7E_997758F992C7__INCLUDED_)
////////////////////////////////////////////////////////////////////// // This file was auto-generated by codelite's wxCrafter Plugin // wxCrafter project file: GDCppDialogs.wxcp // Do not modify this file by hand! ////////////////////////////////////////////////////////////////////// #ifndef IDE_DIALOGS_GDCPPDIALOGS_BASE_CLASSES_H #define IDE_DIALOGS_GDCPPDIALOGS_BASE_CLASSES_H #include <wx/settings.h> #include <wx/xrc/xmlres.h> #include <wx/xrc/xh_bmp.h> #include <wx/panel.h> #include <wx/artprov.h> #include <wx/aui/framemanager.h> #include <wx/aui/dockart.h> #include <wx/pen.h> #include <wx/aui/auibar.h> #include <map> #include <wx/menu.h> #include <wx/toolbar.h> #include <wx/notebook.h> #include <wx/imaglist.h> #include <wx/sizer.h> #include <wx/listctrl.h> #include <wx/treectrl.h> #include <wx/stattext.h> #include <wx/bmpbuttn.h> #include <wx/dialog.h> #include <wx/iconbndl.h> #include <wx/statbox.h> #include <wx/hyperlink.h> #include <wx/statline.h> #include <wx/textctrl.h> #include <wx/button.h> #if wxVERSION_NUMBER >= 2900 #include <wx/persist.h> #include <wx/persist/toplevel.h> #include <wx/persist/bookctrl.h> #include <wx/persist/treebook.h> #endif class DebuggerGUIBase : public wxPanel { public: enum { ID_ADD_OBJECT_TOOL = 1001, ID_ADD_VARG_TOOL = 1002, ID_ADD_VAR_TOOL = 1003, ID_DELETE_BT = 1004, ID_GENERAL_LIST_CTRL = 1005, ID_OBJECTS_TREE_CTRL = 1006, ID_OBJECT_LIST = 1007, ID_PAUSE_TOOL = 1008, ID_PLAY_TOOL = 1009, ID_STEP_TOOL = 1010, }; protected: wxAuiManager* m_auimgr; wxAuiToolBar* m_toolbar; wxNotebook* m_notebook; wxPanel* m_panel31; wxListCtrl* m_generalList; wxPanel* m_panel33; wxTreeCtrl* m_objectsTree; wxStaticText* m_staticText45; wxStaticText* m_objectName; wxBitmapButton* m_deleteBt; wxListCtrl* m_objectList; protected: public: wxAuiToolBar* GetToolbar() { return m_toolbar; } wxListCtrl* GetGeneralList() { return m_generalList; } wxPanel* GetPanel31() { return m_panel31; } wxTreeCtrl* GetObjectsTree() { return m_objectsTree; } wxStaticText* GetStaticText45() { return m_staticText45; } wxStaticText* GetObjectName() { return m_objectName; } wxBitmapButton* GetDeleteBt() { return m_deleteBt; } wxListCtrl* GetObjectList() { return m_objectList; } wxPanel* GetPanel33() { return m_panel33; } wxNotebook* GetNotebook() { return m_notebook; } wxAuiManager* GetAuimgr() { return m_auimgr; } DebuggerGUIBase(wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(500,300), long style = wxTAB_TRAVERSAL); virtual ~DebuggerGUIBase(); }; class AndroidExportDialogBase : public wxDialog { protected: wxStaticText* m_staticText55; wxStaticText* m_staticText85; wxHyperlinkCtrl* m_hyperLink57; wxStaticLine* m_staticLine59; wxStaticText* m_staticText61; wxTextCtrl* m_exportFolderTextCtrl; wxButton* m_browserButton; wxStdDialogButtonSizer* m_stdBtnSizer71; wxButton* m_okButton; wxButton* m_cancelButton; protected: virtual void OnHelpButtonClicked(wxHyperlinkEvent& event) { event.Skip(); } virtual void OnBrowseButtonClicked(wxCommandEvent& event) { event.Skip(); } public: wxStaticText* GetStaticText55() { return m_staticText55; } wxStaticText* GetStaticText85() { return m_staticText85; } wxHyperlinkCtrl* GetHyperLink57() { return m_hyperLink57; } wxStaticLine* GetStaticLine59() { return m_staticLine59; } wxStaticText* GetStaticText61() { return m_staticText61; } wxTextCtrl* GetExportFolderTextCtrl() { return m_exportFolderTextCtrl; } wxButton* GetBrowserButton() { return m_browserButton; } AndroidExportDialogBase(wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = _("Export to native Android"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(-1,-1), long style = wxDEFAULT_DIALOG_STYLE); virtual ~AndroidExportDialogBase(); }; #endif
#ifndef FUNCTIONS_H_ #define FUNCTIONS_H_ #include <ext/algorithm> #include <iterator> #include <set> #include <utility> #include <vector> namespace mt { namespace functions { /** * @brief A distance function object which calculates the <b>euclidean * distance</b> between two data objects representing coordinates. * @details Assumes that the data objects are same-sized sequences of numbers. * @see http://en.wikipedia.org/wiki/Euclidean_distance */ struct euclidean_distance { /** * @brief The operator that performs the calculation. */ template <typename Sequence> double operator()(const Sequence& data1, const Sequence& data2) const { double distance = 0; for(auto i1 = data1.begin(), i2 = data2.begin(); i1 != data1.end() && i2 != data2.end(); ++i1, ++i2) { double diff = *i1 - *i2; distance += diff * diff; } distance = sqrt(distance); return distance; } }; /** * @brief A promotion function object which randomly chooses two data objects * as promoted. */ struct random_promotion { /** * @brief The operator that performs the promotion. * @tparam Data The type of the data objects. * @tparam DistanceFunction The type of the function or function object used * to calculate the distance between two Data objects. * @return A pair with the promoted data objects. */ template <typename Data, typename DistanceFunction> std::pair<Data, Data> operator()(const std::set<Data>& data_objects, DistanceFunction& distance_function) const { std::vector<Data> promoted; random_sample_n(data_objects.begin(), data_objects.end(), inserter(promoted, promoted.begin()), 2); assert(promoted.size() == 2); return {promoted[0], promoted[1]}; } }; /** * @brief A partition function object which equally distributes the data objects * according to their distances to the promoted data objects. * @details The algorithm is roughly equivalent to this: * @code * data_objects := first_partition * first_partition := Empty * second_partition := Empty * Repeat until data_object is empty: * X := The object in data_objects which is the nearest to promoted.first * Remove X from data_object * Add X to first_partition * * Y := The object in data_objects which is the nearest to promoted.second * Remove Y from data_object * Add Y to second_partition * @endcode */ struct balanced_partition { /** * @brief The operator that performs the partition. * @tparam Data The type of the data objects. * @tparam DistanceFunction The type of the function or function object used * to calculate the distance between two @c Data * objects. * @param [in] promoted The promoted data objects. * @param [in,out] first_partition Initially, is the set containing all the * objects that must be partitioned. After * the partitioning, contains the objects * related to the first promoted data object, * which is @c promoted.first. * @param [out] second_partition Initially, is an empty set. After the * partitioning, contains the objects related * to the second promoted data object, which * is @c promoted.second. * @param [in] distance_function The distance function or function object. */ template <typename Data, typename DistanceFunction> void operator()(const std::pair<Data, Data>& promoted, std::set<Data>& first_partition, std::set<Data>& second_partition, DistanceFunction& distance_function ) const { std::vector<Data> queue1(first_partition.begin(), first_partition.end()); // Sort by distance to the first promoted data std::sort(queue1.begin(), queue1.end(), [&](const Data& data1, const Data& data2) { double distance1 = distance_function(data1, promoted.first); double distance2 = distance_function(data2, promoted.first); return distance1 < distance2; } ); std::vector<Data> queue2(first_partition.begin(), first_partition.end()); // Sort by distance to the second promoted data std::sort(queue2.begin(), queue2.end(), [&](const Data& data1, const Data& data2) { double distance1 = distance_function(data1, promoted.second); double distance2 = distance_function(data2, promoted.second); return distance1 < distance2; } ); first_partition.clear(); typename std::vector<Data>::iterator i1 = queue1.begin(); typename std::vector<Data>::iterator i2 = queue2.begin(); while(i1 != queue1.end() || i2 != queue2.end()) { while(i1 != queue1.end()) { Data& data = *i1; ++i1; if(second_partition.find(data) == second_partition.end()) { first_partition.insert(data); break; } } while(i2 != queue2.end()) { Data& data = *i2; ++i2; if(first_partition.find(data) == first_partition.end()) { second_partition.insert(data); break; } } } } }; /** * @brief A function object that defines a split function by composing a * promotion function and a partition function. * @tparam PromotionFunction The type of the function or function object which * implements a promotion function. * @tparam PartitionFunction The type of the function or function object which * implements a partition function. */ template <typename PromotionFunction, typename PartitionFunction> struct split_function { /** */ typedef PromotionFunction promotion_function_type; /** */ typedef PartitionFunction partition_function_type; PromotionFunction promotion_function; PartitionFunction partition_function; /** */ explicit split_function( PromotionFunction promotion_function = PromotionFunction(), PartitionFunction partition_function = PartitionFunction() ) : promotion_function(promotion_function), partition_function(partition_function) {} /** * @brief The operator that performs the split. * @tparam Data The type of the data objects. * @tparam DistanceFunction The type of the function or function object used * to calculate the distance between two @c Data * objects. * @param [in,out] first_partition Initially, is the set containing all the * objects that must be partitioned. After * the partitioning, contains the objects * related to the first promoted data object. * @param [out] second_partition Initially, is an empty set. After the * partitioning, contains the objects related * to the second promoted data object. * @param [in] distance_function The distance function or function object. * @return A pair with the promoted data objects. */ template <typename Data, typename DistanceFunction> std::pair<Data, Data> operator()( std::set<Data>& first_partition, std::set<Data>& second_partition, DistanceFunction& distance_function ) const { std::pair<Data, Data> promoted = promotion_function(first_partition, distance_function); partition_function(promoted, first_partition, second_partition, distance_function); return promoted; } }; template <typename Data, typename DistanceFunction> class cached_distance_function { public: explicit cached_distance_function(const DistanceFunction& distance_function) : distance_function(distance_function) {} double operator()(const Data& data1, const Data& data2) { typename CacheType::iterator i = cache.find(make_pair(data1, data2)); if(i != cache.end()) { return i->second; } i = cache.find(make_pair(data2, data1)); if(i != cache.end()) { return i->second; } // Not found in cache double distance = distance_function(data1, data2); // Store in cache cache.insert(make_pair(make_pair(data1, data2), distance)); cache.insert(make_pair(make_pair(data2, data1), distance)); return distance; } private: typedef std::map<std::pair<Data, Data>, double> CacheType; const DistanceFunction& distance_function; CacheType cache; }; } /* namespace functions */ } /* namespace mtree */ #endif /* FUNCTIONS_H_ */
<reponame>horance-liu/cub<filename>cub/algo/bound.h #ifndef H1BEBC79D_5BA8_1234_AD8C_94F820EC7D5B #define H1BEBC79D_5BA8_1234_AD8C_94F820EC7D5B #include <stddef.h> namespace cub { namespace details { template <typename T, bool IsLowBound> size_t bound(const T* array, size_t len, T key) { size_t low = 0; size_t high = len - 1; size_t mid = 0; if (key < array[low]) { return low; } if (key > array[high]) { return high; } while (low <= high) { mid = (low + high) >> 1; if (key == array[mid]) { return mid; } else if (key > array[mid]) { low = mid + 1; } else { high = mid - 1; } } return IsLowBound ? high : low; } } // namespace details template <typename T> size_t lower_bound(const T* array, size_t len, T key) { return details::bound<T, true>(array, len, key); } template <typename T> size_t upper_bound(const T* array, size_t len, T key) { return details::bound<T, false>(array, len, key); } } // namespace cub #endif
<reponame>mickaelcala/TNTbasic /******************** ***********************/ // // Player PRO 5.9 - DRIVER SOURCE CODE - // // Library Version 5.9 // // To use with MAD Library for Mac: Symantec, CodeWarrior and MPW // // <NAME> // 20 Micheli-Du-Crest // 1205 GENEVA // SWITZERLAND // // COPYRIGHT <NAME> 1996, 1997, 1998, 1999, 2000, 2001, 2002 // // Thank you for your interest in PlayerPRO ! // // FAX: (+41 22) 346 11 97 // PHONE: (+41 79) 203 74 62 // Internet: <EMAIL> // /******************** ***********************/ #include "FileUtils.h" #include <Script.h> extern void NSLog(CFStringRef format, ...); //TODO: migrate PlayerPRO away from FSSpec! //TODO: HSetVol isn't available in 64-bit code :( //TODO: Also, FSSpec is defined as UInt8 hidden[70] unsigned char* MYC2PStr( Ptr cStr) { long size = strlen( cStr); BlockMoveData( cStr, cStr + 1, strlen( cStr)); cStr[ 0] = size; return (unsigned char*) cStr; } void MYP2CStr( unsigned char *cStr) { long size = cStr[ 0]; BlockMoveData( cStr + 1, cStr, size); cStr[ size] = 0; } UNFILE iFileOpen(Ptr name) { UNFILE temp; OSErr iErr; FSRef Ref; FSSpec spec; HGetVol( NULL, &spec.vRefNum, &spec.parID); MYC2PStr( name); pStrcpy( spec.name, (unsigned char*) name); MYP2CStr((unsigned char*)name); iErr = FSpMakeFSRef(&spec, &Ref); if(iErr != noErr) return 0; Boolean UnusedBoolean, UnusedBoolean2; HFSUniStr255 whythis; FSGetDataForkName(&whythis); FSResolveAliasFile(&Ref, TRUE, &UnusedBoolean, &UnusedBoolean2); iErr = FSOpenFork(&Ref, whythis.length, whythis.unicode, fsCurPerm, &temp); if(iErr != noErr) return 0; else return temp; } long iGetEOF(UNFILE iFileRefI) { SInt64 curEOF; FSGetForkSize(iFileRefI, &curEOF); return curEOF; } OSErr iRead(long size, Ptr dest, UNFILE iFileRefI) { return FSReadFork(iFileRefI, fsAtMark, 0, size, dest, NULL); } OSErr iSeekCur(long size, UNFILE iFileRefI) { return FSSetForkPosition( iFileRefI, fsFromMark, size); } void iFileCreate(Ptr name, OSType type) { /* char *folderPath, *FileName; Boolean isFolder, unusedBool; OSStatus iErr; FSRef Ref; int slashCharPos = 0, nameLen, i, ii; FSCatalogInfo fileCat; FileInfo *fInfo = (FileInfo*)&fileCat.finderInfo; if(FSPathMakeRef((UInt8*)name, &Ref, NULL) == noErr) { FSDeleteObject(&Ref); } nameLen = strlen(name); for(i = 0; i > (nameLen); i++) { if(name[i] == '/') slashCharPos = i; } //TODO: use a better function folderPath = calloc((slashCharPos + 2), sizeof(char)); FileName = calloc((nameLen - slashCharPos + 2), sizeof(char)); for(i = 0; i == slashCharPos;i++) { folderPath[i] = name[i]; } for(i=slashCharPos+1, ii=0;i == nameLen;i++, ii++) { FileName[ii] = name[i]; FileName[ii+1] = '\0'; } // folderPath[slashCharPos+1] = '\0'; iErr = FSPathMakeRef((UInt8*)folderPath, &Ref, &isFolder); if(iErr != noErr) MyDebugStr(__LINE__, __FILE__, "Error creating FSRef"); if(isFolder == FALSE) NSLog(CFSTR("FSRef wasn't a folder. Ignoring, hoping it is an alias.")); iErr= FSResolveAliasFile(&Ref, TRUE, &isFolder, &unusedBool); if(iErr != noErr) MyDebugStr(__LINE__, __FILE__, "Error resolving Alias"); if(isFolder == FALSE) MyDebugStr(__LINE__, __FILE__, "FSRef wasn't a folder!"); //TODO: do NOT use CFString! CFStringRef UniCFSTR = CFStringCreateWithCString(kCFAllocatorDefault, FileName, CFStringGetSystemEncoding()); CFIndex UNIcharLen = CFStringGetLength(UniCFSTR); UniChar* UNICHARThing = calloc(UNIcharLen, sizeof(UniChar)); CFRange UNIRange; UNIRange.location = 0; UNIRange.length = UNIcharLen; CFStringGetCharacters(UniCFSTR, UNIRange, UNICHARThing); fInfo->fileType = type; fInfo->fileCreator = 'SNPL'; fInfo->finderFlags = 0; fInfo->location.h = 0; fInfo->location.v = 0; fInfo->reservedField = 0; FSCreateFileUnicode(&Ref, UNIcharLen, UNICHARThing, kFSCatInfoFinderInfo, &fileCat, NULL, NULL); CFRelease(UniCFSTR); free(folderPath); free(FileName); free(UNICHARThing); */ FSSpec spec; HGetVol( NULL, &spec.vRefNum, &spec.parID); MYC2PStr( name); pStrcpy( spec.name, (unsigned char*) name); FSpDelete( &spec); FSpCreate( &spec, 'SNPL', type, smSystemScript); MYP2CStr( (unsigned char*) name); } OSErr iWrite(long size, Ptr dest, UNFILE iFileRefI) { return FSWriteFork(iFileRefI, fsAtMark, 0, size, dest, NULL); } void iClose(UNFILE iFileRefI) { FSCloseFork(iFileRefI); } ///////////////////////////////// Ptr MADstrcpy( Ptr dst, const char* src) { // NSLog(CFSTR("MADstrcpy is depricated; just use strcpy")); long i = 0; do { dst[ i] = src[ i]; }while( src[ i++]); return dst; } //TODO: use system native strcmp? int MADstrcmp( const char *dst, const char* src) { long i = 0; do { if( dst[ i] != src[ i]) return -1; }while( src[ i++]); return 0; } EXP void OSType2Ptr( OSType type, Ptr str) { #ifdef __LITTLE_ENDIAN__ MOT32(&type); #endif BlockMoveData( &type, str, 4); str[ 4] = 0; } EXP OSType Ptr2OSType( char* str) { short i; OSType type; i = strlen( str); if( i > 4) i = 4; type = ' '; BlockMoveData( str, &type, i); #ifdef __LITTLE_ENDIAN__ MOT32(&type); #endif return type; }
// // IAPCell.h // ShopFolder // // Created by <NAME> on 2012/03/22. // Copyright (c) 2012年 CCTSAI. All rights reserved. // #import <UIKit/UIKit.h> @interface IAPCell : UITableViewCell { CGSize textLabelSize; } @property (nonatomic, assign) CGSize textLabelSize; @end
<reponame>ihowson/bulkem #ifndef BULKEM_H #define BULKEM_H // Do not include any R or CUDA headers in here; the R and CUDA stuff needs to be compiled separately. // To save time, we put a hard limit on the number of components that we can // fit. This limit can be removed if necessary. #define MAX_COMPONENTS 8 // TODO: Ditto for max observations. This limit really ought to be lifted; 10k obs isn't very large #define MAX_OBSERVATIONS 1000000 // This ought to work well for most modern machines (at least, as of 2015). // TODO: make it a parameter to the R interface #define NUM_THREADS 8 enum fit_result { FIT_NOT_ATTEMPTED = 0, // default; dataset has not been fit yet FIT_SUCCESS, FIT_FAILED // DID_NOT_CONVERGE, // OTHER }; typedef struct _invgauss_params_t { double mu; double lambda; double alpha; // mixing proportion } invgauss_params_t; typedef struct _dataset { // Before fitting, these fields are filled in double *data; int num_observations; // After fitting, these fields are filled in enum fit_result fr; double final_loglik; invgauss_params_t init_params[MAX_COMPONENTS]; // initial parameters used for the fit invgauss_params_t fit_params[MAX_COMPONENTS]; int num_iterations; // number of iterations used to produce the fit // TODO: return posterior probabilities } dataset; typedef struct _fit_params { dataset *datasets; int num_datasets; int num_components; double epsilon; int verbose; int random_inits; int max_iters; } fit_params; #ifdef __cplusplus extern "C" { #endif int bulkem_cuda(fit_params *fp); void stream_main(fit_params *fp); #ifdef __cplusplus } #endif #endif
<filename>wavebench-dag/include/core/math/vector-elemental-functions.h #ifndef __VECTOR_ELEMENTAL_FUNCTIONS_MATH_CORE_H__ #define __VECTOR_ELEMENTAL_FUNCTIONS_MATH_CORE_H__ #include "../macros/macros.h" #include "../meta/meta.h" #include "../types/types.h" #include "arithmetic.h" #include "elemental-functions.h" #include "vector-arithmetic.h" namespace __core__ { namespace __math__ { //****************************************************************************************************************************************************************************** //****************************************************************************************************************************************************************************** template <typename RVT=void,typename V=void,int N=0,uint AV=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>>,typename RET=basal_T<RT>> static inline __forceflatten__ __optimize__ __host_device__ RT __floor__(const Vector<V,N,AV>& v) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result[i]=__floor__(v(i));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result[i]=__floor__(v(i));)) #endif return result; } template <typename RVT=void,typename V=void,int N=0,uint AV=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>>,typename RET=basal_T<RT>> static inline __forceflatten__ __optimize__ __host_device__ RT __ceil__(const Vector<V,N,AV>& v) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result[i]=__ceil__(v(i));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result[i]=__ceil__(v(i));)) #endif return result; } //****************************************************************************************************************************************************************************** //****************************************************************************************************************************************************************************** template <typename RVT=void,typename V=void,int N=0,uint AV=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>>,typename RET=basal_T<RT>> static inline __forceflatten__ __optimize__ __host_device__ RT __abs__(const Vector<V,N,AV>& v) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result[i]=__abs__(v(i));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result[i]=__abs__(v(i));)) #endif return result; } template <typename RVT=void,typename V=void,int N=0,uint AV=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>>,typename RET=basal_T<RT>> static inline __forceflatten__ __optimize__ __host_device__ RT __sign__(const Vector<V,N,AV>& v) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result[i]=__sign__(v(i));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result[i]=__sign__(v(i));)) #endif return result; } //****************************************************************************************************************************************************************************** //****************************************************************************************************************************************************************************** template <typename RVT=void,typename V=void,int N=0,uint AV=0,typename RT=conditional_T<is_same_CE<void,RVT>(),V,RVT>,enable_IT<!is_vector_CE<RVT>()> = 0> static inline __forceflatten__ __optimize__ __host_device__ RT __max__(const Vector<V,N,AV>& v) { RT result=v(0); #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result=__max__(v(i),result);)) #else __unroll_cpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result=__max__(v(i),result);)) #endif return result; } template <typename RVT=void,typename V=void,typename U=void,int N=0,uint AV=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>,U>,typename RET=basal_T<RT>,enable_IT<!is_vector_CE<U>()> = 0> static inline __forceflatten__ __optimize__ __host_device__ RT __max__(const Vector<V,N,AV>& v,const U x) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const U),(RT& result,const Vector<V,N,AV>& v,const U x),(result,v,x),(result[i]=__max__(v(i),x);)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const U),(RT& result,const Vector<V,N,AV>& v,const U x),(result,v,x),(result[i]=__max__(v(i),x);)) #endif return result; } template <typename RVT=void,typename V=void,typename U=void,int N=0,uint AV=0,uint AU=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>,Vector<U,N,AU>>,typename RET=basal_T<RT>> static inline __forceflatten__ __optimize__ __host_device__ RT __max__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u),(result[i]=__max__(v(i),u(i));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u),(result[i]=__max__(v(i),u(i));)) #endif return result; } template <typename RVT=void,typename V=void,int N=0,uint AV=0,typename RT=conditional_T<is_same_CE<void,RVT>(),V,RVT>,enable_IT<!is_vector_CE<RVT>()> = 0> static inline __forceflatten__ __optimize__ __host_device__ RT __min__(const Vector<V,N,AV>& v) { RT result=v(0); #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result=__min__(v(i),result);)) #else __unroll_cpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&),(RT& result,const Vector<V,N,AV>& v),(result,v),(result=__min__(v(i),result);)) #endif return result; } template <typename RVT=void,typename V=void,typename U=void,int N=0,uint AV=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>,U>,typename RET=basal_T<RT>,enable_IT<!is_vector_CE<U>()> = 0> static inline __forceflatten__ __optimize__ __host_device__ RT __min__(const Vector<V,N,AV>& v,const U x) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const U),(RT& result,const Vector<V,N,AV>& v,const U x),(result,v,x),(result[i]=__min__(v(i),x);)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const U),(RT& result,const Vector<V,N,AV>& v,const U x),(result,v,x),(result[i]=__min__(v(i),x);)) #endif return result; } template <typename RVT=void,typename V=void,typename U=void,int N=0,uint AV=0,uint AU=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>,Vector<U,N,AU>>,typename RET=basal_T<RT>> static inline __forceflatten__ __optimize__ __host_device__ RT __min__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u),(result[i]=__min__(v(i),u(i));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u),(result[i]=__min__(v(i),u(i));)) #endif return result; } //****************************************************************************************************************************************************************************** //****************************************************************************************************************************************************************************** template <typename RVT=void,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,int N=0,uint AV=0,uint AU=0,typename RT=conditional_T<is_same_CE<void,RVT>(),higher_PT<V,U>,RVT>,enable_IT<!is_vector_CE<RVT>()> = 0> static inline __forceflatten__ __optimize__ __host_device__ RT __max_diff__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u) { RT result=__sub__<RM>(v(0),u(0)); #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u), (result=__max__(__sub__<RM>(v(i),u(i)),result);)) #else __unroll_cpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u), (result=__max__(__sub__<RM>(v(i),u(i)),result);)) #endif return result; } template <typename RVT=void,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,int N=0,uint AV=0,uint AU=0,typename RT=conditional_T<is_same_CE<void,RVT>(),higher_PT<V,U>,RVT>,enable_IT<!is_vector_CE<RVT>()> = 0> static inline __forceflatten__ __optimize__ __host_device__ RT __min_diff__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u) { RT result=__sub__<RM>(v(0),u(0)); #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u), (result=__min__(__sub__<RM>(v(i),u(i)),result);)) #else __unroll_cpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u), (result=__min__(__sub__<RM>(v(i),u(i)),result);)) #endif return result; } template <typename RVT=void,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,int N=0,uint AV=0,uint AU=0,typename RT=conditional_T<is_same_CE<void,RVT>(),higher_PT<V,U>,RVT>,enable_IT<!is_vector_CE<RVT>()> = 0> static inline __forceflatten__ __optimize__ __host_device__ RT __max_abs_diff__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u) { RT result=__sub__<RM>(v(0),u(0)); #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u), (result=__max__(__abs__(__sub__<RM>(v(i),u(i))),result);)) #else __unroll_cpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u), (result=__max__(__abs__(__sub__<RM>(v(i),u(i))),result);)) #endif return result; } template <typename RVT=void,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,int N=0,uint AV=0,uint AU=0,typename RT=conditional_T<is_same_CE<void,RVT>(),higher_PT<V,U>,RVT>,enable_IT<!is_vector_CE<RVT>()> = 0> static inline __forceflatten__ __optimize__ __host_device__ RT __min_abs_diff__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u) { RT result=__sub__<RM>(v(0),u(0)); #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u), (result=__min__(__abs__(__sub__<RM>(v(i),u(i))),result);)) #else __unroll_cpu__(int,i,1,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u), (result=__min__(__abs__(__sub__<RM>(v(i),u(i))),result);)) #endif return result; } //****************************************************************************************************************************************************************************** //****************************************************************************************************************************************************************************** template <typename RVT=void,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,int N=0,uint AV=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>,U>,typename RET=basal_T<RT>,enable_IT<!is_vector_CE<U>()> = 0> static inline __forceflatten__ __optimize__ __host_device__ RT __abs_add__(const Vector<V,N,AV>& v,const U x) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const U),(RT& result,const Vector<V,N,AV>& v,const U x),(result,v,x),(result[i]=__abs__(__add__<RM,V,U>(v(i),x));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const U),(RT& result,const Vector<V,N,AV>& v,const U x),(result,v,x),(result[i]=__abs__(__add__<RM,V,U>(v(i),x));)) #endif return result; } template <typename RVT=void,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,int N=0,uint AV=0,uint AU=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>,Vector<U,N,AU>>,typename RET=basal_T<RT>> static inline __forceflatten__ __optimize__ __host_device__ RT __abs_add__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u),(result[i]=__abs__(__add__<RM,V,U>(v(i),u(i)));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u),(result[i]=__abs__(__add__<RM,V,U>(v(i),u(i)));)) #endif return result; } template <typename RVT=void,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,typename X=void,int N=0,uint AV=0,uint AU=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>,Vector<U,N,AU>>,typename RET=basal_T<RT>> static inline __forceflatten__ __optimize__ __host_device__ RT __abs_add__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u,const X alpha) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&,const X),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u,const X alpha),(result,v,u,alpha), (result[i]=__abs__(__ma__<RM>(v(i),alpha,u(i)));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&,const X),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u,const X alpha),(result,v,u,alpha), (result[i]=__abs__(__ma__<RM>(v(i),alpha,u(i)));)) #endif return result; } template <typename RVT=void,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,typename X=void,typename Y=void,int N=0,uint AV=0,uint AU=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>,Vector<U,N,AU>>,typename RET=basal_T<RT>> static inline __forceflatten__ __optimize__ __host_device__ RT __abs_add__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u,const X alpha,const Y beta) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&,const X,const Y),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u,const X alpha,const Y beta),(result,v,u,alpha,beta), (result[i]=__abs__(__ma__<RM>(v(i),alpha,__mul__<RM>(u(i),beta)));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&,const X,const Y),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u,const X alpha,const Y beta),(result,v,u,alpha,beta), (result[i]=__abs__(__ma__<RM>(v(i),alpha,__mul__<RM>(u(i),beta)));)) #endif return result; } template <typename RVT=void,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,int N=0,uint AV=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>,U>,typename RET=basal_T<RT>,enable_IT<!is_vector_CE<U>()> = 0> static inline __forceflatten__ __optimize__ __host_device__ RT __abs_sub__(const Vector<V,N,AV>& v,const U x) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const U),(RT& result,const Vector<V,N,AV>& v,const U x),(result,v,x),(result[i]=__abs__(__sub__<RM,V,U>(v(i),x));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const U),(RT& result,const Vector<V,N,AV>& v,const U x),(result,v,x),(result[i]=__abs__(__sub__<RM,V,U>(v(i),x));)) #endif return result; } template <typename RVT=void,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,int N=0,uint AV=0,uint AU=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,N,AV>,Vector<U,N,AU>>,typename RET=basal_T<RT>> static inline __forceflatten__ __optimize__ __host_device__ RT __abs_sub__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u) { RT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u),(result[i]=__abs__(__sub__<RM,V,U>(v(i),u(i)));)) #else __unroll_cpu__(int,i,0,N,(RT&,const Vector<V,N,AV>&,const Vector<U,N,AU>&),(RT& result,const Vector<V,N,AV>& v,const Vector<U,N,AU>& u),(result,v,u),(result[i]=__abs__(__sub__<RM,V,U>(v(i),u(i)));)) #endif return result; } //****************************************************************************************************************************************************************************** //****************************************************************************************************************************************************************************** template <typename RVT=void,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,uint AV=0,uint AU=0,typename RT=__vprivate_arithmetic__::ReturnType<RVT,Vector<V,3,AV>,Vector<U,3,AU>>,typename RET=basal_T<RT>> static inline __forceflatten__ __optimize__ __host_device__ RT __cross__(const Vector<V,3,AV>& v,const Vector<U,3,AU>& u) { RT result; result[0]=__sub__<RM>(__mul__<RM>(v(1),u(2)),__mul__<RM>(v(2),u(1))); result[1]=__sub__<RM>(__mul__<RM>(v(2),u(0)),__mul__<RM>(v(0),u(2))); result[2]=__sub__<RM>(__mul__<RM>(v(0),u(1)),__mul__<RM>(v(1),u(0))); return result; } //****************************************************************************************************************************************************************************** //****************************************************************************************************************************************************************************** template <typename TRT=double,bool optimized=true,FastMathMode FM=__default_fast_math_mode__,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,int N=0,uint AV=0,uint AU=0,typename RT=conditional_T<is_same_CE<void,TRT>(),higher_PT<V,U>,TRT>> __forceinline__ __optimize__ __host_device__ __forceflatten__ RT __angle__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u) { return __acos__(__dot__<TRT,RM>(v,u)/(__mul__<RM>(__norm2__<TRT,optimized,FM,RM>(v),__norm2__<TRT,optimized,FM,RM>(u)))); } template <typename TRT=double,bool optimized=true,FastMathMode FM=__default_fast_math_mode__,RoundingMode RM=__default_rounding_mode__,typename V=void,typename U=void,int N=0,uint AV=0,uint AU=0,typename RT=conditional_T<is_same_CE<void,TRT>(),higher_PT<V,U>,TRT>> __forceinline__ __optimize__ __host_device__ __forceflatten__ RT __angle_cos__(const Vector<V,N,AV>& v,const Vector<U,N,AU>& u) { return __dot__<TRT,RM>(v,u)/(__mul__<RM>(__norm2__<TRT,optimized,FM,RM>(v),__norm2__<TRT,optimized,FM,RM>(u))); } //****************************************************************************************************************************************************************************** //****************************************************************************************************************************************************************************** template <typename RVT,RoundingMode RM=__default_rounding_mode__,typename V=void,int N=0,uint AV=0,typename RET=basal_T<RVT>,enable_IT<same_dimensions<RVT,Vector<V,N,AV>>()&&(!is_same_CE<RVT,Vector<V,N,AV>>())> = 0> static inline __forceflatten__ __optimize__ __host_device__ RVT __cast__(const Vector<V,N,AV>& v) { RVT result; #if defined(__CUDA_ARCH__) #ifdef __PRAGMA_UNROLL__ #pragma unroll #endif __unroll_gpu__(int,i,0,N,(RVT&,const Vector<V,N,AV>&),(RVT& result,const Vector<V,N,AV>& v),(result,v),(result[i]=__cast__<RET,RM>(v(i));)) #else __unroll_cpu__(int,i,0,N,(RVT&,const Vector<V,N,AV>&),(RVT& result,const Vector<V,N,AV>& v),(result,v),(result[i]=__cast__<RET,RM>(v(i));)) #endif return result; } template <typename RVT,RoundingMode RM=__default_rounding_mode__,typename V=void,int N=0,uint AV=0,typename RET=basal_T<RVT>,enable_IT<is_same_CE<RVT,Vector<V,N,AV>>()> = 0> static inline __forceflatten__ __optimize__ __host_device__ RVT __cast__(const Vector<V,N,AV>& v) { return v; } } } #endif
<reponame>alexcurylo/drawkit-touch<filename>DrawKitTouch/source/drawkit/Code/DKStyleRegistry.h // // DKStyleRegistry.h /// DrawKit ©2005-2008 Apptree.net // // Created by graham on 15/03/2008. /// /// This software is released subject to licensing conditions as detailed in DRAWKIT-LICENSING.TXT, which must accompany this source file. // // not in iPhone SDK, should be left to .pch ...alex //#import <Cocoa/Cocoa.h> #import "DKCategoryManager.h" @class DKStyle; // options flags - control behaviour when styles from a document are merged with the registry typedef enum { kDKIgnoreUnsharedStyles = ( 1 << 0 ), // compatibility with old registry - styles with sharing off are ignored kDKReplaceExistingStyles = ( 1 << 1 ), // styles passed in replace those with the same key (doc -> reg) kDKReturnExistingStyles = ( 1 << 2 ), // styles in reg with the same keys are returned (reg -> doc) kDKAddStylesAsNewVersions = ( 1 << 3 ) // styles with the same keys are copied and registered again (reg || doc) } DKStyleMergeOptions; // values you can test for in result of compareStylesInSet: enum { kDKStyleNotRegistered = 0, kDKStyleIsOlder = 1, kDKStyleUnchanged = 2, kDKStyleIsNewer = 3 }; // class: @interface DKStyleRegistry : DKCategoryManager // retrieving the registry and styles + (DKStyleRegistry*) sharedStyleRegistry; + (DKStyle*) styleForKey:(NSString*) styleID; + (DKStyle*) styleForKeyAddingToRecentlyUsed:(NSString*) styleID; // registering a style + (void) registerStyle:(DKStyle*) aStyle; + (void) registerStyle:(DKStyle*) aStyle inCategories:(NSArray*) styleCategories; + (void) registerStylesFromArray:(NSArray*) styles inCategories:(NSArray*) styleCategories; + (void) registerStylesFromArray:(NSArray*) styles inCategories:(NSArray*) styleCategories ignoringDuplicateNames:(BOOL) ignoreDupes; + (void) unregisterStyle:(DKStyle*) aStyle; + (void) setNeedsUIUpdate; + (void) setStyleNotificationsEnabled:(BOOL) enable; // merging sets of styles read in with a document + (NSSet*) mergeStyles:(NSSet*) styles inCategories:(NSArray*) styleCategories options:(DKStyleMergeOptions) options mergeDelegate:(id) aDel; + (NSDictionary*) compareStylesInSet:(NSSet*) styles; // high-level data access + (NSArray*) registeredStyleKeys; + (NSData*) registeredStylesData; + (void) saveDefaults; + (void) loadDefaults; + (void) resetRegistry; #ifndef TARGET_OS_IPHONE + (void) registerSolidColourFillsFromListNamed:(NSString*) name asCategory:(NSString*) catName; + (void) registerSolidColourStrokesFromListNamed:(NSString*) name asCategory:(NSString*) catName; #endif TARGET_OS_IPHONE + (void) setShouldNotAddDKDefaultCategory:(BOOL) noDKDefaults; // getting a fully-managed menu for all styles, organised by category: #ifndef TARGET_OS_IPHONE + (NSMenu*) managedStylesMenuWithItemTarget:(id) target itemAction:(SEL) selector; #endif TARGET_OS_IPHONE // low-level instance methods - (NSString*) styleNameForKey:(NSString*) styleID; - (DKStyle*) styleForKey:(NSString*) styleID; - (NSSet*) stylesInCategories:(NSArray*) cats; - (NSString*) uniqueNameForName:(NSString*) name; - (NSArray*) styleNames; - (NSArray*) styleNamesInCategory:(NSString*) catName; - (BOOL) writeToFile:(NSString*) path atomically:(BOOL) atom; - (BOOL) readFromFile:(NSString*) path mergeOptions:(DKStyleMergeOptions) options mergeDelegate:(id) aDel; - (DKStyle*) mergeFromStyle:(DKStyle*) aStyle mergeDelegate:(id) aDel; - (void) removeAllStyles; - (void) setNeedsUIUpdate; - (void) styleDidChange:(NSNotification*) note; #ifndef TARGET_OS_IPHONE - (NSMenu*) managedStylesMenuWithItemTarget:(id) target itemAction:(SEL) selector; #endif TARGET_OS_IPHONE @end // default registry category names: extern NSString* kDKStyleLibraryStylesCategory; extern NSString* kDKStyleTemporaryDocumentCategory; extern NSString* kDKStyleRegistryDKDefaultsCategory; extern NSString* kDKStyleRegistryTextStylesCategory; // notifications extern NSString* kDKStyleRegistryDidFlagPossibleUIChange; extern NSString* kDKStyleWasRegisteredNotification; extern NSString* kDKStyleWasRemovedFromRegistryNotification; extern NSString* kDKStyleWasEditedWhileRegisteredNotification; // delegate informal protocol allows the delegate to decide which of a pair of styles should be used @interface NSObject (DKStyleRegistryDelegate) - (DKStyle*) registry:(DKStyleRegistry*) reg shouldReplaceStyle:(DKStyle*) regStyle withStyle:(DKStyle*) docStyle; @end @interface NSObject (StyleRegistrySubstitution) - (DKStyleRegistry*) applicationWillReturnStyleRegistry; @end /* The style registry is a singleton category manager instance that consolidates styles from a variety of sources into a single app-wide "database" of styles, organised into categories. Styles can come from these sources: 1. The application defaults, if the app is launched with no library preferences available (i.e. first run). 2. The styles library, which is the complete registry saved to disk (user prefs) at quit time. 3. A document, when it is opened. 4. A separate file containing just styles. 5. A new style being created and registered by the user as the app is used. ------------------------------------------------------------------------------------------------------------------------------------------------- The point of the registry is twofold: A. It permits the construction of a UI for accessing pre-built styles and applying them to objects in a drawing. By organising styles into categories, potentially large number of styles may be managed effectively. B. It tracks styles across any number of documents as they are created. For example if a document uses a particular registered style, when that document is reopened at a later date, the style can be recognised and linked to the same style in the registry. If the style has changed in the meantime so that there is a difference between the saved style and the currently registered version, the user can be offered the option to update the style in the document to match the registry, update the registry to match the document, or to re-register the style as a new version. Note the registry is not mandatory - an app using DK can use styles without registering them if it wishes. The advantage of the registry is that it permits styles to persist and be tracked across multiple documents, saving the user from having to redefine styles for every new graphic. ------------------------------------------------------------------------------------------------------------------------------------------------- In order for the registry to uniquely and positively identify a style, its unique ID is used as its key. The unique ID is assigned when the style first comes into existence and cannot be changed. It is a string representation of a UUID so is guaranteed unique. UUID's are not very user friendly and should never be exposed by an application's user interface. Thus a style also has an ordinary descriptive name which can be displayed in the UI. Such names are not guaranteed to be unique however, as the user is free to enter whatever name they wish. When a style is first registered the name may be changed to avoid a collision with an already registered style having the same name - this is done by appending 1, 2, 3 etc until the name doesn't collide. However this is just done to disambiguate the style for the user - it is not intended to guarantee uniqueness so that the name can be used as a key to the object. A user interface will want to use the ordinary names, but internally must be set up to use the unique ID or the object itself to avoid any confusion as to which style is actually being referred to. For example a menu of available styles could use the UUID or the object as the represented object of the menu item. DO NOT USE THE ORDINARY NAME AS A KEY. ------------------------------------------------------------------------------------------------------------------------------------------------- Locking. Styles in the registry are usually locked. This is to prevent accidental alteration of a style that may be being used across many documents. When a style is added to the registry, it should be unlocked (because the name might need to be automatically changed) but the registry will lock the style upon a successful operation. Styles in a document. Styles used in a document may or may not be registered. A user may never register a style, but still have many styles defined in a document. Such styles work normally and can be copied and pasted and shared between objects if set to do so - use of styles is not dependent in any way upon the registry. When the document is saved, a flag as to whether the style was registered or not is saved with it. When the document is opened again later, such flagged styles will be optionally reconnected to the style registry so that the actual style used is always the registered style, so if the style is updated, existing documents are offered the opportunity to use the updated version. As well as any user-defined categories, documents may wish to create a temporary category using the document's name which gives the user a way to quickly discover the complete set of registered styles used in a document. The category should be removed when the document is closed. DKDrawDocument implements this behaviour by default, so if your document class is based on it, your app can get this feature for free. ------------------------------------------------------------------------------------------------------------------------------------------------- Registering a style. The style registry performs the following steps: 1. It checks that the style is not already registered. If it is, it does no more. 2. It checks that the style is unlocked. If not, an exception is thrown. 3. It resolves the style's name so that there are no collisions with any existing style's name, and changes the style's name if needed. 4. It creates any new categories as requested (depends on the particular method used to register the style). If no specific categories are requested, the style is added to the default category. 5. It adds the style to the registry using its unique ID as the key. 6. It locks the style. ------------------------------------------------------------------------------------------------------------------------------------------------- Cut/Paste: cut and paste of styles works independently of the registry, including dealing with shared styles. See DKStyle for more info. */
<reponame>martmists-gh/BDSP #pragma once #include "il2cpp.h" bool FieldMistWork__CheckMistWeather (const MethodInfo* method_info); bool FieldMistWork__AvailableKiribarai (const MethodInfo* method_info); EnvironmentSettings_o* FieldMistWork__GetCurrentSetting (FieldMistWork_o* __this, const MethodInfo* method_info); bool FieldMistWork__get_IsEnable (FieldMistWork_o* __this, const MethodInfo* method_info); void FieldMistWork__Setup (FieldMistWork_o* __this, const MethodInfo* method_info); EnvironmentSettings_o* FieldMistWork__GetBaseSetting (FieldMistWork_o* __this, int32_t zoneId, const MethodInfo* method_info); void FieldMistWork__Update (FieldMistWork_o* __this, float deltaTime, const MethodInfo* method_info); void FieldMistWork__ChangeMist (FieldMistWork_o* __this, float target, float time, const MethodInfo* method_info); void FieldMistWork__CalcCurrentSetting (FieldMistWork_o* __this, const MethodInfo* method_info); void FieldMistWork__BlendSetting (FieldMistWork_o* __this, EnvironmentSettings_Parameters_o* paramA, EnvironmentSettings_Parameters_o* paramB, float weight, EnvironmentSettings_Parameters_o* refOutParam, const MethodInfo* method_info); void FieldMistWork__CreateMistEffectSetting (FieldMistWork_o* __this, const MethodInfo* method_info); void FieldMistWork__OverrideParameter (FieldMistWork_o* __this, EnvironmentSettings_Parameters_o* param, int32_t paramHeadIndex, const MethodInfo* method_info); void FieldMistWork___ctor (FieldMistWork_o* __this, const MethodInfo* method_info); float FieldMistWork___OverrideParameter_g__Get_15_0 (FieldMistWork___c__DisplayClass15_0_o* , const MethodInfo* method_info);
<reponame>daidi-double/_new_YWB<filename>YuWa/YuWa/Foundation/Custom Category/UserSession.h<gh_stars>0 // // UserSession.h // NewVipxox // // Created by 黄佳峰 on 16/8/31. // Copyright © 2016年 黄蜂大魔王. All rights reserved. // #import <Foundation/Foundation.h> @interface UserSession : NSObject @property (nonatomic,assign)NSInteger uid;//uid @property (nonatomic,copy)NSString * token; //用户登录后标识 @property (nonatomic,copy)NSString * account; //账户 @property (nonatomic,copy)NSString * password; //密码 @property (nonatomic,copy)NSString * hxPassword; //环信密码 @property (nonatomic,copy)NSString * inviteID; //邀请ID @property (nonatomic,copy)NSString * invite_code;//邀请码 @property (nonatomic,copy)NSString * logo;//头像 @property (nonatomic,copy)NSString * nickName;//昵称 @property (nonatomic,copy)NSString * sex;//性别 @property (nonatomic,copy)NSString * birthDay;//生日 @property (nonatomic,copy)NSString * local; //常驻地 @property (nonatomic,copy)NSString * personality; //个人签名 @property (nonatomic,copy)NSString * businessAgreement;//商务会员协议 @property (nonatomic,copy)NSString * agreement;//用户协议 @property (nonatomic,copy)NSString * attentionCount;//关注数 @property (nonatomic,copy)NSString * fans;//粉丝 @property (nonatomic,copy)NSString * praised;//被赞数 @property (nonatomic,copy)NSString * collected;//被收藏 @property (nonatomic,copy)NSString * aldumCount; //专辑个数 @property (nonatomic,copy)NSString * money; //钱 @property (nonatomic,copy)NSString * last_login_time; @property (nonatomic,copy)NSString * reg_time; @property (nonatomic,copy)NSString * status; @property (nonatomic,copy)NSString * email; @property (nonatomic,copy)NSString * sale_id; //note_nums album_nums comment_nums @property(nonatomic,strong)NSString*note_nums; //多少条笔记 @property(nonatomic,strong)NSString*album_nums; //多少个专辑 @property(nonatomic,strong)NSString*comment_nums; //多少条评论 @property(nonatomic,strong)NSString*today_money; //今日收益 今天到登录为止时候的介绍分红和商务分红相加的钱(不算积分分红)7天后才会结算这部分钱 @property (nonatomic,strong)NSNumber*isVIP;//是否是会员 1普通用户2销售 没有3商家了移除 @property (nonatomic,strong)NSString * bankName;//记录上次提现的银行卡 @property (nonatomic,strong)NSString * bankCard;//记录上次提现的银行卡号 //@property(nonatomic,copy)NSString * currency; //货币 //已经登录 @property(nonatomic,assign)BOOL isLogin; //是否登录 (这个要自己给他) @property (nonatomic,assign)NSInteger baobaoLV; //雨娃宝宝等级 @property (nonatomic,assign)NSInteger baobaoEXP; //宝宝的经验 @property (nonatomic,assign)NSInteger baobaoNeedEXP; //宝宝升级需要的经验 //记录环信是否登录成功,成功是 yes 失败是NO; @property (nonatomic, assign) BOOL isLoginHX; +(UserSession*)instance; //创建单例 +(void)clearUser; //退出登录 删除数据 + (void)saveUserLoginWithAccount:(NSString *)account withPassword:(NSString *)password; //save login data + (void)saveUserInfoWithDic:(NSDictionary *)dataDic;//save user data + (void)autoLoginRequestWithPragram:(NSDictionary *)pragram; @end
<reponame>ssathy2/Hakken // // DDDRightNavigationView.h // Hakken // // Created by sathyam on 3/31/15. // Copyright (c) 2015 dotdotdot. All rights reserved. // #import <UIKit/UIKit.h> #import "UIView+Utility.h" @class DDDRightNavigationView; typedef void(^ViewAnimationBlock)(DDDRightNavigationView *navigationView); @interface DDDRightNavigationView : UIControl @property (weak, nonatomic) IBOutlet UILabel *numberLabel; // sets the number of the navigation view with any custom animations. If the 'animated' param is YES but 'animationBlock' is nil then a default spring animation will be used. - (void)setNumber:(NSInteger)number animated:(BOOL)animated withCustomAnimations:(ViewAnimationBlock)animationBlock; - (void)setNumberViewHidden:(BOOL)hidden animated:(BOOL)animated; @end
#include <config.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <netcdf.h> #define SYSCMD "ncgen -o %s %s" #define SYSCMD2 "ncgen -v 2 -o %s %s" #define LAT "lat" #define LON "lon" #define LAH "lah" #define LOH "loh" #ifndef DEBUG #define DEBUG 0 #endif #ifdef FORTRANCAPS #define read_cdf_static READ_CDF_STATIC #define write_cdf_static WRITE_CDF_STATIC #endif #ifdef FORTRANDOUBLEUNDERSCORE #define cdf_update_stat cdf_update_stat__ #define free_static_malloc free_static_malloc__ #define cdf_wrt_hdr_stat cdf_wrt_hdr_stat__ #define write_cdf_static write_cdf_static__ #define cdf_retr_grid_stat cdf_retr_grid_stat__ #define cdf_retr_hdr_stat cdf_retr_hdr_stat__ #define read_cdf_static read_cdf_static__ #define open_cdf open_cdf__ #define dim_size_v3 dim_size_v3__ #define nstrncpy nstrncpy__ #define fstrncpy fstrncpy__ #endif #ifdef FORTRANUNDERSCORE #define cdf_update_stat cdf_update_stat_ #define free_static_malloc free_static_malloc_ #define cdf_wrt_hdr_stat cdf_wrt_hdr_stat_ #define write_cdf_static write_cdf_static_ #define cdf_retr_grid_stat cdf_retr_grid_stat_ #define cdf_retr_hdr_stat cdf_retr_hdr_stat_ #define read_cdf_static read_cdf_static_ #define open_cdf open_cdf_ #define dim_size_v3 dim_size_v3_ #define nstrncpy nstrncpy_ #define fstrncpy fstrncpy_ #endif #if(SIZEOF_SHORT==4) #define fint4 short #elif(SIZEOF_INT==4) #define fint4 int #elif(SIZEOF_LONG==4) #define fint4 long #endif /***************************************************************************** * CDF_UPDATE_STAT * Category Product Management * Group General Purpose Database * Module Update the LAPS netCDF static file * Purpose To coordinate the writing of static info into * the appropriate netCDF file: find the * appropriate location to write the grid, * and call the routine that does the writing. * * Designer/Programmer : <NAME> * Modifications : original 9/5/90 * adapted for new WRITELAPSDATA 1/93 <NAME> * adapted from CDF_UPDATE_LAPS for new * WRT_LAPS_STATIC 4/93 <NAME> * * Input : * s_field A character string identifying the field: * lat latitude of grid point * lon longitude of grid point * avg average elev MSL of grid box * std std dev of elev's in box * env avg + std * zin avg converted to mb pressure, * then mapped 1100=0 to 100=20 * gptr A pointer to the grid (including product and data * headers). * Output : * None * Globals : * NC_WRITE A flag used to open the netCDF file for writing * Returns : * 0 if successful * -1 if an error occurs ***************************************************************************/ #ifdef __STDC__ int cdf_update_stat (int i_cdfid,int i_varid, char *s_field,void *gptr, char *commnt, char *comm_ptr) #else int cdf_update_stat (i_cdfid, i_varid, s_field, gptr, commnt, comm_ptr) int i_cdfid; int i_varid; char *s_field; void *gptr; char *commnt; char *comm_ptr; #endif { int i_status, i_comid; long start[4], count[4], start_c[3], count_c[3]; if(DEBUG==1) printf( "cdf_update_stat:grid name = %s\n", s_field); /* turn off the error handling done by the netCDF routines */ ncopts = NC_VERBOSE; /* get the x and y dimension sizes */ count[0] = 1; count[1] = 1; count[2] = dim_size_v3 (i_cdfid, "y"); count[3] = dim_size_v3 (i_cdfid, "x"); /* construct the arrays needed by the netcdf write routine */ start[0] = 0; start[1] = 0; start[2] = 0; start[3] = 0; start_c[0] = 0; start_c[1] = 0; start_c[2] = 0; count_c[0] = 1; count_c[1] = 1; count_c[2] = strlen(comm_ptr); /* get the variable ids */ if(DEBUG==1) printf( "Data variable name = %s\n", s_field); if ((i_comid = ncvarid (i_cdfid, commnt)) == (-1)) return -1; /* write the grid to the netcdf file */ i_status = ncvarput (i_cdfid, i_varid, (const long *)start, (const long *)count, (void *)gptr); if (i_status == (-1)) { if(DEBUG==1) printf( "1 cdf_update_stat: error during cdf write %d %d\n",i_cdfid,i_varid); return -1; } else { i_status = ncvarput (i_cdfid, i_comid, (const long *)start_c, (const long *)count_c, (void *)comm_ptr); if (i_status == (-1)){ if(DEBUG==1) printf( "2 cdf_update_stat: error during cdf write\n"); }else{ if(DEBUG==1) printf( "cdf_update_stat: cdf write ok\n"); } } return i_status; } /************************************************************************* * FREE_STATIC_MALLOC * Category Product Management * Group General Purpose Database * Module Write Static Grid data * Purpose Frees memory mallocd within write_cdf_static * * Designer/Programmer : <NAME> * Modifications : original 7/97 * * Input: * prefix String variable mallocd in write_cdf_static * comm_var String variable mallocd in write_cdf_static * model String variable mallocd in write_cdf_static * asctime String variable mallocd in write_cdf_static * var String variable mallocd in write_cdf_static * comment String variable mallocd in write_cdf_static * fname String variable mallocd in write_cdf_static * Output: * none * Globals: * none * Returns: * none *****************************************************************************/ #ifdef __STDC__ void free_static_malloc(char *prefix, char *comm_var, char *model, char *asctime, char *var, char *comment, char *units, char *fname) #else void free_static_malloc(prefix, comm_var, model, asctime, var, comment, units, fname) char *prefix; char *comm_var; char *model; char *asctime; char *var; char *comment; char *units; char *fname; #endif { if(prefix != NULL) free(prefix); if(comm_var != NULL) free(comm_var); if (model != NULL) free(model); if(asctime != NULL) free(asctime); if(var != NULL) free(var); if(comment != NULL) free(comment); if(units != NULL) free(units); if(fname != NULL) free(fname); return; } /************************************************************************* * CDF_WRT_HDR_STAT * Category Product Management * Group General Purpose Database * Module Write header data * Purpose Write header data into netCDF static file. * * Designer/Programmer : <NAME> * Modifications : original 7/97 * * Input: * cdf_id netCDF id of open file to write to * n_grids Number of grids available in file * grid_spacing size of grid box in METERS * asctime Ascii time file was generated * model Model generating static data * Nx X dimension of data in file * Ny Y dimension of data in file * Dx delta X in km of grid * Dy delta Y in km of grid * LoV standard longitude * Latin1 first standard latitude * Latin2 second standard latitude * Center_lat latitude of domain center * Center_lon longitude of domain center * lli lower left (SW) i coordinate of domain * llj lower left (SW) j coordinate of domain * uri upper right (NE) i coordinate of domain * urj upper right (NE) j coordinate of domain * parent_id Domain number of parent within which current domain resides * ratio_2_parent Integer number of grid points minus 1 in current domain between * two grid points of parent domain * origin site where LAPS being run * map_proj map projection * Output: * none * Globals: * none * Returns: * status Returns status to calling subroutine **************************************************************************/ #ifdef __STDC__ int cdf_wrt_hdr_stat(int cdf_id, fint4 *n_grids, float *grid_spacing, char *asctime, int asc_len, char *model, fint4 *nx, fint4 *ny, float *dx, float *dy, float *lov, float *latin1, float *latin2, float *la1, float *lo1, float *la2, float *lo2, float *center_lat, float *center_lon, int wrfsi, fint4 *lli, fint4 *llj, fint4 *uri, fint4 *urj, fint4 *parent_id, fint4 *ratio_2_parent, char *origin, char *map_proj, double unixtime, fint4 *status) #else int cdf_wrt_hdr_stat(cdf_id, n_grids, grid_spacing, asctime, asc_len,model, nx, ny, dx, dy, lov, latin1, latin2, la1,lo1, la2, lo2, center_lat, center_lon, wrfsi, lli, llj, uri, urj, parent_id, ratio_2_parent, origin, map_proj, unixtime, status) int cdf_id; fint4 *n_grids; float *grid_spacing; char *asctime; int asc_len; char *model; fint4 *nx; fint4 *ny; float *dx; float *dy; float *lov; float *latin1; float *latin2; float *la1; float *lo1; float *la2; float *lo2; fint4 *center_lat; fint4 *center_lon; int wrfsi; fint4 *lli; fint4 *llj; fint4 *uri; fint4 *urj; fint4 *parent_id; fint4 *ratio_2_parent; char *origin; char *map_proj; double unixtime; fint4 *status; #endif { int i_varid; long start[1], edges[1]; long start_map[2], edges_map[2]; short nx_in, ny_in; const long zero = 0L; /* store n_grids */ if ((i_varid = ncvarid (cdf_id, "n_grids")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput1(cdf_id, i_varid, (const long *) &zero, (void *)n_grids); /* store imax */ if ((i_varid = ncvarid (cdf_id, "imax")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput1(cdf_id, i_varid, (const long *) &zero, (void *)nx); /* store jmax */ if ((i_varid = ncvarid (cdf_id, "jmax")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput1(cdf_id, i_varid, (const long *) &zero, (void *)ny); /* store grid_spacing */ if ((i_varid = ncvarid (cdf_id, "grid_spacing")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput1(cdf_id, i_varid, (const long *) &zero, (void *)grid_spacing); start[0] = 0; /* store asctime */ if(DEBUG==1) printf("cdf_wrt_hdr_stat: C asc_len %d\n",asc_len); edges[0] = asc_len; if ((i_varid = ncvarid (cdf_id, "asctime")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, (const long *)start, (const long *)edges, (void *)asctime); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 1 %d\n",edges[0]); /* store model */ edges[0] = strlen(model); if ((i_varid = ncvarid (cdf_id, "process_name")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)model); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 1a %d %s\n",edges[0],model); edges[0] = 1; /* store Nx */ if ((i_varid = ncvarid (cdf_id, "Nx")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } nx_in = (short)(*nx); ncvarput(cdf_id, i_varid, start, edges, (void *)&nx_in); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 2 %d\n",edges[0]); /* store Ny */ if ((i_varid = ncvarid (cdf_id, "Ny")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ny_in = (short)*ny; ncvarput(cdf_id, i_varid, start, edges, (void *)&ny_in); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 3 %d\n",edges[0]); /* store Dx */ if ((i_varid = ncvarid (cdf_id, "Dx")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)dx); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 4 %d\n",edges[0]); /* store Dy */ if ((i_varid = ncvarid (cdf_id, "Dy")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)dy); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 5 %d\n",edges[0]); /* store LoV */ if ((i_varid = ncvarid (cdf_id, "LoV")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)lov); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 8 %d\n",edges[0]); /* store Latin1 */ if ((i_varid = ncvarid (cdf_id, "Latin1")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)latin1); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 9 %d\n",edges[0]); /* store Latin2 */ if ((i_varid = ncvarid (cdf_id, "Latin2")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)latin2); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 10 %d\n",edges[0]); /* store La1 */ if ((i_varid = ncvarid (cdf_id, "La1")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)la1); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 6 %d\n",edges[0]); /* store Lo1 */ if ((i_varid = ncvarid (cdf_id, "Lo1")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)lo1); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 7 %d\n",edges[0]); /* store La2 */ if ((i_varid = ncvarid (cdf_id, "La2")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)la2); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 6 %d\n",edges[0]); /* store Lo2 */ if ((i_varid = ncvarid (cdf_id, "Lo2")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)lo2); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 7 %d\n",edges[0]); /* store center_lat */ if ((i_varid = ncvarid (cdf_id, "center_lat")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)center_lat); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 10 %d\n",edges[0]); /* store center_lon */ if ((i_varid = ncvarid (cdf_id, "center_lon")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)center_lon); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 10 %d\n",edges[0]); /* write out 6 extra variables if domain is wrfsi */ if (wrfsi == 1) { /* store lower left i -> lli*/ if ((i_varid = ncvarid (cdf_id, "SW_i")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput1(cdf_id, i_varid, (const long *) &zero, (void *)lli); /* store lower left j -> llj*/ if ((i_varid = ncvarid (cdf_id, "SW_j")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput1(cdf_id, i_varid, (const long *) &zero, (void *)llj); /* store upper right i -> uri*/ if ((i_varid = ncvarid (cdf_id, "NE_i")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput1(cdf_id, i_varid, (const long *) &zero, (void *)uri); /* store upper right j -> urj*/ if ((i_varid = ncvarid (cdf_id, "NE_j")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput1(cdf_id, i_varid, (const long *) &zero, (void *)urj); /* store parent_id*/ if ((i_varid = ncvarid (cdf_id, "Parent_ID")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput1(cdf_id, i_varid, (const long *) &zero, (void *)parent_id); /* store ratio_2_parent*/ if ((i_varid = ncvarid (cdf_id, "Ratio_to_Parent")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput1(cdf_id, i_varid, (const long *) &zero, (void *)ratio_2_parent); } /* store valtime */ if ((i_varid = ncvarid (cdf_id, "valtime")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)&unixtime); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 11 %d\n",edges[0]); /* store reftime */ if ((i_varid = ncvarid (cdf_id, "reftime")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)&unixtime); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 12 %d\n",edges[0]); /* store origin */ edges[0] = strlen(origin); if ((i_varid = ncvarid (cdf_id, "origin_name")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start, edges, (void *)origin); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 13 %d\n",edges[0]); /* store map_proj */ start_map[0] = 0; start_map[1] = 0; edges_map[0] = 1; edges_map[1] = strlen(map_proj); if ((i_varid = ncvarid (cdf_id, "grid_type")) == (-1)) { *status = -5; /* returns "error writing header" */ return -5; } ncvarput(cdf_id, i_varid, start_map, edges_map, (void *)map_proj); if(DEBUG==1) printf("cdf_wrt_hdr_stat: 14 %d %d\n",edges_map[0],edges_map[1]); return 0; } /************************************************************************* * WRITE_CDF_STATIC * Category Product Management * Group General Purpose Database * Module Write Grid data * Purpose Write grid data into netCDF static file. * * Designer/Programmer : <NAME> * Modifications : original 4/93 * * Input: * filname NetCDF filename to open * asctime Ascii time of file * var Array of LAPS variables to write out * comment Comments for each level to write * imax X dimension of data in file * jmax Y dimension of data in file * n_grids Number of grids available in file & * dimension of the VAR and COMMENT * in the calling program * data 3D grid containing data to write * zin Grid for AVS applications * model Model generating static data * grid_spacing size of grid box in M * Output: * status Returns status to calling subroutine * Globals: * none * Returns: * none *****************************************************************************/ #ifdef __STDC__ void write_cdf_static(char *filname, fint4 *s_length, char *f_asctime, fint4 *f_asc_len, char *f_cdl_dir, fint4 *cdl_len, char *f_var, fint4 *var_len, char *f_comment, fint4 *com_len, char *f_ldf, fint4 *ldf_len, fint4 *imax, fint4 *jmax, fint4 *n_grids, fint4 *nx_lp, fint4 *ny_lp, float *data, char *f_model, float *grid_spacing, float *dx, float *dy, float *lov, float *latin1, float *latin2, float *la1, float *lo1, float *la2, float* lo2, float *center_lat, float *center_lon, fint4 *lli, fint4 *llj, fint4 *uri, fint4 *urj, fint4 *parent_id, fint4 *ratio_2_parent, char *f_origin, fint4 *origin_len, char *f_map_proj, fint4 *map_len, fint4 *unixtime, fint4 *status) #else void write_cdf_static(filname, s_length, f_asctime, f_asc_len, f_cdl_dir, cdl_len, f_var, var_len, f_comment, com_len, f_ldf, ldf_len, imax, jmax, n_grids, nx_lp, ny_lp, data, f_model, grid_spacing, dx, dy, lov, latin1, latin2, la1,lo1,la2,lo2, center_lat, center_lon, lli, llj, uri, urj, parent_id, ratio_2_parent, f_origin, origin_len, f_map_proj, map_len, unixtime, status) char *filname; fint4 *s_length; char *f_asctime; fint4 *f_asc_len; char *f_cdl_dir; fint4 *cdl_len; char *f_var; fint4 *var_len; char *f_comment; fint4 *com_len; char *f_ldf; fint4 *ldf_len; fint4 *imax; fint4 *jmax; fint4 *n_grids; fint4 *nx_lp; fint4 *ny_lp; float *data; char *f_model; float *grid_spacing; float *dx; float *dy; float *lov; float *latin1; float *latin2; float *la1; float *lo1; float *la2; float *lo2; fint4 *center_lat; fint4 *center_lon; fint4 *lli; fint4 *llj; fint4 *uri; fint4 *urj; fint4 *parent_id; fint4 *ratio_2_parent; char *f_origin; fint4 *origin_len; char *f_map_proj; fint4 *map_len; fint4 *unixtime; fint4 *status; #endif { char *prefix, *comm_var, *model, *asctime, *fname, *map_proj; char *var, *comment, *ldf, *p_var, *pf_var, *p_com, *pf_com; char *origin, *units; int mod_len, asc_len, c_var_len, c_com_len, wrfsi; int out_file, istat, i_varid, i, process_vr, count; int lat_index, lon_index, hdr_status; int xdimid, ydimid; static char *syscmd, *cdlfile; double d_unixtime; long nx_cdl, ny_cdl; /* turn off the error handling done by the netCDF routines */ ncopts = NC_VERBOSE; /* malloc space for c-strings */ c_var_len = *var_len + 1; prefix = malloc(c_var_len * sizeof(char)); comm_var = malloc((c_var_len+8) * sizeof(char)); mod_len = strlen(f_model); model = malloc(((mod_len)+1) * sizeof(char)); asc_len = *f_asc_len; asctime = malloc(((asc_len)+1) * sizeof(char)); map_proj = malloc(((*map_len)+1) * sizeof(char)); origin = malloc(((*origin_len)+1) * sizeof(char)); var = malloc(c_var_len * (*n_grids) * sizeof(char)); c_com_len = *com_len + 1; comment = malloc(c_com_len * (*n_grids) * sizeof(char)); fname = malloc(((*s_length)+1) * sizeof(char)); /* convert fortran string f_var to c string var */ for (i = 0; i < *n_grids; i++) { p_var = var + (i * c_var_len); pf_var = f_var + (i * (*var_len)); nstrncpy(p_var, pf_var, *var_len); downcase_c(p_var,p_var); p_com = comment + (i * c_com_len); pf_com = f_comment + (i * (*com_len)); fstrncpy(p_com,pf_com, *com_len); } fstrncpy(model,f_model,mod_len); fstrncpy(asctime,f_asctime,asc_len); fstrncpy(map_proj,f_map_proj,*map_len); fstrncpy(origin,f_origin,*origin_len); /* convert fortran file_name into C fname */ nstrncpy(fname,filname,s_length); /* allocate space for syscmd and cdlfile and fill up */ /* cdl file contains domain name + ".cdl\0" */ cdlfile = malloc(((*cdl_len)+(*ldf_len)+5) * sizeof(char)); nstrncpy(cdlfile,f_cdl_dir,*cdl_len); ldf = malloc(((*ldf_len) + 1) * sizeof(char)); nstrncpy(ldf,f_ldf,*ldf_len); strcat(cdlfile,ldf); /* determine if ldf is nest7grid or wrfsi */ if (strncmp(ldf,"wrfsi", 5) == 0) { wrfsi = 1; } else { wrfsi = 0; } free(ldf); strcat(cdlfile,".cdl"); *cdl_len = strlen(cdlfile); /* SYSCMD contains "ncgen -o %s %s\0" which is 16 char, cdlfile, and fname + 10 extra */ if (nx_cdl * ny_cdl > 4000000) { syscmd = malloc((strlen(SYSCMD2)+*cdl_len+*s_length+10) * sizeof(char)); sprintf(syscmd,SYSCMD2, fname, cdlfile); } else { syscmd = malloc((strlen(SYSCMD)+*cdl_len+*s_length+10) * sizeof(char)); sprintf(syscmd,SYSCMD, fname, cdlfile); } free(cdlfile); /* create output file */ #ifdef SMS *status = pcl_system(syscmd); #else system(syscmd); #endif free(syscmd); out_file = ncopen(fname,NC_WRITE); if (out_file == -1) { *status = -2; /* error in file creation */ free_static_malloc(prefix, comm_var, model, asctime, var, comment, NULL, fname); return; } /* get x and y dimensions from output file and make sure they are the same as nx_lp and ny_lp */ xdimid = ncdimid(out_file,"x"); ydimid = ncdimid(out_file,"y"); ncdiminq(out_file,xdimid, (char *) 0, &nx_cdl); ncdiminq(out_file,ydimid, (char *) 0, &ny_cdl); if ((nx_cdl == *nx_lp) && (ny_cdl == *ny_lp)) { } else { *status = -6; /* nest7grid.cdl & nest7grid.parms disagree */ free_static_malloc(prefix, comm_var, model, asctime, var, comment, NULL, fname); return; } /* check to see if we're working with LAPS...if we are, la1, lo1, la2, lo2 will all be -999.0 */ /* if they're filled, its wrfsi and they are passed in */ if ((*la1==-999.0)&&(*lo1==-999.0)&&(*la2==-999.0)&&(*lo2==-999.0)) { /* get La1 and Lo1 (SW corner lat and lon) and La2 and Lo2 (NE corner lat and lon) from data array */ lat_index = -1; lon_index = -1; for (i = 0; i < *n_grids; i++) { p_var = var + (i * c_var_len); if (strcmp(p_var, LAT) == 0) lat_index = i; if (strcmp(p_var, LON) == 0) lon_index = i; } if (lat_index == (-1)) { *la1 = -999.99; *la2 = -999.99; } else { *la1 = *(data + (lat_index*(*imax)*(*jmax))); *la2 = *(data + ((lat_index+1)*(*imax)*(*jmax)) - 1); } if (lon_index == (-1)) { *lo1 = -999.99; *lo2 = -999.99; } else { *lo1 = *(data + (lon_index*(*imax)*(*jmax))); *lo2 = *(data + ((lon_index+1)*(*imax)*(*jmax)) - 1); if (*lo1 < 0.0) *lo1 = 360.0 + *lo1; if (*lo2 < 0.0) *lo2 = 360.0 + *lo2; } } /* write header info to output file */ d_unixtime = (double)*unixtime; hdr_status = cdf_wrt_hdr_stat(out_file, n_grids, grid_spacing, asctime, asc_len,model, imax, jmax, dx, dy, lov, latin1, latin2,la1,lo1,la2,lo2, center_lat, center_lon, wrfsi, lli, llj, uri, urj, parent_id, ratio_2_parent, origin, map_proj,d_unixtime, status); if (hdr_status != 0) { *status = hdr_status; free_static_malloc(prefix, comm_var, model, asctime, var, comment, NULL, fname); return; } /* write data to grid and write out comment */ count = 0; for (i = 0; i < *n_grids; i++) { p_var = var + (i * c_var_len); p_com = comment + (i * c_com_len); strcpy(prefix,p_var); strcpy(comm_var,p_var); strcat(comm_var,"_comment"); if ((i_varid = ncvarid (out_file , prefix)) == (-1)) { printf("write_cdf_static: no variable %s in file.\n", prefix); } else { istat = cdf_update_stat(out_file,i_varid, prefix, (void *)(data + (i*(*imax)*(*jmax))), comm_var,p_com); if (istat == -1) { *status = -4; printf("1st case \n"); ncclose(out_file); return; } count++; } } *status = count; /* returns number of grids written */ ncclose(out_file); return; } /***************************************************************************** * CDF_RETR_GRID_STAT * Category Product Management * Group General Purpose Database * Module Retrieve Grid Data * Purpose To retrieve a specified grid from a netcdf file * * Designer/Programmer : <NAME> * Modifications : original 9/12/90 * modified for new READLAPSDATA 1/93 <NAME> * * Input : * i_cdfid NetCDF file id for file to be read * s_field A character string identifying the field * gptr Pointer to location in data array to write data. * cptr Pointer to location in data array to write comments * uptr Pointer to location in data array to write units. * Output : * none * Globals: * NC_NOWRITE A NetCDF global that opens the NetCDF file for reading * only. * Returns: * 0 if normal return * -1 if an error occurs *****************************************************************************/ #ifdef __STDC__ int cdf_retr_grid_stat(int i_cdfid, int i_varid, char *s_field, float *gptr, char *cptr, int c_com_len, char *uptr, int c_unit_len) #else int cdf_retr_grid_stat(i_cdfid, i_varid, s_field, gptr, cptr, c_com_len, uptr, c_unit_len) int i_cdfid; int i_varid; char *s_field; float *gptr; char *cptr; int c_com_len; char *uptr; int c_unit_len; #endif { int i_status, j; long start[4],count[4],start_c[3],count_c[3]; char var_name[13]; /* printf("cdf_ret_grd: level = %d fctime = %d field = %s\n", i_level, i_fctime, s_field); */ /* turn off the error handling done by the netCDF routines */ ncopts = NC_VERBOSE; /* get the x and y dimension sizes */ count[0] = 1; count[1] = 1; count[2] = dim_size_v3 (i_cdfid, "y"); count[3] = dim_size_v3 (i_cdfid, "x"); start[0] = 0; start[1] = 0; start[2] = 0; start[3] = 0; /* read the grid from the netcdf file */ i_status = ncvarget (i_cdfid, i_varid, (const long *)start, (const long *)count, (void *)gptr); if (i_status == (-1)) { printf("cdf_retrieve_laps: error retrieving data %s grid.\n", s_field); return -1; } /* retrieve units */ i_status = ncattget (i_cdfid, i_varid, "LAPS_units", uptr); if (i_status == (-1)) { printf("cdf_retrieve_laps: error retrieving LAPS_units.\n"); return -1; } if(DEBUG==1) printf("cdf_retrieve_laps: units >%s<\n",uptr); /* setup to read the comment from the netcdf file */ sprintf(var_name, "%s%s", s_field, "_comment"); if ((i_varid = ncvarid (i_cdfid, var_name)) == (-1)) { printf("cdf_retrieve_laps: no comment field available.\n"); return -1; } /* construct the arrays needed to read the grid */ start_c[0] = 0; start_c[1] = 0; start_c[2] = 0; count_c[0] = 1; count_c[1] = 1; count_c[2] = c_com_len; i_status = ncvarget (i_cdfid, i_varid, (const long *)start_c, (const long *)count_c, (void *)cptr); if (i_status == (-1)) { printf("cdf_retrieve_laps: error retrieving comment.\n"); return -1; } /* normal return */ return 0; } /***************************************************************************** * CDF_RETR_HDR_STAT * Category Product Management * Group General Purpose Database * Module Retrieve Static Grid * Purpose To retrieve header info from a netcdf file * * Designer/Programmer : <NAME> * Modifications : original 4/93 * * Input : * i_cdfid NetCDF file id for file to be read * Output : * imaxn number of x gridpoints * jmaxn number of y gridpoints * kmaxn number of grids in the file * laps_dom_file name of laps domain for this file * Globals: * NC_NOWRITE A NetCDF global that opens the NetCDF file for * reading only. * Returns: * -1 if an error occurs *****************************************************************************/ #ifdef __STDC__ int cdf_retr_hdr_stat(int i_cdfid,fint4 *imaxn, fint4 *jmaxn, fint4 *n_grids_n, float *grid_spacing_n) #else int cdf_retr_hdr_stat(i_cdfid,imaxn,jmaxn,n_grids_n,grid_spacing_n) int i_cdfid; fint4 *imaxn; fint4 *jmaxn; fint4 *n_grids_n; float *grid_spacing_n; #endif { int i_status, i_varid, i, temp, str_len; long mindex[1], start[1], count_asc[1], count_long[1]; static char c_ver[5]; char *t_ptr; /* turn off the error handling done by the netCDF routines */ ncopts = NC_VERBOSE; mindex[0] = 0; start[0] = 0; count_asc[0] = 18; count_long[0] = 132; /* get the data variable id */ if(DEBUG==1) printf( "cdf_read_grid: data variable name = %s\n", "imax"); if ((i_varid = ncvarid (i_cdfid, "imax")) == (-1)) return -1; /* read the var from the netcdf file */ i_status = ncvarget1 (i_cdfid, i_varid, (const long *)mindex, (void *)imaxn); if (i_status == (-1)) return -1; /* get the data variable id */ if(DEBUG==1) printf( "cdf_read_grid: data variable name = %s\n", "jmax"); if ((i_varid = ncvarid (i_cdfid, "jmax")) == (-1)) return -1; /* read the var from the netcdf file */ i_status = ncvarget1 (i_cdfid, i_varid, (const long *)mindex, (void *)jmaxn); if (i_status == (-1)) return -1; /* get the data variable id */ if(DEBUG==1) printf( "cdf_read_grid: data variable name = %s\n", "n_grids"); if ((i_varid = ncvarid (i_cdfid, "n_grids")) == (-1)) return -1; /* read the var from the netcdf file */ i_status = ncvarget1 (i_cdfid, i_varid, (const long *)mindex, (void *)n_grids_n); if (i_status == (-1)) return -1; /* get the data variable id */ if(DEBUG==1) printf( "cdf_read_grid: data variable name = %s\n", "grid_spacing"); if ((i_varid = ncvarid (i_cdfid, "grid_spacing")) == (-1)) return -1; /* read the var from the netcdf file */ i_status = ncvarget1 (i_cdfid, i_varid, (const long *)mindex, (void *)grid_spacing_n); if (i_status == (-1)) return -1; /* normal return */ return 0; } /************************************************************************* * READ_CDF_STATIC * Category Product Management * Group General Purpose Database * Module write_cdf-Read_cdf_file * Purpose Read LAPS data from netCDF format static file. * * Designer/Programmer : <NAME> * Modifications : original 4/93 * * Input: * filname NetCDF filename to open * s_length length of the filname string * f_var Array of static variables to retrieve * var_len length of one f_var string * f_comment Array to hold comment info retrieved * com_len length of one f_comment string * f_units Array to hold units info retrieved * unit_len length of one f_units string * imax Expected X dimension of data * jmax Expected Y dimension of data * n_grids Dimension of the f_var, comment, * data 3D grid containing data requested * otherwise contains 0 * and units arrays in the calling program * Output: * imax_n Actual X dimension of data in file * jmax_n Actual Y dimension of data in file * status Returns status to calling subroutine * Globals: * none * Returns: * count of requested variables that were not retrieved *************************************************************************/ #ifdef __STDC__ void read_cdf_static(char *filname, fint4 *s_length,char *f_var, fint4 *var_len, char *f_comment, fint4 *com_len, char *f_units,fint4 *unit_len, fint4 *imax,fint4 *jmax, fint4 *n_grids,float *data,float *grid_spacing, fint4 *no_laps_diag,fint4 *status) #else void read_cdf_static(filname,s_length,f_var,var_len,f_comment,com_len, f_units,unit_len,imax,jmax, n_grids,data, grid_spacing,no_laps_diag,status) char *filname; fint4 *s_length; char *f_var; int *var_len; char *f_comment; int *com_len; char *f_units; int *unit_len; fint4 *imax; fint4 *jmax; fint4 *n_grids; float *data; float *grid_spacing; fint4 *no_laps_diag; fint4 *status; #endif { /*char model[132], asctime[18], origin[132], version[5]; */ char *var, *comment, *units, *prefix, *fname; char *p_var, *pf_var, *p_com, *pf_com, *p_unit, *pf_unit; char *comm_var, *model, *asctime; float *p_data; int istat, i, j, unconv_var, process_vr, cdfid, varid; int c_var_len, c_com_len, c_unit_len, s_len; fint4 imaxn, jmaxn, n_grids_n; /* turn off the error handling done by the netCDF routines */ ncopts = NC_VERBOSE; /* malloc space for c-strings */ c_var_len = *var_len + 1; prefix = malloc(c_var_len * sizeof(char)); var = malloc(c_var_len * (*n_grids) * sizeof(char)); c_com_len = *com_len + 1; comment = calloc(c_com_len * (*n_grids), sizeof(char)); c_unit_len = *unit_len + 1; units = calloc(c_unit_len * (*n_grids), sizeof(char)); fname = malloc(((*s_length)+1) * sizeof(char)); /* null out arrays for units,comment before using */ /* convert fortran string f_var to c string var and downcase */ for (i = 0; i < *n_grids; i++) { p_unit = units + (i * c_unit_len); (*p_unit) = '\0'; p_com = comment + (i * c_com_len); (*p_com) = '\0'; p_var = var + (i * c_var_len); pf_var = f_var + (i * (*var_len)); nstrncpy(p_var, pf_var, *var_len); downcase_c(p_var,p_var); } /* convert fortran filname into C fname */ nstrncpy(fname,filname,s_length); /* open file for reading */ cdfid = open_cdf(NC_NOWRITE,fname,no_laps_diag); if (cdfid == -1) { *status = -1; /* error opening file */ free_static_malloc(prefix, NULL, NULL, NULL, var, comment, units, fname); return; } /* get header info */ istat = cdf_retr_hdr_stat(cdfid,&imaxn,&jmaxn,&n_grids_n, grid_spacing); if (istat == -1) { *status = -5; ncclose(cdfid); free_static_malloc(prefix, NULL, NULL, NULL, var, comment, units, fname); return; } if(DEBUG==1) printf("read_cdf_static: %d %d %d %d %d %d\n", imaxn,jmaxn,n_grids_n,*imax,*jmax,*n_grids); if (imaxn > *imax || jmaxn > *jmax ) { *status = -3; ncclose(cdfid); free_static_malloc(prefix, NULL, NULL, NULL, var, comment, units, fname); return; } unconv_var = 0; for (i = 0; i < *n_grids; i++) { p_var = var + (i * c_var_len); p_com = comment + (i * c_com_len); p_unit = units + (i * c_unit_len); p_data = data + (i*(*imax)*(*jmax)); strcpy(prefix,p_var); if ((varid = ncvarid (cdfid , prefix)) == (-1)) { printf("write_cdf_static: no variable %s in file.\n", prefix); unconv_var += 1; } else { /* if(DEBUG==1) printf("b write_cdf_static: >%s<>%s<\n",p_unit,units[i * c_unit_len]); */ istat = cdf_retr_grid_stat(cdfid,varid,prefix,p_data, p_com,c_com_len,p_unit, c_unit_len); if(DEBUG==1) printf("a write_cdf_static: %d %d >%s< >%s< %d >%s< %d \n", cdfid,varid,prefix, p_com,c_com_len,p_unit, c_unit_len); if (istat == -1) { *status = -4; printf("2nd case \n"); ncclose(cdfid); free_static_malloc(prefix, NULL, NULL, NULL, var, comment, units, fname); return; } } } ncclose(cdfid); for (i = 0; i < *n_grids; i++) { p_com = comment + (i * c_com_len); pf_com = f_comment + (i * (*com_len)); s_len = strlen(p_com); strncpy(pf_com, p_com, s_len); pf_com += s_len; if (s_len < (*com_len)) { for ( j = 0; j < (*com_len - s_len); j++) { *pf_com = ' '; pf_com++; } } p_unit = units + (i * c_unit_len); pf_unit = f_units + (i * (*unit_len)); s_len = strlen(p_unit); strncpy(pf_unit, p_unit, s_len); pf_unit += s_len; if (s_len < (*unit_len)) { for ( j = 0; j < (*unit_len - s_len); j++) { *pf_unit = ' '; pf_unit++; } } } free_static_malloc(prefix, NULL, NULL, NULL, var, comment, units, fname); *status = unconv_var; return; }
#include <pthread.h> // for pthread_create, pthread_join, pthread_exit #include <stdio.h> // for printf #include <stdlib.h> // for exit #define NITER 1000000 pthread_mutex_t mutex; int count = 0; void * Count(void * a) { int i, tmp; for(i = 0; i < NITER; i++) { pthread_mutex_lock( &mutex ); tmp = count; /* copy the global count locally */ tmp = tmp+1; /* increment the local copy */ count = tmp; /* store the local value into the global count */ pthread_mutex_unlock( &mutex ); } } int main(int argc, char * argv[]) { pthread_t tid1, tid2; pthread_mutex_init( & mutex, NULL ); if(pthread_create(&tid1, NULL, Count, NULL)) { printf("\n ERROR creating thread 1"); exit(1); } if(pthread_create(&tid2, NULL, Count, NULL)) { printf("\n ERROR creating thread 2"); exit(1); } if(pthread_join(tid1, NULL)) /* wait for the thread 1 to finish */ { printf("\n ERROR joining thread"); exit(1); } if(pthread_join(tid2, NULL)) /* wait for the thread 2 to finish */ { printf("\n ERROR joining thread"); exit(1); } if (count < 2 * NITER) printf("\n BAD! count is [%d], should be %d\n", count, 2*NITER); else printf("\n OK! count is [%d]\n", count); pthread_exit(NULL); }
<reponame>bianhaoyi/necache /* * twemcache - Twitter memcached. * Copyright (c) 2012, Twitter, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Twitter 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _MC_THREAD_H_ #define _MC_THREAD_H_ #include <semaphore.h> #include <pthread.h> #include <mc_slabs.h> #include <mc_stats.h> #include <mc_connection.h> /* A mapping from a member to its key value in pthread */ struct thread_key { pthread_key_t stats_mutex; /* stats lock */ pthread_key_t stats_thread; /* thread stats */ pthread_key_t stats_slabs; /* slab stats */ pthread_key_t kbuf; /* klog buffer */ }; typedef void * (*thread_func_t)(void *); struct thread_worker { pthread_t tid; /* thread id */ struct event_base *base; /* libevent handle this thread uses */ struct event notify_event; /* listen event for notify pipe */ int notify_receive_fd; /* receiving end of notify pipe */ int notify_send_fd; /* sending end of notify pipe */ struct conn_q new_cq; /* new connection q */ cache_t *suffix_cache; /* suffix cache */ pthread_mutex_t *stats_mutex; /* lock for stats update/aggregation */ struct stats_metric *stats_thread; /* per-thread thread-level stats */ struct stats_metric **stats_slabs; /* per-thread slab-level stats */ struct kbuf *kbuf; /* per-thread klog buffer */ }; /* * Aggregator model: * * The stats aggregator thread periodically wakes itself up and collects * collects stats from all worker threads. * * Clients can collect stats by sending 'stats' command to a twemcache * server and get replies in pretty much the same format as before. But * data are obtained from the aggregator rather than collected on-the-fly. * * Note that update granularity is the same as aggregation interval. This * may break some tests which rely on instant stats update, our in-house * python tests factor this in, and should pass on all future versions. * * Semaphore: * * Because now workers can process stats commands while aggregator is updating, * a semaphore is utilized to prevent workers from getting inconsistent data * (imagine the aggregator has flushed half of its metrics before aggregation * when a stats query command comes in). On the other hand, we don't want to * discourage concurrent queries if they are all reads, therefore a semaphore * instead of a mutex. * * Configuration: * * aggregation interval: settings.stats_interval * - default: 0.1s, not much overhead with this value * (twctop.rb pulls data every 1 or 2 seconds) */ struct thread_aggregator { pthread_t tid; /* thread id */ struct event_base *base; /* libevent handle for this thread */ struct event ev; /* event object */ sem_t stats_sem; /* rw sempahore */ struct timeval stats_ts; /* aggregation timestamp */ struct stats_metric *stats_thread; /* aggregated thread-level stats */ struct stats_metric **stats_slabs; /* aggregated slab-level stats */ struct stats_slab_const stats_slabs_const[SLABCLASS_MAX_IDS]; }; /* * The command logger (klogger) model: * * klogger periodically wakes itself up through libevent, * and collects/logs command logs from all worker threads. * * Configuration: * collect interval: settings.klog_intvl * - default: 1ms, the structure is lockless so we can afford to wake up often * local log file: settings.klog_name * - default: NULL */ struct thread_klogger { pthread_t tid; /* unique ID of this thread */ struct event_base *base; /* libevent handle for this thread */ struct event ev; /* event object */ }; void *thread_get(pthread_key_t key); rstatus_t thread_init(struct event_base *main_base); void thread_deinit(void); rstatus_t thread_dispatch(int sd, conn_state_t state, int ev_flags, int udp); #endif
#ifndef _EXT_PROTOCOL_H_ #define _EXT_PROTOCOL_H_ #if defined(__cplusplus) extern "C" { #endif #define PROTOCOL_API_VERSION 1 typedef enum { extStreamTypeMpegTS = 0, extStreamTypeMpegPS = 1, }extStreamType_e; #define EXT_STATUS_OK 0 /** * Error opening media */ #define EXT_STATUS_OPEN_ERROR -1 /** * Read error */ #define EXT_STATUS_READ_ERROR -2 /** * End of stream while reading */ #define EXT_STATUS_EOS -3 /** * Bad argument */ #define EXT_STATUS_BAD_ARGUMENT -4 typedef struct ext_protocol ext_protocol_t; /** * Handle to the opened instance of the protocol. */ typedef void* ProtocolHandle; struct ext_protocol { /** * null-terminated string with protocol name(identifier). */ char ident[64]; /** * Some private data to be filled and used by the protocol. */ void * private_data; /** * Implementation version. */ int version; /** * Open stream via protocol. * * @param e - pointer to protocol * @param pHandle - handler to opened instatnce of protocol. * Will be used with all operations applied to opened instance. * In case of error *pHandle should be filled with NULL. * otherwise - with opened handle. * @param url - content URL to be played * @param extra_data - some extra_data * * @return 0 if success * error code otherwise. */ int (*open) (ext_protocol_t *e, ProtocolHandle* pHandle, const char *url); /** * Read data from stream. * @param handle - protocol instance handle * * @return number of bytes read: * 0 - no data received try again * <0 - error code. @See EXT_STATUS_XXX */ int (*read) (ProtocolHandle handle, char *buf, int buflen); /** * Close stream. * @param handle - protocol instance handle */ void (*close) (ProtocolHandle handle); /** * Send command to ext. protocol * This function is always called from other thread relative to calls of open,read,setPosTime,... * @param e - pointer to protocol * @param cmd - command to be executed. * @param params - command params. * * @return result of command execution allocated by malloc. * free() it after use. */ char * (*command) (ext_protocol_t *e, const char *cmd, const char *params); /** * Send event to protocol * @param e - pointer to protocol * @param event_id - event code. */ void (*event) (ext_protocol_t *e, unsigned long event_id); /** * Seek to specified time (in ms) in stream. * @param handle - protocol instance handle * @param posInMs - position in media in ms since start of media * always from 0 to duration (posInMs is not related to startTime) * * @return if success - >= 0 - success, returns stream position in ms * otherwise - < 0 - error */ int (*setPosTime) (ProtocolHandle handle, unsigned int posInMs); /** * Get timestamp of media content start point in ms. * * @param handle - protocol instance handle * * @return start time of the stream in ms if known * otherwise - 0. */ unsigned int(*getStartTime) (ProtocolHandle handle); /** * Get the duration of whole media in ms. * * @param handle - protocol instance handle * * @return duration of the stream in ms if known * otherwise - 0. */ unsigned int(*getDuration) (ProtocolHandle handle); /** * Get the stream type of the data that is being read from this protocol. * * @param handle - protocol instance handle * * @return type of the stream container provided by this protocol. */ extStreamType_e (*getStreamType)(ProtocolHandle handle); /** * Get video frame rate if available. * @param handle - protocol instance handle * * @return frame_rate*1000, e.i. 24000, 25000, ... , * 0 if not available */ int (*getVideoFPS) (ProtocolHandle handle); /** * Get content specific meta data information * It can be list of chapters etc. It should be JSON string * It should contain field "infoType" with string value which explicitly specifies * format of returned metadata information. */ const char* (*getMetadataInfo) (ProtocolHandle handle); /** * Return whether protocol is realtime or not. * @param e - pointer to protocol * * Return: non zero - if it is realtime protocol (default) * zero - otherwise */ int (*isRealTimeProtocol) (ext_protocol_t *e); /** * Leave space for future extensions. It must be filled by NULLs. */ void * padding[8]; }; typedef void (*ext_event_fn_t) (ext_protocol_t *e, unsigned long event_id, const char* event_data); typedef int (*ext_abort_fn_t) (ext_protocol_t *e); typedef ext_protocol_t * (*ext_protocol_init_t) (ext_event_fn_t ext_event_fn); typedef void (*ext_protocol_register_abort_fn_t)(ext_protocol_t *e, ext_abort_fn_t ext_abort_fn); typedef void (*ext_protocol_free_t) (ext_protocol_t **pe); /* The dynamic library will implement these */ /** * Allocate and return ext_protocol_t * * @param ext_event_fn Event function that will be called from inside ext_protocol * * @return pointer to protocol instance. */ ext_protocol_t * ext_protocol_init (ext_event_fn_t ext_event_fn); /** * Register abort function that should be called from inside ext_protocol * During long-duration operations such as read, open and setPosTime ext_protocol should periodically * call this function to check whether protocol should return from long-duration call with error. * ext_abort_fn return 0 if protocol can continue operation, otherwise - abort operation. * * ONLY for ext-protocol V1. * For V2 use per playback abort. * * @param e - pointer to protocol * @param ext_abort_fn abort function. * can be NULL if abort function should not be called. */ void ext_protocol_register_abort_fn(ext_protocol_t *e, ext_abort_fn_t ext_abort_fn); /** * Free ext_protocol_t * * @param *e - pointer to protocol */ void ext_protocol_free (ext_protocol_t **pe); //==============V2 extension ===================== typedef struct ext_protocol_v2 ext_protocol_v2_t; typedef void (*ext_protocol_playback_event_fn_v2_t)(ext_protocol_v2_t *e ,void * context ,unsigned long event_id ,const char* event_data); typedef int (*ext_playback_abort_fn_v2_t) (ext_protocol_v2_t *e ,void * context); struct ext_protocol_v2 { /** * null-terminated string with protocol name(identifier). */ char ident[64]; /** * Some private data to be filled and used by the protocol. */ void * private_data; /** * Implementation version. */ int version; /** * Open stream via protocol. * * @param e - pointer to protocol * @param pHandle - handler to opened instatnce of protocol. * Will be used with all operations applied to opened instance. * In case of error *pHandle should be filled with NULL. * otherwise - with opened handle. * @param evt_fn callback to pass events for the corresponding playback * @param abort_fn callback to check if stop is required, it's return value: * 1 - stop is required; * 0 - continue; * @param context - passed to evt_fn and abort_fn * @param url - content URL to be played * * @return 0 if success * error code otherwise. */ int (*open) (ext_protocol_v2_t *e ,ProtocolHandle * pHandle ,ext_protocol_playback_event_fn_v2_t evt_fn ,ext_playback_abort_fn_v2_t abort_fn ,void * context ,const char *url); /** * Read data from stream. * @param handle - protocol instance handle * * @return number of bytes read: * 0 - no data received try again * <0 - error code. @See EXT_STATUS_XXX */ int (*read) (ProtocolHandle handle, char *buf, int buflen); /** * Close stream. * @param handle - protocol instance handle */ void (*close) (ProtocolHandle handle); /** * Send command to ext. protocol * This function is always called from other thread relative to calls of open,read,setPosTime,... * @param e - pointer to protocol * @param handle the command pertains to, if NULL, command applies to the entire protocol * @param cmd - command to be executed. * @param params - command params. * * @return result of command execution allocated by malloc. * free() it after use. */ char * (*command) (ext_protocol_v2_t *e, ProtocolHandle handle, const char *cmd, const char *params); /** * Send event to protocol * @param e - pointer to protocol * @param handle the command pertains to, if NULL, command applies to the entire protocol * @param event_id - event code. */ void (*event) (ext_protocol_v2_t *e, ProtocolHandle handle, unsigned long event_id); /** * Seek to specified time (in ms) in stream. * @param handle - protocol instance handle * @param posInMs - position in media in ms since start of media * always from 0 to duration (posInMs is not related to startTime) * * @return if success - >= 0 - success, returns stream position in ms * otherwise - < 0 - error */ int (*setPosTime) (ProtocolHandle handle, unsigned int posInMs); /** * Get timestamp of media content start point in ms. * * @param handle - protocol instance handle * * @return start time of the stream in ms if known * otherwise - 0. */ unsigned int(*getStartTime) (ProtocolHandle handle); /** * Get the duration of whole media in ms. * * @param handle - protocol instance handle * * @return duration of the stream in ms if known * otherwise - 0. */ unsigned int(*getDuration) (ProtocolHandle handle); /** * Get the stream type of the data that is being read from this protocol. * * @param handle - protocol instance handle * * @return type of the stream container provided by this protocol. */ extStreamType_e (*getStreamType)(ProtocolHandle handle); /** * Get video frame rate if available. * @param handle - protocol instance handle * * @return frame_rate*1000, e.i. 24000, 25000, ... , * 0 if not available */ int (*getVideoFPS) (ProtocolHandle handle); /** * Get content specific meta data information * It can be list of chapters etc. It should be JSON string * It should contain field "infoType" with string value which explicitly specifies * format of returned metadata information. */ const char* (*getMetadataInfo) (ProtocolHandle handle); /** * Return whether protocol is realtime or not. * @param e - pointer to protocol * * Return: non zero - if it is realtime protocol (default) * zero - otherwise */ int (*isRealTimeProtocol) (ext_protocol_v2_t *e); /** * Leave space for future extensions. It must be filled by NULLs. */ void * padding[8]; }; typedef void (*ext_protocol_global_event_fn_v2_t)(ext_protocol_v2_t *e ,unsigned long event_id ,const char* event_data); /** * Allocate and return ext_protocol_v2 * * @param ext_event_fn Event function that will be called from inside ext_protocol * * @return pointer to protocol instance. */ typedef ext_protocol_v2_t * (*ext_protocol_init_v2_t) (ext_protocol_global_event_fn_v2_t ext_glob_event_fn); typedef void (*ext_protocol_free_v2_t) (ext_protocol_v2_t **p); /* The dynamic library will implement these */ ext_protocol_v2_t * ext_protocol_init_v2 (ext_protocol_global_event_fn_v2_t ext_event_fn); /** * Free ext_protocol_v2 * * @param *e - pointer to protocol */ void ext_protocol_free_v2 (ext_protocol_v2_t **pe); #if defined(__cplusplus) } #endif #endif //_EXT_PROTOCOL_H_
/* * Licensed to Systerel under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Systerel licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include "sopc_dict.h" #include "sopc_mem_alloc.h" #include <assert.h> #define HASH_I(hash, i) (hash + (i / 2) + (i * i / 2)) /* This is a dictionary implemented using quadratic probing (see * https://en.wikipedia.org/wiki/Linear_probing) for resolving key conflicts. * * We distinguish between empty and non-empty buckets using a special value for * the key. Removal of items can be implemented by stealing a second value from * the keyspace and using it as a tombstone. */ typedef struct _SOPC_DictBucket { void* key; void* value; } SOPC_DictBucket; struct _SOPC_Dict { SOPC_DictBucket* buckets; size_t size; // Total number of buckets, always a power of two size_t sizemask; // sizemask == (size - 1), used to replace (hash % size) by (hash & sizemask) size_t n_items; // Number of buckets holding a "real" value (not empty, not tombstone) size_t n_busy; // Number of buckets where the key is not the empty key void* empty_key; void* tombstone_key; SOPC_Dict_KeyHash_Fct hash_func; SOPC_Dict_KeyEqual_Fct equal_func; SOPC_Dict_Free_Fct key_free; SOPC_Dict_Free_Fct value_free; }; static const size_t DICT_INITIAL_SIZE = 16; // Shrink the table if the number of items is below SHRINK_FACTOR * (number of buckets) // We never shrink below DICT_INITIAL_SIZE. static const double SHRINK_FACTOR = 0.4; static void set_empty_keys(SOPC_DictBucket* buckets, size_t n_buckets, void* empty_key) { for (size_t i = 0; i < n_buckets; ++i) { buckets[i].key = empty_key; } } static void free_bucket(SOPC_DictBucket* b, SOPC_Dict_Free_Fct key_free, SOPC_Dict_Free_Fct value_free) { if (key_free != NULL) { key_free(b->key); } if (value_free != NULL) { value_free(b->value); } } static bool insert_item(SOPC_Dict* d, uint64_t hash, void* key, void* value, bool overwrite) { for (size_t i = 0; i < d->size; ++i) { size_t idx = (size_t) HASH_I(hash, i) & d->sizemask; SOPC_DictBucket* b = &d->buckets[idx]; // Normal insert if (b->key == d->empty_key || b->key == d->tombstone_key) { b->key = key; b->value = value; d->n_items++; d->n_busy++; return true; } // Overwriting of existing value if (overwrite && d->equal_func(key, b->key)) { free_bucket(b, d->key_free, d->value_free); b->key = key; b->value = value; return true; } } assert(false && "Cannot find a free bucket?!"); return false; } static bool dict_resize(SOPC_Dict* d, size_t size) { size_t sizemask = size - 1; assert((size & sizemask) == 0); // Ensure we have a power of two SOPC_DictBucket* buckets = SOPC_Calloc(size, sizeof(SOPC_DictBucket)); if (buckets == NULL) { return false; } if (d->empty_key != NULL) { set_empty_keys(buckets, size, d->empty_key); } SOPC_Dict dict_backup = *d; d->n_busy = 0; d->n_items = 0; d->buckets = buckets; d->size = size; d->sizemask = sizemask; bool ok = true; for (size_t i = 0; i < dict_backup.size; ++i) { SOPC_DictBucket* b = &dict_backup.buckets[i]; if ((b->key == d->empty_key) || (b->key == d->tombstone_key)) { continue; } uint64_t hash = d->hash_func(b->key); if (!insert_item(d, hash, b->key, b->value, false)) { ok = false; break; } } if (ok) { SOPC_Free(dict_backup.buckets); } else { *d = dict_backup; } return ok; } SOPC_Dict* SOPC_Dict_Create(void* empty_key, SOPC_Dict_KeyHash_Fct key_hash, SOPC_Dict_KeyEqual_Fct key_equal, SOPC_Dict_Free_Fct key_free, SOPC_Dict_Free_Fct value_free) { SOPC_Dict* d = SOPC_Calloc(1, sizeof(SOPC_Dict)); if (d == NULL) { return NULL; } d->size = DICT_INITIAL_SIZE; d->sizemask = d->size - 1; d->buckets = SOPC_Calloc(d->size, sizeof(SOPC_DictBucket)); bool ok = d->buckets != NULL; if (!ok) { SOPC_Dict_Delete(d); return NULL; } d->empty_key = empty_key; d->tombstone_key = empty_key; d->hash_func = key_hash; d->equal_func = key_equal; d->key_free = key_free; d->value_free = value_free; // We only go touch the memory if the empty key is not 0, since the memory // for our buckets is always alloced with calloc. if (d->empty_key != NULL) { set_empty_keys(d->buckets, d->size, d->empty_key); } return d; } void SOPC_Dict_Delete(SOPC_Dict* d) { if (d != NULL) { // buckets can be NULL if called from SOPC_Dict_Create if (d->buckets != NULL) { for (size_t i = 0; i < d->size; ++i) { SOPC_DictBucket* bucket = &d->buckets[i]; if ((bucket->key != d->empty_key) && (bucket->key != d->tombstone_key)) { free_bucket(bucket, d->key_free, d->value_free); } } SOPC_Free(d->buckets); } SOPC_Free(d); } } // Compute the minimum dictionary size (a power of two) given an initial size // and a number of items to store. // The computed value is such that dictionary occupation stays under 50%. static size_t minimum_dict_size(size_t start_size, size_t n_items) { assert((start_size & (start_size - 1)) == 0); size_t size = start_size; while (size < (2 * n_items)) { size *= 2; } return size; } bool SOPC_Dict_Reserve(SOPC_Dict* d, size_t n_items) { assert(d != NULL); return dict_resize(d, minimum_dict_size(d->size, n_items)); } void SOPC_Dict_SetTombstoneKey(SOPC_Dict* d, void* tombstone_key) { assert(d != NULL); assert(d->empty_key != tombstone_key); assert(d->n_busy == 0); d->tombstone_key = tombstone_key; } // Delta is 1 when adding, 0 when removing static bool maybe_resize(SOPC_Dict* d, uint8_t delta) { const size_t shrink_limit = (size_t)(SHRINK_FACTOR * ((double) d->size)); size_t target_size = d->size; if (((delta > 0) && ((d->n_busy + delta) > (d->size / 2))) || ((delta == 0) && (d->n_items < shrink_limit))) { // One of the two cases: // - Overpopulation when adding items // - Underpopulation while removing items // // Compute the required number of buckets after eliminating tombstones // and resize. // Ensure the occupation will be under 50% target_size = minimum_dict_size(DICT_INITIAL_SIZE, d->n_items + delta); } return (d->size == target_size) ? true : dict_resize(d, target_size); } bool SOPC_Dict_Insert(SOPC_Dict* d, void* key, void* value) { assert(d != NULL); assert(key != d->empty_key); assert(key != d->tombstone_key); if (!maybe_resize(d, 1)) { return false; } uint64_t hash = d->hash_func(key); return insert_item(d, hash, key, value, true); } static SOPC_DictBucket* get_internal(const SOPC_Dict* d, const void* key) { assert(key != d->empty_key); assert(key != d->tombstone_key); uint64_t hash = d->hash_func(key); for (size_t i = 0; i < d->size; ++i) { uint64_t idx = HASH_I(hash, i) & d->sizemask; const void* bucket_key = d->buckets[idx].key; if (bucket_key == d->empty_key) { break; } // If removals are not supported, we have empty_key == tombstone_key, so // this if never matches. if (bucket_key == d->tombstone_key) { continue; } if (d->equal_func(key, bucket_key)) { return &d->buckets[idx]; } } return NULL; } void* SOPC_Dict_Get(const SOPC_Dict* d, const void* key, bool* found) { assert(d != NULL); SOPC_DictBucket* bucket = get_internal(d, key); if (found != NULL) { *found = (bucket != NULL); } return (bucket != NULL) ? bucket->value : NULL; } void* SOPC_Dict_GetKey(const SOPC_Dict* d, const void* key, bool* found) { assert(d != NULL); SOPC_DictBucket* bucket = get_internal(d, key); if (found != NULL) { *found = (bucket != NULL); } return (bucket != NULL) ? bucket->key : NULL; } void SOPC_Dict_Remove(SOPC_Dict* d, const void* key) { assert(d != NULL); // Check that a tombstone key has been defined assert(d->empty_key != d->tombstone_key); SOPC_DictBucket* bucket = get_internal(d, key); if (bucket == NULL) { return; } free_bucket(bucket, d->key_free, d->value_free); bucket->key = d->tombstone_key; bucket->value = NULL; --d->n_items; // We can ignore failures here, worst case we fail to compact and will try // later. maybe_resize(d, 0); } SOPC_Dict_Free_Fct SOPC_Dict_GetKeyFreeFunc(const SOPC_Dict* d) { assert(d != NULL); return d->key_free; } void SOPC_Dict_SetKeyFreeFunc(SOPC_Dict* d, SOPC_Dict_Free_Fct func) { assert(d != NULL); d->key_free = func; } SOPC_Dict_Free_Fct SOPC_Dict_GetValueFreeFunc(const SOPC_Dict* d) { assert(d != NULL); return d->value_free; } void SOPC_Dict_SetValueFreeFunc(SOPC_Dict* d, SOPC_Dict_Free_Fct func) { assert(d != NULL); d->value_free = func; } size_t SOPC_Dict_Size(const SOPC_Dict* d) { return d->n_items; } size_t SOPC_Dict_Capacity(const SOPC_Dict* d) { return d->size / 2; } void SOPC_Dict_ForEach(SOPC_Dict* d, SOPC_Dict_ForEach_Fct func, void* user_data) { for (size_t i = 0; i < d->size; ++i) { if (d->buckets[i].key != d->empty_key) { func(d->buckets[i].key, d->buckets[i].value, user_data); } } }
/** * WinPR: Windows Portable Runtime * Process Thread Functions * * Copyright 2012 <NAME> <<EMAIL>> * * 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 WINPR_THREAD_H #define WINPR_THREAD_H #include <winpr/winpr.h> #include <winpr/wtypes.h> #include <winpr/handle.h> #ifndef _WIN32 typedef struct _STARTUPINFOA { DWORD cb; LPSTR lpReserved; LPSTR lpDesktop; LPSTR lpTitle; DWORD dwX; DWORD dwY; DWORD dwXSize; DWORD dwYSize; DWORD dwXCountChars; DWORD dwYCountChars; DWORD dwFillAttribute; DWORD dwFlags; WORD wShowWindow; WORD cbReserved2; LPBYTE lpReserved2; HANDLE hStdInput; HANDLE hStdOutput; HANDLE hStdError; } STARTUPINFOA, *LPSTARTUPINFOA; typedef struct _STARTUPINFOW { DWORD cb; LPWSTR lpReserved; LPWSTR lpDesktop; LPWSTR lpTitle; DWORD dwX; DWORD dwY; DWORD dwXSize; DWORD dwYSize; DWORD dwXCountChars; DWORD dwYCountChars; DWORD dwFillAttribute; DWORD dwFlags; WORD wShowWindow; WORD cbReserved2; LPBYTE lpReserved2; HANDLE hStdInput; HANDLE hStdOutput; HANDLE hStdError; } STARTUPINFOW, *LPSTARTUPINFOW; #ifdef UNICODE typedef STARTUPINFOW STARTUPINFO; typedef LPSTARTUPINFOW LPSTARTUPINFO; #else typedef STARTUPINFOA STARTUPINFO; typedef LPSTARTUPINFOA LPSTARTUPINFO; #endif /* Process */ WINPR_API BOOL CreateProcessA(LPCSTR lpApplicationName, LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCSTR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); WINPR_API BOOL CreateProcessW(LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); WINPR_API BOOL CreateProcessAsUserA(HANDLE hToken, LPCSTR lpApplicationName, LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCSTR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); WINPR_API BOOL CreateProcessAsUserW(HANDLE hToken, LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation); #ifdef UNICODE #define CreateProcess CreateProcessW #define CreateProcessAsUser CreateProcessAsUserW #else #define CreateProcess CreateProcessA #define CreateProcessAsUser CreateProcessAsUserA #endif WINPR_API VOID ExitProcess(UINT uExitCode); WINPR_API HANDLE _GetCurrentProcess(VOID); WINPR_API DWORD GetCurrentProcessId(VOID); WINPR_API BOOL TerminateProcess(HANDLE hProcess, UINT uExitCode); /* Thread */ #define CREATE_SUSPENDED 0x00000004 #define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000 WINPR_API HANDLE CreateThread(LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId); WINPR_API HANDLE CreateRemoteThread(HANDLE hProcess, LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId); WINPR_API VOID ExitThread(DWORD dwExitCode); WINPR_API HANDLE _GetCurrentThread(VOID); WINPR_API DWORD GetCurrentThreadId(VOID); WINPR_API DWORD ResumeThread(HANDLE hThread); WINPR_API DWORD SuspendThread(HANDLE hThread); WINPR_API BOOL SwitchToThread(VOID); WINPR_API BOOL TerminateThread(HANDLE hThread, DWORD dwExitCode); /* Processor */ WINPR_API DWORD GetCurrentProcessorNumber(VOID); /* Thread-Local Storage */ #define TLS_OUT_OF_INDEXES ((DWORD) 0xFFFFFFFF) WINPR_API DWORD TlsAlloc(VOID); WINPR_API LPVOID TlsGetValue(DWORD dwTlsIndex); WINPR_API BOOL TlsSetValue(DWORD dwTlsIndex, LPVOID lpTlsValue); WINPR_API BOOL TlsFree(DWORD dwTlsIndex); #else /* * GetCurrentProcess / GetCurrentThread cause a conflict on Mac OS X */ #define _GetCurrentProcess GetCurrentProcess #define _GetCurrentThread GetCurrentThread #endif #endif /* WINPR_THREAD_H */
<gh_stars>1-10 /* * Copyright (c) 2015, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define CC_QUICK_COMPILE #include "Expression.h" #include <inttypes.h> #include "ExpressionEvaluator.h" #include "TypeCallbacks.h" static CCExpressionValue *CCExpressionValueCreateFromString(CCAllocatorType Allocator, const char *Input, size_t Length); static CCExpression CCExpressionParse(const char **Source); static CCExpression CCExpressionRetainValueCopy(CCExpression Value); const CCExpressionValueCopy CCExpressionRetainedValueCopy = CCExpressionRetainValueCopy; static CCExpression CCExpressionValueAtomOrStringCopy(CCExpression Value) { return (CCExpressionGetType(Value) == CCExpressionValueTypeAtom ? CCExpressionCreateAtom : CCExpressionCreateString)(Value->allocator, CCExpressionGetType(Value) == CCExpressionValueTypeAtom ? CCExpressionGetAtom(Value) : CCExpressionGetString(Value), TRUE); } static CCExpression CCExpressionValueListCopy(CCExpression Value) { CCExpression Copy = CCExpressionCreateList(Value->allocator); CCOrderedCollection(CCExpression) List = CCExpressionGetList(Copy); CC_COLLECTION_FOREACH(CCExpression, Element, CCExpressionGetList(Value)) { CCExpression CopiedElement = CCExpressionCopy(Element); CCExpressionStateSetSuper(CopiedElement, Copy); CCOrderedCollectionAppendElement(List, &CopiedElement); } return Copy; } static CCExpression CCExpressionRetainValueCopy(CCExpression Value) { return CCExpressionCreateCustomType(Value->allocator, CCExpressionGetType(Value), CCRetain(CCExpressionGetData(Value)), Value->copy, Value->destructor); } static void CCExpressionDestructor(CCExpression Expression) { if (Expression->destructor) Expression->destructor(CCExpressionGetData(Expression)); if (Expression->state.values) CCDictionaryDestroy(Expression->state.values); if ((Expression->state.result) && (Expression->state.result != Expression)) CCExpressionDestroy(Expression->state.result); if (Expression->state.private) CCExpressionDestroy(Expression->state.private); } CCExpression CCExpressionCreate(CCAllocatorType Allocator, CCExpressionValueType Type) { CCExpression Expression = CCMalloc(CC_ALIGNED_ALLOCATOR(8)/*Allocator*/, sizeof(*Expression), NULL, CC_DEFAULT_ERROR_CALLBACK); if (!Expression) { CC_LOG_ERROR("Failed to create expression due to allocation failing. Allocation size: %zu", sizeof(*Expression)); return NULL; } CCMemorySetDestructor(Expression, (CCMemoryDestructorCallback)CCExpressionDestructor); Expression->type = Type; switch (Type) { case CCExpressionValueTypeAtom: case CCExpressionValueTypeString: Expression->destructor = (CCExpressionValueDestructor)CCStringDestroy; Expression->copy = CCExpressionValueAtomOrStringCopy; break; case CCExpressionValueTypeList: #if CC_EXPRESSION_ENABLE_CONSTANT_LISTS Expression->list.items = CCCollectionCreateWithImplementation(Allocator, CCCollectionHintOrdered | CCCollectionHintSizeSmall, sizeof(CCExpression), CCExpressionDestructorForCollection, CCCollectionFastArray); Expression->list.constant = FALSE; #else Expression->list = CCCollectionCreateWithImplementation(Allocator, CCCollectionHintOrdered | CCCollectionHintSizeSmall, sizeof(CCExpression), CCExpressionDestructorForCollection, CCCollectionFastArray); #endif Expression->destructor = (CCExpressionValueDestructor)CCCollectionDestroy; Expression->copy = CCExpressionValueListCopy; break; default: Expression->destructor = NULL; Expression->copy = NULL; break; } Expression->state = (CCExpressionState){ .values = NULL, .super = NULL, .result = NULL, .remove = NULL, .private = NULL }; Expression->allocator = Allocator; return Expression; } CCExpression CCExpressionCreateNull(CCAllocatorType Allocator) { #if CC_EXPRESSION_ENABLE_TAGGED_TYPES return (CCExpression)CCExpressionTaggedExtendedNull; #else CCExpression Expression = CCExpressionCreate(Allocator, CCExpressionValueTypeNull); return Expression; #endif } CCExpression CCExpressionCreateAtom(CCAllocatorType Allocator, CCString Atom, _Bool Copy) { const CCChar Prefix = CCStringGetCharacterAtIndex(Atom, 0), Suffix = CCStringGetCharacterAtIndex(Atom, CCStringGetLength(Atom) - 1); #if CC_EXPRESSION_ENABLE_TAGGED_TYPES && CC_EXPRESSION_STRICT_NAMING_RULES if ((Prefix == '.') || (Prefix == '@') || (Prefix == '&')) { } else if ((Prefix == ':') || (Suffix == ':')) { } else { uintptr_t EvalIndex = CCExpressionEvaluatorIndexForName(Atom); if ((EvalIndex != SIZE_MAX) && ((EvalIndex & CCExpressionTaggedFunctionIndexMask) == EvalIndex)) { if (!Copy) CCStringDestroy(Atom); return (CCExpression)((EvalIndex << CCExpressionTaggedFunctionIndexBits) | (CCExpressionAtomTypeFunction << CCExpressionTaggedAtomTaggedBits) | CCExpressionTaggedExtendedAtom); } } #endif CCExpression Expression = CCExpressionCreate(Allocator, CCExpressionValueTypeAtom); #if CC_EXPRESSION_STRICT_NAMING_RULES if ((Prefix == '.') || (Prefix == '@') || (Prefix == '&')) { Expression->atom.kind = CCExpressionAtomTypeState | (Suffix == '!' ? CCExpressionAtomTypeOperationSet : CCExpressionAtomTypeOperationGet); } else if ((Prefix == ':') || (Suffix == ':')) { Expression->atom.kind = CCExpressionAtomTypeSymbol; } else Expression->atom.kind = CCExpressionAtomTypeFunction; Expression->atom.name = Copy ? CCStringCopy(Atom) : Atom; #else Expression->atom = Copy ? CCStringCopy(Atom) : Atom; #endif return Expression; } #if CC_EXPRESSION_STRICT_NAMING_RULES CCString CCExpressionGetAtomFunctionName(size_t Index) { return CCExpressionEvaluatorNameForIndex(Index); } #endif CCExpressionEvaluator CCExpressionGetFunctionEvaluator(CCExpression Expression) { CCExpressionEvaluator Eval = NULL; if ((Expression) && (CCExpressionGetType(Expression) == CCExpressionValueTypeAtom)) { #if CC_EXPRESSION_STRICT_NAMING_RULES if (CCExpressionGetAtomType(Expression) == CCExpressionAtomTypeFunction) { Eval = CCExpressionIsTagged(Expression) ? CCExpressionEvaluatorForIndex((uintptr_t)Expression >> CCExpressionTaggedFunctionIndexBits) : CCExpressionEvaluatorForName(CCExpressionGetAtom(Expression)); } #else Eval = CCExpressionEvaluatorForName(CCExpressionGetAtom(Expression)); #endif } return Eval; } CCExpression CCExpressionCreateInteger(CCAllocatorType Allocator, int32_t Value) { #if CC_HARDWARE_PTR_64 && CC_EXPRESSION_ENABLE_TAGGED_TYPES return (CCExpression)(((uintptr_t)Value << CCExpressionTaggedIntegerTaggedBits) | CCExpressionTaggedExtendedInteger); #else #if CC_EXPRESSION_ENABLE_TAGGED_TYPES _Static_assert((CCExpressionTaggedExtendedMask | CCExpressionTaggedMask) == 31, "If base tagged size changes this must be changed"); /* (vvvvvvvv vvvvvvvv vvvvvvvv vvvvvvvv) vvvvvvvv vvvvvvvv vvvvvvvv vvsxxxxx x = tagged bits s = signed bit v = value bits 5 bits = tagging 1 bit = signed flag (sizeof(uintptr_t) * 8) - 6 = value bits If signed flag is set, then it counts down from -1 (high range). So 32-bits the range of a tagged integer is: -67108864 to 67108863 64-bits can fit the entire range INT32_MIN to INT32_MAX */ const uintptr_t MaxValue = UINTPTR_MAX >> CCExpressionTaggedIntegerTaggedBits; if ((Value <= MaxValue) || (Value >= (-MaxValue - 1))) { _Static_assert(sizeof(Value) == 4, "Need to change the signed bit as is for int32_t"); const _Bool Signed = Value & 0x80000000; if (Signed) { return (CCExpression)(((uintptr_t)~(-1 + (Value + 1)) << CCExpressionTaggedIntegerTaggedBits) | CCExpressionTaggedIntegerSignedFlag | CCExpressionTaggedExtendedInteger); } else { return (CCExpression)(((uintptr_t)Value << CCExpressionTaggedIntegerTaggedBits) | CCExpressionTaggedExtendedInteger); } } #endif CCExpression Expression = CCExpressionCreate(Allocator, CCExpressionValueTypeInteger); Expression->integer = Value; return Expression; #endif } CCExpression CCExpressionCreateFloat(CCAllocatorType Allocator, float Value) { #if CC_HARDWARE_PTR_64 && CC_EXPRESSION_ENABLE_TAGGED_TYPES return (CCExpression)(((uintptr_t)*(uint32_t*)&Value << CCExpressionTaggedFloatTaggedBits) | CCExpressionTaggedExtendedFloat); #else #if CC_HARDWARE_PTR_32 && CC_EXPRESSION_ENABLE_TAGGED_TYPES /* eeeeeeee mmmmmmmm mmmmmmmm mmsxxxxx x = tagged bits s = signed bit m = mantissa bits (only thing reduced from normal binary32) e = exponent bits This isn't a perfect implementation, as unsure what ranges of values would really care about. But it's fast to implement. If revisiting in the future: - we can probably assume we care about 0.0 - 1.0, - probably don't need denormals or NANs, or INFINITY - probably don't care about very large floats either, so probably only wouldn't want an exponent higher than 140 or somewhere around there. */ _Static_assert(sizeof(Value) == 4, "Need to change the format as is for float/binary32"); const uint32_t v = *(uint32_t*)&Value; const uint32_t Mantissa = v & 0x7fffff; if ((Mantissa & 0x1ffff) == Mantissa) { return (CCExpression)((uintptr_t)((v & 0xff800000) | (Mantissa << CCExpressionTaggedFloatTaggedBits) | CCExpressionTaggedExtendedFloat)); } #endif CCExpression Expression = CCExpressionCreate(Allocator, CCExpressionValueTypeFloat); Expression->real = Value; return Expression; #endif } CCExpression CCExpressionCreateString(CCAllocatorType Allocator, CCString Input, _Bool Copy) { CCString String = Copy ? CCStringCopy(Input) : Input; #if CC_EXPRESSION_ENABLE_TAGGED_TYPES if (String & 3) return (CCExpression)String; #endif CCExpression Expression = CCExpressionCreate(Allocator, CCExpressionValueTypeString); Expression->string = String; return Expression; } CCExpression CCExpressionCreateList(CCAllocatorType Allocator) { return CCExpressionCreate(Allocator, CCExpressionValueTypeList); } CCExpression CCExpressionCreateCustomType(CCAllocatorType Allocator, CCExpressionValueType Type, void *Data, CCExpressionValueCopy Copy, CCExpressionValueDestructor Destructor) { CCExpression Expression = CCExpressionCreate(Allocator, Type); Expression->data = Data; Expression->copy = Copy; Expression->destructor = Destructor; return Expression; } void CCExpressionDestroy(CCExpression Expression) { CCAssertLog(Expression, "Expression must not be NULL"); if (CCExpressionIsTagged(Expression)) return; CC_SAFE_Free(Expression); } CCExpressionValueType CCExpressionGetTaggedType(uintptr_t Expression) { if ((Expression & CCExpressionTaggedMask) == CCExpressionTaggedExtended) { switch (Expression & CCExpressionTaggedExtendedMask) { case CCExpressionTaggedExtendedNull: return CCExpressionValueTypeNull; case CCExpressionTaggedExtendedAtom: return CCExpressionValueTypeAtom; case CCExpressionTaggedExtendedInteger: return CCExpressionValueTypeInteger; case CCExpressionTaggedExtendedFloat: return CCExpressionValueTypeFloat; default: return CCExpressionValueTypeUnspecified; } } else return CCExpressionValueTypeString; } void CCExpressionChangeOwnership(CCExpression Expression, CCExpressionValueCopy Copy, CCExpressionValueDestructor Destructor) { CCAssertLog(Expression, "Expression must not be NULL"); if (CCExpressionIsTagged(Expression)) return; Expression->copy = Copy; Expression->destructor = Destructor; } CCExpression CCExpressionCopy(CCExpression Expression) { CCAssertLog(Expression, "Expression must not be NULL"); if (CCExpressionIsTagged(Expression)) return Expression; CCExpression Copy = NULL; if (Expression->copy) Copy = Expression->copy(Expression); else { Copy = CCExpressionCreate(Expression->allocator, CCExpressionGetType(Expression)); memcpy(Copy, Expression, sizeof(CCExpressionValue)); } if (Copy) { CCExpressionCopyState(Expression, Copy); } return Copy; } static CCExpression CCExpressionDeepFindEquivalentExpression(CCExpression Root, CCExpression Expression) { CCExpression Super = CCExpressionStateGetSuper(Expression); if (!Super) return Root; Root = CCExpressionDeepFindEquivalentExpression(Root, Super); CCOrderedCollection(CCExpression) List = CCExpressionGetList(Super); const size_t Index = CCOrderedCollectionGetIndex(List, CCCollectionFindElement(List, &Expression, NULL)); return *(CCExpression*)CCOrderedCollectionGetElementAtIndex(CCExpressionGetList(Root), Index); } CCExpression CCExpressionDeepCopy(CCExpression Expression) { CCAssertLog(Expression, "Expression must not be NULL"); if (CCExpressionIsTagged(Expression)) return Expression; CCExpression Root = CCExpressionCopy(CCExpressionStateGetSuperRoot(Expression)); return CCExpressionDeepFindEquivalentExpression(Root, Expression); } CCExpression CCExpressionRetain(CCExpression Expression) { CCAssertLog(Expression, "Expression must not be NULL"); return CCExpressionIsTagged(Expression) ? Expression : CCRetain(Expression); } CCExpression CCExpressionCreateFromSourceFile(FSPath Path) { CCExpression Expression = NULL; FSHandle Handle; if (FSHandleOpen(Path, FSHandleTypeRead, &Handle) == FSOperationSuccess) { size_t Size = FSManagerGetSize(Path); char *Source; CC_SAFE_Malloc(Source, sizeof(char) * (Size + 1), CC_LOG_ERROR("Failed to create expression from source due to allocation failure. Allocation size (%zu)", sizeof(char) * (Size + 1)); return NULL; ); FSHandleRead(Handle, &Size, Source, FSBehaviourDefault); Source[Size] = 0; Expression = CCExpressionCreateFromSource(Source); FSHandleClose(Handle); CC_SAFE_Free(Source); const char *Filename = FSPathGetFilenameString(Path); CCExpressionCreateState(Expression, CC_STRING("@file"), CCExpressionCreateString(CC_STD_ALLOCATOR, CCStringCreate(CC_STD_ALLOCATOR, CCStringEncodingUTF8 | CCStringHintCopy, Filename), FALSE), FALSE, NULL, FALSE); const char *Dir = FSPathGetPathString(Path); CCExpressionCreateState(Expression, CC_STRING("@cd"), CCExpressionCreateString(CC_STD_ALLOCATOR, CCStringCreateWithSize(CC_STD_ALLOCATOR, CCStringEncodingUTF8 | CCStringHintCopy, Dir, strlen(Dir) - strlen(Filename)), FALSE), FALSE, NULL, FALSE); } else CC_LOG_ERROR("Failed to create expression from source due to error opening source: %s", FSPathGetFullPathString(Path)); return Expression; } CCExpression CCExpressionCreateFromSource(const char *Source) { CCAssertLog(Source, "Source must not be NULL"); return CCExpressionParse(&Source); } static CCString CCExpressionStringConvertEscapes(CCAllocatorType Allocator, const char *Input, size_t Length) { CCString s1 = CCStringCreateWithSize(Allocator, CCStringEncodingASCII | CCStringHintCopy, Input, Length); CCString s2 = CCStringCreateByReplacingOccurrencesOfGroupedStrings(s1, (CCString[4]){ CC_STRING("\\\""), CC_STRING("\\n"), CC_STRING("\\t"), CC_STRING("\\\\") }, (CCString[4]){ CC_STRING("\""), CC_STRING("\n"), CC_STRING("\t"), CC_STRING("\\") }, 4); CCStringDestroy(s1); return s2; } static CCExpressionValue *CCExpressionValueCreateFromString(CCAllocatorType Allocator, const char *Input, size_t Length) { CCExpressionValueType Type = CCExpressionValueTypeAtom; if (*Input == '"') { Type = CCExpressionValueTypeString; Length--; Input++; } else if (isdigit(*Input)) Type = CCExpressionValueTypeInteger; else if ((*Input == '.') && (Length > 1) && (isdigit(Input[1]))) Type = CCExpressionValueTypeFloat; else if ((*Input == '-') && (Length > 1) && (isdigit(Input[1]))) Type = CCExpressionValueTypeInteger; if ((Type == CCExpressionValueTypeInteger) && (memchr(Input, '.', Length))) Type = CCExpressionValueTypeFloat; switch (Type) { case CCExpressionValueTypeAtom: { if (!strncmp(Input, "#f", Length)) return CCExpressionCreateInteger(Allocator, 0); else if (!strncmp(Input, "#t", Length)) return CCExpressionCreateInteger(Allocator, 1); else return CCExpressionCreateAtom(Allocator, CCStringCreateWithSize(Allocator, CCStringEncodingASCII | CCStringHintCopy, Input, Length), FALSE); } case CCExpressionValueTypeInteger: return CCExpressionCreateInteger(Allocator, (int32_t)strtol(Input, NULL, 10)); case CCExpressionValueTypeFloat: return CCExpressionCreateFloat(Allocator, (float)strtod(Input, NULL)); case CCExpressionValueTypeString: return CCExpressionCreateString(Allocator, CCExpressionStringConvertEscapes(Allocator, Input, Length), FALSE); default: break; } return NULL; } #if CC_EXPRESSION_ENABLE_CONSTANT_LISTS && CC_EXPRESSION_STRICT_NAMING_RULES static _Bool CCExpressionIsConstant(CCExpression Expression) { switch (CCExpressionGetType(Expression)) { case CCExpressionValueTypeInteger: case CCExpressionValueTypeFloat: case CCExpressionValueTypeString: return TRUE; case CCExpressionValueTypeList: return Expression->list.constant; case CCExpressionValueTypeAtom: return (CCExpressionGetAtomType(Expression) & CCExpressionAtomTypeKindMask) == CCExpressionAtomTypeKindSymbol; } return FALSE; } #endif static CCExpression CCExpressionParse(const char **Source) { CCExpression Expr = NULL; const char *Value = NULL; _Bool IsStr = FALSE, IsComment = FALSE, IsEscape = FALSE; for (char c = 0; (c = **Source); (*Source)++) { if ((!IsComment) && (!IsStr) && (c == '(')) { if (Expr) { CCExpression Val = CCExpressionParse(Source); CCOrderedCollectionAppendElement(CCExpressionGetList(Expr), &Val); #if CC_EXPRESSION_ENABLE_CONSTANT_LISTS && CC_EXPRESSION_STRICT_NAMING_RULES if (Expr->list.constant) Expr->list.constant = CCExpressionIsConstant(Val); #endif } else { Expr = CCExpressionCreate(CC_STD_ALLOCATOR, CCExpressionValueTypeExpression); #if CC_EXPRESSION_ENABLE_CONSTANT_LISTS && CC_EXPRESSION_STRICT_NAMING_RULES Expr->list.constant = TRUE; #endif } } else if ((Expr) && (!IsComment) && (!IsStr) && (c == ')')) { if (Value) { CCExpression Val = CCExpressionValueCreateFromString(CC_STD_ALLOCATOR, Value, *Source - Value); if (!Val) { CCExpressionDestroy(Expr); return NULL; } CCOrderedCollectionAppendElement(CCExpressionGetList(Expr), &Val); #if CC_EXPRESSION_ENABLE_CONSTANT_LISTS && CC_EXPRESSION_STRICT_NAMING_RULES if (Expr->list.constant) Expr->list.constant = CCExpressionIsConstant(Val); #endif Value = NULL; } break; } else if ((Expr) && (!IsComment) && (!IsEscape) && (c == '"')) { if (IsStr) { CCExpression Val = CCExpressionValueCreateFromString(CC_STD_ALLOCATOR, Value, *Source - Value); if (!Val) { CCExpressionDestroy(Expr); return NULL; } CCOrderedCollectionAppendElement(CCExpressionGetList(Expr), &Val); #if CC_EXPRESSION_ENABLE_CONSTANT_LISTS && CC_EXPRESSION_STRICT_NAMING_RULES if (Expr->list.constant) Expr->list.constant = CCExpressionIsConstant(Val); #endif Value = NULL; } else Value = *Source; IsStr = !IsStr; } else if ((!IsStr) && (c == ';')) { IsComment = TRUE; } else if ((Expr) && (!IsComment) && (!IsStr)) { if (!isspace(c)) { if (!Value) Value = *Source; } else if (Value) { CCExpression Val = CCExpressionValueCreateFromString(CC_STD_ALLOCATOR, Value, *Source - Value); if (!Val) { CCExpressionDestroy(Expr); return NULL; } CCOrderedCollectionAppendElement(CCExpressionGetList(Expr), &Val); #if CC_EXPRESSION_ENABLE_CONSTANT_LISTS && CC_EXPRESSION_STRICT_NAMING_RULES if (Expr->list.constant) Expr->list.constant = CCExpressionIsConstant(Val); #endif Value = NULL; } } else if (c == '\n') { IsComment = FALSE; } else if (IsEscape) { IsEscape = FALSE; } else if (c == '\\') { IsEscape = TRUE; } } return Expr; } static void CCExpressionPrintStatement(CCExpression Expression) { const CCExpressionValueType Type = CCExpressionGetType(Expression); switch (Type) { case CCExpressionValueTypeNull: printf("<null>"); break; case CCExpressionValueTypeAtom: { CC_STRING_TEMP_BUFFER(Buffer, CCExpressionGetAtom(Expression)) printf("%s", Buffer); break; } case CCExpressionValueTypeInteger: printf("%" PRId32, CCExpressionGetInteger(Expression)); break; case CCExpressionValueTypeFloat: printf("%f", CCExpressionGetFloat(Expression)); break; case CCExpressionValueTypeString: { CC_STRING_TEMP_BUFFER(Buffer, CCExpressionGetString(Expression)) printf("\"%s\"", Buffer); break; } case CCExpressionValueTypeList: { printf("( "); CC_COLLECTION_FOREACH(CCExpression, Expr, CCExpressionGetList(Expression)) { CCExpressionPrintStatement(Expr); printf(" "); } printf(")"); break; } default: { #if CC_HARDWARE_ENDIAN_LITTLE char Identifier[5] = { (Type >> 24) & 0xff, (Type >> 16) & 0xff, (Type >> 8) & 0xff, Type & 0xff, 0 }; #else char Identifier[5] = { Type & 0xff, (Type >> 8) & 0xff, (Type >> 16) & 0xff, (Type >> 24) & 0xff, 0 }; #endif printf("<%p:%s>", Expression, Identifier); break; } } } void CCExpressionPrint(CCExpression Expression) { CCExpressionPrintStatement(Expression); printf("\n"); } #if CC_EXPRESSION_STATS _Thread_local size_t CCExpressionEvalCount = 0; _Thread_local size_t CCExpressionEvalCost = 0; #endif CCExpression CCExpressionEvaluate(CCExpression Expression) { CCAssertLog(Expression, "Expression must not be NULL"); #if CC_EXPRESSION_STATS CCExpressionEvalCount++; #endif if (CCExpressionIsTagged(Expression)) return Expression; if ((Expression->state.result) && (Expression->state.result != Expression)) CCExpressionDestroy(Expression->state.result); Expression->state.result = Expression; if ((CCExpressionGetType(Expression) == CCExpressionValueTypeExpression) && (CCCollectionGetCount(CCExpressionGetList(Expression)))) { #if CC_EXPRESSION_ENABLE_CONSTANT_LISTS if (Expression->list.constant) return Expression; #endif _Bool IsList = TRUE; CC_COLLECTION_FOREACH(CCExpression, Expr, CCExpressionGetList(Expression)) { CCExpressionStateSetSuper(Expr, Expression); } CCExpression *Expr = CCOrderedCollectionGetElementAtIndex(CCExpressionGetList(Expression), 0); if (Expr) { CCExpression Func = CCExpressionEvaluate(*Expr); if ((Func) && (CCExpressionGetType(Func) == CCExpressionValueTypeAtom)) { CCExpressionEvaluator Eval = CCExpressionGetFunctionEvaluator(Func); if (Eval) { Expression->state.result = Eval(Expression); IsList = FALSE; } #if CC_EXPRESSION_STRICT_NAMING_RULES else if (CCExpressionGetAtomType(Func) == (CCExpressionAtomTypeState | CCExpressionAtomTypeOperationSet)) //set state #else else if (CCStringHasSuffix(CCExpressionGetAtom(Func), CC_STRING("!"))) //set state #endif { CCString Name = CCStringCopySubstring(CCExpressionGetAtom(Func), 0, CCStringGetLength(CCExpressionGetAtom(*Expr)) - 1); CCExpression State = NULL; if (CCCollectionGetCount(CCExpressionGetList(Expression)) == 2) { State = CCExpressionSetState(Expression, Name, CCExpressionEvaluate(*(CCExpression*)CCOrderedCollectionGetElementAtIndex(CCExpressionGetList(Expression), 1)), TRUE); } else { CCExpression Value = CCExpressionCreateList(Expression->allocator); CCEnumerator Enumerator; CCCollectionGetEnumerator(CCExpressionGetList(Expression), &Enumerator); for (CCExpression *Arg = CCCollectionEnumeratorNext(&Enumerator); Arg; Arg = CCCollectionEnumeratorNext(&Enumerator)) { CCOrderedCollectionAppendElement(CCExpressionGetList(Value), &(CCExpression){ CCExpressionRetain(CCExpressionEvaluate(*Arg)) }); } State = CCExpressionSetState(Expression, Name, Value, FALSE); } CCStringDestroy(Name); if (State) { Expression->state.result = CCExpressionRetain(State); IsList = FALSE; } } } if (!Expression->state.result) //mark expression for removal { CCExpression Super = Expression->state.super; if (!Super->state.remove) Super->state.remove = CCCollectionCreate(CC_STD_ALLOCATOR, CCCollectionHintSizeSmall, sizeof(CCCollectionEntry), NULL); CCCollectionEntry Entry = CCCollectionFindElement(CCExpressionGetList(Super), &Expression, NULL); if (Entry) CCCollectionInsertElement(Super->state.remove, &Entry); Expression->state.result = CCExpressionCreateNull(CC_STD_ALLOCATOR); } } if (Expression->state.remove) //remove expression { CCCollectionRemoveCollection(CCExpressionGetList(Expression), Expression->state.remove); CCCollectionDestroy(Expression->state.remove); Expression->state.remove = NULL; } if (IsList) //evaluate list { #if CC_EXPRESSION_ENABLE_CONSTANT_LISTS Expression->list.constant = TRUE; #endif Expression->state.result = CCExpressionCreateList(Expression->allocator); CCEnumerator Enumerator; CCCollectionGetEnumerator(CCExpressionGetList(Expression), &Enumerator); CCExpression *Expr = CCCollectionEnumeratorGetCurrent(&Enumerator); if (Expr) { CCExpression Item = CCExpressionRetain(CCExpressionGetResult(*Expr)); CCOrderedCollectionAppendElement(CCExpressionGetList(Expression->state.result), &Item); #if CC_EXPRESSION_ENABLE_CONSTANT_LISTS if ((Item != *Expr) || ((CCExpressionGetType(Item) == CCExpressionValueTypeExpression) && (!Item->list.constant))) Expression->list.constant = FALSE; #endif while ((Expr = CCCollectionEnumeratorNext(&Enumerator))) { Item = CCExpressionRetain(CCExpressionEvaluate(*Expr)); CCOrderedCollectionAppendElement(CCExpressionGetList(Expression->state.result), &Item); #if CC_EXPRESSION_ENABLE_CONSTANT_LISTS if ((Item != *Expr) || ((CCExpressionGetType(Item) == CCExpressionValueTypeExpression) && (!Item->list.constant))) Expression->list.constant = FALSE; #endif } } } } #if CC_EXPRESSION_STRICT_NAMING_RULES else if ((Expression->state.super) && (CCExpressionGetType(Expression) == CCExpressionValueTypeAtom) && (CCExpressionGetAtomType(Expression) == (CCExpressionAtomTypeState | CCExpressionAtomTypeOperationGet))) //get state #else else if ((Expression->state.super) && (CCExpressionGetType(Expression) == CCExpressionValueTypeAtom)) //get state #endif { CCExpression State = CCExpressionGetState(Expression->state.super, CCExpressionGetAtom(Expression)); if (State) Expression->state.result = CCExpressionRetain(State); } if (Expression->state.result) CCExpressionStateSetSuper(Expression->state.result, Expression->state.super); #if CC_EXPRESSION_STATS CCExpressionEvalCost++; #endif return Expression->state.result; } typedef struct { CCExpression value; CCExpression invalidate; } CCExpressionStateValue; CC_DICTIONARY_DECLARE(CCString, CCExpressionStateValue); static CCExpressionStateValue *CCExpressionGetStateValue(CCExpression Expression, CCString Name) { if (!Expression) return NULL; CCExpressionStateValue *Value = NULL; if (Expression->state.values) Value = CCDictionaryGetValue(Expression->state.values, &Name); if (Value) { if (Value->value) CCExpressionStateSetSuper(Value->value, Expression); if (Value->invalidate) CCExpressionStateSetSuper(Value->invalidate, Expression); return Value; } return CCExpressionGetStateValue(Expression->state.super, Name); } static void CCExpressionStateValueElementDestructor(CCDictionary(CCString, CCExpressionStateValue) Dictionary, CCExpressionStateValue *Element) { if (Element->value) CCExpressionDestroy(Element->value); if (Element->invalidate) CCExpressionDestroy(Element->invalidate); } void CCExpressionCreateState(CCExpression Expression, CCString Name, CCExpression Value, _Bool Retain, CCExpression Invalidator, _Bool InvalidatorRetain) { CCAssertLog(Expression, "Expression must not be NULL"); if ((Expression->state.values) && (CCDictionaryFindKey(Expression->state.values, &Name))) { CC_LOG_ERROR_CUSTOM("Creating duplicate state (%S)", Name); } else { if (!Expression->state.values) Expression->state.values = CCDictionaryCreate(Expression->allocator, CCDictionaryHintSizeSmall | CCDictionaryHintHeavyFinding, sizeof(CCString), sizeof(CCExpressionStateValue), &(CCDictionaryCallbacks){ .getHash = CCStringHasherForDictionary, .compareKeys = CCStringComparatorForDictionary, .keyDestructor = CCStringDestructorForDictionary, .valueDestructor = (CCDictionaryElementDestructor)CCExpressionStateValueElementDestructor }); CCExpressionStateValue StateValue = { .value = NULL, .invalidate = NULL }; if (Invalidator) { StateValue.invalidate = InvalidatorRetain ? CCExpressionRetain(Invalidator) : Invalidator; if (Value) { StateValue.value = CCExpressionCopy(Value); if (!Retain) CCExpressionDestroy(Value); } } else if (Value) StateValue.value = Retain ? CCExpressionRetain(Value) : Value; CCDictionarySetValue(Expression->state.values, &(CCString){ CCStringCopy(Name) }, &StateValue); } } CCExpression CCExpressionGetStateStrict(CCExpression Expression, CCString Name) { CCAssertLog(Expression, "Expression must not be NULL"); CCExpressionStateValue *State = NULL; if (Expression->state.values) State = CCDictionaryGetValue(Expression->state.values, &Name); if ((State) && (State->value)) { CCExpression Result = CCExpressionGetResult(State->value); if ((Result) && (State->invalidate)) { CCExpression Invalidate = CCExpressionEvaluate(State->invalidate); if (CCExpressionGetType(Invalidate) == CCExpressionValueTypeInteger) { if (!CCExpressionGetInteger(Invalidate)) return Result; } else CC_LOG_ERROR_CUSTOM("State (%S) invalidator is not valid, should return a boolean", Name); } return CCExpressionEvaluate(State->value); } return NULL; } CCExpression CCExpressionGetState(CCExpression Expression, CCString Name) { CCAssertLog(Expression, "Expression must not be NULL"); CCExpressionStateValue *State = CCExpressionGetStateValue(Expression, Name); if ((State) && (State->value)) { CCExpression Result = CCExpressionGetResult(State->value); if (State->invalidate) { CCExpression Invalidate = CCExpressionEvaluate(State->invalidate); if (Result) { if (CCExpressionGetType(Invalidate) == CCExpressionValueTypeInteger) { if (!CCExpressionGetInteger(Invalidate)) return Result; } else CC_LOG_ERROR_CUSTOM("State (%S) invalidator is not valid, should return a boolean", Name); } } return CCExpressionEvaluate(State->value); } return NULL; } CCExpression CCExpressionSetState(CCExpression Expression, CCString Name, CCExpression Value, _Bool Retain) { CCAssertLog(Expression, "Expression must not be NULL"); CCExpressionStateValue *State = CCExpressionGetStateValue(Expression, Name); if (State) { if (State->value) CCExpressionDestroy(State->value); if (State->invalidate) { if (Value) { State->value = CCExpressionCopy(Value); if (!Retain) CCExpressionDestroy(Value); } } else if (Value) State->value = Retain ? CCExpressionRetain(Value) : Value; return State->value; } return NULL; } void CCExpressionSetStateInvalidator(CCExpression Expression, CCString Name, CCExpression Invalidator, _Bool Retain) { CCAssertLog(Expression, "Expression must not be NULL"); CCExpressionStateValue *State = CCExpressionGetStateValue(Expression, Name); if (State) { if (State->invalidate) CCExpressionDestroy(State->invalidate); else if (State->value) { CCExpression Value = State->value; State->value = CCExpressionCopy(Value); CCExpressionDestroy(Value); } State->invalidate = Retain ? (Invalidator ? CCExpressionRetain(Invalidator) : NULL) : Invalidator; } } void CCExpressionCopyState(CCExpression Source, CCExpression Destination) { CCAssertLog(Source && Destination, "Source and destination expressions must not be NULL"); if ((CCExpressionIsTagged(Source)) || (CCExpressionIsTagged(Destination))) return; if (Source->state.values) { CC_DICTIONARY_FOREACH_KEY(CCString, Key, Source->state.values) { CCExpressionStateValue *State = CCDictionaryGetEntry(Source->state.values, CCDictionaryEnumeratorGetEntry(&CC_DICTIONARY_CURRENT_KEY_ENUMERATOR)); CCExpressionCreateState(Destination, Key, State->value, TRUE, State->invalidate, TRUE); } } else if (Destination->state.values) { CCDictionaryDestroy(Destination->state.values); Destination->state.values = NULL; } Destination->state.private = NULL; Destination->state.remove = NULL; Destination->state.result = NULL; Destination->state.super = Source->state.super; } void CCExpressionPrintState(CCExpression Expression) { if (Expression->state.super) { printf("super:%p: ", Expression->state.super); CCExpressionPrint(Expression->state.super); } if (Expression->state.result) { printf("result:%p: ", Expression->state.result); CCExpressionPrint(Expression->state.result); } if (Expression->state.values) { printf("state:\n{\n"); CC_DICTIONARY_FOREACH_KEY(CCString, Key, Expression->state.values) { CCExpressionStateValue *Value = CCDictionaryGetEntry(Expression->state.values, CCDictionaryEnumeratorGetEntry(&CC_DICTIONARY_CURRENT_KEY_ENUMERATOR)); CC_STRING_TEMP_BUFFER(Buffer, Key) printf("\t%s:%p: ", Buffer, Value->value); if (Value->value) CCExpressionPrint(Value->value); else printf("\n"); } printf("}\n"); } if (Expression->state.remove) { printf("remove:\n{\n"); CC_COLLECTION_FOREACH(CCCollectionEntry, Entry, Expression->state.remove) { CCExpression *Expr = CCCollectionGetElement(CCExpressionGetList(Expression), Entry); printf("\t%p: ", Expr); if (Expr) CCExpressionPrint(*Expr); else printf("\n"); } printf("}\n"); } }
<gh_stars>1-10 //--------------------------------------------------------------------- // // XMLNetProfile.h - a simple xml profile manager for mach plugins // // similar to the CXMLProfile that mach uses // // based on our examination of the CXMLProfile and the xml // files used by mach the assumption has been made that it // is a simple xml tree with no duplicate node paths. // // simplified sample: // // <profile> // <preferences> // <value1>123</value1> // ... // </preferences> // ... (other sections belonging to mach) // <GreatPlugin> <- our plugin section // <value1>234</value1> // <table> <- subsection if simplePath // <value1>111</value1> // </table> // ... // </GreatPlugin> // </profile> // // based on observation it is our recommendation that the // user choose a section name based on their plugin name // plus the word 'Plugin' if it is not already part of the // name. be aware that there is no registered list of plugin // names that we are aware of so you could collide with other // section names already in use. by appending the word 'Plugin' // you shouldn't collide with any of mach's sections. // // syntax and functions have been changed to a new format. // a ReadDouble and WriteDouble have been added. // a simplePath option has been added. // // at construction the following parameters are required: // // profileFileSpec - path to xml file // sectionName - this plugin's section name // simplePath - a bool that turns on simple path // logic to allow for a tree inside // of the section // // each Read (ReadInt, ReadDouble, ReadString) can be // supplied with a default value to return if entry does // not exist. the defaults can also be left off and standard // values will be returned as defaults. // // if simplePath is turned on the entry name can contain // forward slashes '/' to define a layered xml tree inside // of the plugin's section. again based on the assumption // of no duplicate fully qualified node paths. // // we recommend that you test the return value of the Load() // function. if it is false, then a problem occurred (and a // warning message has been displayed). if you proceed with // a save then you could overwrite the xml file with a profile // that only contains your information. // //--------------------------------------------------------------------- using namespace System; using namespace System::Collections::Specialized; using namespace System::Data; using namespace System::Windows::Forms; using namespace System::Xml; public ref class XMLNetProfile { public: XmlDocument^ profileDocument; // the underlying DOM String^ profileFileSpec; // full file specification String^ sectionName; // section name (plugin name) bool simplePath; // allows simple path tree //----------------------------------------------------------------- // // XMLNetProfile() - constructor // // must be provided with the file specification, section name // and simple path bool. // //----------------------------------------------------------------- XMLNetProfile(String^ profileFileSpec, String^ sectionName, bool simplePath) { this->profileFileSpec = profileFileSpec; this->sectionName = sectionName; this->simplePath = simplePath; profileDocument = gcnew XmlDocument(); } //----------------------------------------------------------------- // // Load() - load the xml into the DOM // //----------------------------------------------------------------- bool Load() { bool success = true; try { profileDocument->Load(profileFileSpec); } catch(XmlException^ e) { MessageBox::Show("Warning - " + e->Message, "XMLNetProfile"); success = false; } return success; } //----------------------------------------------------------------- // // Save() - save the DOM back into the xml file // //----------------------------------------------------------------- bool Save() { bool success = true; try { XmlTextWriter^ tr = gcnew XmlTextWriter(profileFileSpec, System::Text::Encoding::ASCII); tr->Formatting = Formatting::Indented; profileDocument->WriteContentTo(tr); tr->Close(); } catch(XmlException^ e) { MessageBox::Show("Warning - " + e->Message, "XMLNetProfile"); success = false; } return success; } //----------------------------------------------------------------- // // ReadBool() - read a bool from the DOM // // optional default value or assume false for default value // //----------------------------------------------------------------- bool ReadBool(String^ entry) { return ReadBool(entry, false); } bool ReadBool(String^ entry, bool defaultValue) { XmlNode^ node = FindEntry(entry); bool val = defaultValue; if (node) { if (node->InnerText == Boolean::TrueString) val = true; else val = false; } return val; } //----------------------------------------------------------------- // // ReadInt() - read an integer from the DOM // // optional default value or assume 0 for default value // //----------------------------------------------------------------- int ReadInt(String^ entry) { return ReadInt(entry, 0); } int ReadInt(String^ entry, int defaultValue) { XmlNode^ node = FindEntry(entry); int val = defaultValue; if (node) val = Convert::ToInt32(node->InnerText); return val; } //----------------------------------------------------------------- // // ReadDouble() - read a double from the DOM // // optional default value or assume 0 for default value // //----------------------------------------------------------------- double ReadDouble(String^ entry) { return ReadDouble(entry, 0); } double ReadDouble(String^ entry, double defaultValue) { XmlNode^ node = FindEntry(entry); double val = defaultValue; if (node) val = Convert::ToDouble(node->InnerText); return val; } //----------------------------------------------------------------- // // ReadString() - read a string from the DOM // // optional default value or assume "" for default value // //----------------------------------------------------------------- String^ ReadString(String^ entry) { return ReadString(entry, ""); } String^ ReadString(String^ entry, String^ defaultValue) { XmlNode^ node = FindEntry(entry); String^ val = defaultValue; if (node) val = node->InnerText; return val; } //----------------------------------------------------------------- // // WriteBool() - writes a bool to the DOM // //----------------------------------------------------------------- void WriteBool(String^ entry, bool value) { WriteString(entry, value.ToString()); } //----------------------------------------------------------------- // // WriteInt() - writes an int to the DOM // //----------------------------------------------------------------- void WriteInt(String^ entry, int value) { WriteString(entry, value.ToString()); } //----------------------------------------------------------------- // // WriteDouble() - writes a double to the DOM // //----------------------------------------------------------------- void WriteDouble(String^ entry, double value) { WriteString(entry, value.ToString()); } //----------------------------------------------------------------- // // WriteString() - writes a String to the DOM // //----------------------------------------------------------------- void WriteString(String^ entry, String^ value) { SetEntry(entry, value); } //----------------------------------------------------------------- // // FindEntry() - finds the node that match the entry in the DOM // // if the node does not exist it returns a nullptr // //----------------------------------------------------------------- XmlNode^ FindEntry(String^ entry) { StringCollection^ levels = gcnew StringCollection(); array<Char>^ chars = {'/'}; XmlNode^ node = profileDocument->DocumentElement; levels->Add(sectionName); if (simplePath) levels->AddRange(entry->Split(chars)); else levels->Add(entry); for each (String^ lvl in levels) { if (node) { XmlNode^ child = node->FirstChild; while (child) { if (child->Name == lvl) break; child = child->NextSibling; } node = child; } } return node; } //----------------------------------------------------------------- // // SetEntry() - sets the innertext of the node that match the entry // // it will create nodes as needed to create the descending // tree of nodes // //----------------------------------------------------------------- void SetEntry(String^ entry, String^ innerText) { StringCollection^ levels = gcnew StringCollection(); array<Char>^ chars = {'/'}; XmlNode^ node = profileDocument->DocumentElement; if (node == nullptr) { node = profileDocument->CreateElement("profile"); profileDocument->AppendChild(node); } levels->Add(sectionName); if (simplePath) levels->AddRange(entry->Split(chars)); else levels->Add(entry); for each (String^ lvl in levels) { XmlNode^ child = node->FirstChild; while (child) { if (child->Name == lvl) break; child = child->NextSibling; } if (child == nullptr) { child = profileDocument->CreateElement(lvl); node->AppendChild(child); } node = child; } node->InnerText = innerText; } };
// SPDX-License-Identifier: GPL-2.0 // Copyright (C) 2005-2017 Andes Technology Corporation #include <linux/types.h> #include <linux/mm.h> #include <linux/string.h> #include <linux/dma-noncoherent.h> #include <linux/io.h> #include <linux/cache.h> #include <linux/highmem.h> #include <linux/slab.h> #include <asm/cacheflush.h> #include <asm/tlbflush.h> #include <asm/proc-fns.h> /* * This is the page table (2MB) covering uncached, DMA consistent allocations */ static pte_t *consistent_pte; static DEFINE_RAW_SPINLOCK(consistent_lock); /* * VM region handling support. * * This should become something generic, handling VM region allocations for * vmalloc and similar (ioremap, module space, etc). * * I envisage vmalloc()'s supporting vm_struct becoming: * * struct vm_struct { * struct vm_region region; * unsigned long flags; * struct page **pages; * unsigned int nr_pages; * unsigned long phys_addr; * }; * * get_vm_area() would then call vm_region_alloc with an appropriate * struct vm_region head (eg): * * struct vm_region vmalloc_head = { * .vm_list = LIST_HEAD_INIT(vmalloc_head.vm_list), * .vm_start = VMALLOC_START, * .vm_end = VMALLOC_END, * }; * * However, vmalloc_head.vm_start is variable (typically, it is dependent on * the amount of RAM found at boot time.) I would imagine that get_vm_area() * would have to initialise this each time prior to calling vm_region_alloc(). */ struct arch_vm_region { struct list_head vm_list; unsigned long vm_start; unsigned long vm_end; struct page *vm_pages; }; static struct arch_vm_region consistent_head = { .vm_list = LIST_HEAD_INIT(consistent_head.vm_list), .vm_start = CONSISTENT_BASE, .vm_end = CONSISTENT_END, }; static struct arch_vm_region *vm_region_alloc(struct arch_vm_region *head, size_t size, int gfp) { unsigned long addr = head->vm_start, end = head->vm_end - size; unsigned long flags; struct arch_vm_region *c, *new; new = kmalloc(sizeof(struct arch_vm_region), gfp); if (!new) goto out; raw_spin_lock_irqsave(&consistent_lock, flags); list_for_each_entry(c, &head->vm_list, vm_list) { if ((addr + size) < addr) goto nospc; if ((addr + size) <= c->vm_start) goto found; addr = c->vm_end; if (addr > end) goto nospc; } found: /* * Insert this entry _before_ the one we found. */ list_add_tail(&new->vm_list, &c->vm_list); new->vm_start = addr; new->vm_end = addr + size; raw_spin_unlock_irqrestore(&consistent_lock, flags); return new; nospc: raw_spin_unlock_irqrestore(&consistent_lock, flags); kfree(new); out: return NULL; } static struct arch_vm_region *vm_region_find(struct arch_vm_region *head, unsigned long addr) { struct arch_vm_region *c; list_for_each_entry(c, &head->vm_list, vm_list) { if (c->vm_start == addr) goto out; } c = NULL; out: return c; } void *arch_dma_alloc(struct device *dev, size_t size, dma_addr_t *handle, gfp_t gfp, unsigned long attrs) { struct page *page; struct arch_vm_region *c; unsigned long order; u64 mask = ~0ULL, limit; pgprot_t prot = pgprot_noncached(PAGE_KERNEL); if (!consistent_pte) { pr_err("%s: not initialized\n", __func__); dump_stack(); return NULL; } if (dev) { mask = dev->coherent_dma_mask; /* * Sanity check the DMA mask - it must be non-zero, and * must be able to be satisfied by a DMA allocation. */ if (mask == 0) { dev_warn(dev, "coherent DMA mask is unset\n"); goto no_page; } } /* * Sanity check the allocation size. */ size = PAGE_ALIGN(size); limit = (mask + 1) & ~mask; if ((limit && size >= limit) || size >= (CONSISTENT_END - CONSISTENT_BASE)) { pr_warn("coherent allocation too big " "(requested %#x mask %#llx)\n", size, mask); goto no_page; } order = get_order(size); if (mask != 0xffffffff) gfp |= GFP_DMA; page = alloc_pages(gfp, order); if (!page) goto no_page; /* * Invalidate any data that might be lurking in the * kernel direct-mapped region for device DMA. */ { unsigned long kaddr = (unsigned long)page_address(page); memset(page_address(page), 0, size); cpu_dma_wbinval_range(kaddr, kaddr + size); } /* * Allocate a virtual address in the consistent mapping region. */ c = vm_region_alloc(&consistent_head, size, gfp & ~(__GFP_DMA | __GFP_HIGHMEM)); if (c) { pte_t *pte = consistent_pte + CONSISTENT_OFFSET(c->vm_start); struct page *end = page + (1 << order); c->vm_pages = page; /* * Set the "dma handle" */ *handle = page_to_phys(page); do { BUG_ON(!pte_none(*pte)); /* * x86 does not mark the pages reserved... */ SetPageReserved(page); set_pte(pte, mk_pte(page, prot)); page++; pte++; } while (size -= PAGE_SIZE); /* * Free the otherwise unused pages. */ while (page < end) { __free_page(page); page++; } return (void *)c->vm_start; } if (page) __free_pages(page, order); no_page: *handle = ~0; return NULL; } void arch_dma_free(struct device *dev, size_t size, void *cpu_addr, dma_addr_t handle, unsigned long attrs) { struct arch_vm_region *c; unsigned long flags, addr; pte_t *ptep; size = PAGE_ALIGN(size); raw_spin_lock_irqsave(&consistent_lock, flags); c = vm_region_find(&consistent_head, (unsigned long)cpu_addr); if (!c) goto no_area; if ((c->vm_end - c->vm_start) != size) { pr_err("%s: freeing wrong coherent size (%ld != %d)\n", __func__, c->vm_end - c->vm_start, size); dump_stack(); size = c->vm_end - c->vm_start; } ptep = consistent_pte + CONSISTENT_OFFSET(c->vm_start); addr = c->vm_start; do { pte_t pte = ptep_get_and_clear(&init_mm, addr, ptep); unsigned long pfn; ptep++; addr += PAGE_SIZE; if (!pte_none(pte) && pte_present(pte)) { pfn = pte_pfn(pte); if (pfn_valid(pfn)) { struct page *page = pfn_to_page(pfn); /* * x86 does not mark the pages reserved... */ ClearPageReserved(page); __free_page(page); continue; } } pr_crit("%s: bad page in kernel page table\n", __func__); } while (size -= PAGE_SIZE); flush_tlb_kernel_range(c->vm_start, c->vm_end); list_del(&c->vm_list); raw_spin_unlock_irqrestore(&consistent_lock, flags); kfree(c); return; no_area: raw_spin_unlock_irqrestore(&consistent_lock, flags); pr_err("%s: trying to free invalid coherent area: %p\n", __func__, cpu_addr); dump_stack(); } /* * Initialise the consistent memory allocation. */ static int __init consistent_init(void) { pgd_t *pgd; pmd_t *pmd; pte_t *pte; int ret = 0; do { pgd = pgd_offset(&init_mm, CONSISTENT_BASE); pmd = pmd_alloc(&init_mm, pgd, CONSISTENT_BASE); if (!pmd) { pr_err("%s: no pmd tables\n", __func__); ret = -ENOMEM; break; } /* The first level mapping may be created in somewhere. * It's not necessary to warn here. */ /* WARN_ON(!pmd_none(*pmd)); */ pte = pte_alloc_kernel(pmd, CONSISTENT_BASE); if (!pte) { ret = -ENOMEM; break; } consistent_pte = pte; } while (0); return ret; } core_initcall(consistent_init); static inline void cache_op(phys_addr_t paddr, size_t size, void (*fn)(unsigned long start, unsigned long end)) { struct page *page = pfn_to_page(paddr >> PAGE_SHIFT); unsigned offset = paddr & ~PAGE_MASK; size_t left = size; unsigned long start; do { size_t len = left; if (PageHighMem(page)) { void *addr; if (offset + len > PAGE_SIZE) { if (offset >= PAGE_SIZE) { page += offset >> PAGE_SHIFT; offset &= ~PAGE_MASK; } len = PAGE_SIZE - offset; } addr = kmap_atomic(page); start = (unsigned long)(addr + offset); fn(start, start + len); kunmap_atomic(addr); } else { start = (unsigned long)phys_to_virt(paddr); fn(start, start + size); } offset = 0; page++; left -= len; } while (left); } void arch_sync_dma_for_device(struct device *dev, phys_addr_t paddr, size_t size, enum dma_data_direction dir) { switch (dir) { case DMA_FROM_DEVICE: break; case DMA_TO_DEVICE: case DMA_BIDIRECTIONAL: cache_op(paddr, size, cpu_dma_wb_range); break; default: BUG(); } } void arch_sync_dma_for_cpu(struct device *dev, phys_addr_t paddr, size_t size, enum dma_data_direction dir) { switch (dir) { case DMA_TO_DEVICE: break; case DMA_FROM_DEVICE: case DMA_BIDIRECTIONAL: cache_op(paddr, size, cpu_dma_inval_range); break; default: BUG(); } }
/* +------------------------------------------------------------------------+ | Zephir Language | +------------------------------------------------------------------------+ | Copyright (c) 2011-2016 Zephir Team (http://www.zephir-lang.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to <EMAIL> so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: <NAME> <<EMAIL>> | | <NAME> <<EMAIL>> | +------------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ext.h" /* represents a connection to a database */ struct _zephir_persist_obj { char *data; } zephir_persist_obj; int zephir_persistent_fetch(zval *return_value, zval *service TSRMLS_DC){ zend_rsrc_list_entry *le; /* try to find if we already have this link in our persistent list */ if (zend_hash_find(&EG(persistent_list), Z_STRVAL_P(service), Z_STRLEN_P(service)+1, (void **) &le)==FAILURE) { } } int zephir_persistent_store(zval *service, zval *object TSRMLS_DC){ //pdo_dbh_t *dbh = NULL; //zend_object_store_set_object(object, dbh TSRMLS_CC); zend_rsrc_list_entry new_le; Z_TYPE(new_le) = 1; new_le.ptr = pestrdup("hello", 1); if (zend_hash_update(&EG(persistent_list), Z_STRVAL_P(service), Z_STRLEN_P(service)+1, (void *) &new_le, sizeof(zend_rsrc_list_entry), NULL)==FAILURE) { //goto err; } //zephir_persistent_store }
// C version #include <stdio.h> #include <time.h> #include <cuda.h> #include <cudaProfiler.h> #define check(err) __check(err, __FILE__, __LINE__) void __check(CUresult err, const char *file, const int line) { if (CUDA_SUCCESS != err) { const char *msg; cuGetErrorName(err, &msg); fprintf(stderr, "CUDA error: %s (%04d) at %s:%i.\n", msg, err, file, line); exit(-1); } } const size_t len = 1000; const size_t ITERATIONS = 5000; float median(float x[], int n) { float temp; int i, j; // the following two loops sort the array x in ascending order for (i = 0; i < n - 1; i++) { for (j = i + 1; j < n; j++) { if (x[j] < x[i]) { // swap elements temp = x[i]; x[i] = x[j]; x[j] = temp; } } } if (n % 2 == 0) { // if there is an even number of elements, return mean of the two elements // in the middle return ((x[n / 2] + x[n / 2 - 1]) / 2.0); } else { // else return the element in the middle return x[n / 2]; } } int main(int argc, char **argv) { check(cuInit(0x0)); CUdevice dev; check(cuDeviceGet(&dev, 0)); CUcontext ctx; check(cuCtxCreate(&ctx, 0, dev)); CUmodule mod; check(cuModuleLoad(&mod, "cuda.ptx")); CUfunction fun; check(cuModuleGetFunction(&fun, mod, "kernel_dummy")); CUdeviceptr gpu_arr; check(cuMemAlloc(&gpu_arr, sizeof(float) * len)); float cpu_time[ITERATIONS]; float gpu_time[ITERATIONS]; for (int i = 0; i < ITERATIONS; i++) { if (i == ITERATIONS - 5) check(cuProfilerStart()); struct timespec cpu_t0, cpu_t1; clock_gettime(CLOCK_MONOTONIC, &cpu_t0); CUevent gpu_t0, gpu_t1; check(cuEventCreate(&gpu_t0, 0x0)); check(cuEventCreate(&gpu_t1, 0x0)); check(cuEventRecord(gpu_t0, NULL)); void *args[3] = {&gpu_arr}; check(cuLaunchKernel(fun, len, 1, 1, 1, 1, 1, 0, 0, args, 0)); check(cuEventRecord(gpu_t1, NULL)); check(cuEventSynchronize(gpu_t1)); clock_gettime(CLOCK_MONOTONIC, &cpu_t1); check(cuEventElapsedTime(&gpu_time[i], gpu_t0, gpu_t1)); gpu_time[i] *= 1000; cpu_time[i] = (cpu_t1.tv_sec - cpu_t0.tv_sec) + (cpu_t1.tv_nsec - cpu_t0.tv_nsec) / 1000.; } check(cuProfilerStop()); printf("CPU time: %.2fus\n", median(cpu_time, ITERATIONS)); printf("GPU time: %.2fus\n", median(gpu_time, ITERATIONS)); return 0; }
/* * main.h * * Created: 8/13/2018 6:28:55 AM * Author: pvallone */ #ifndef MAIN_H_ #define MAIN_H_ //#define LTC_ECB_MODE //#define LTC_CTR_MODE #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif #include <asf.h> void show_menu(void); /* Tests */ int run_hardware_encryption_test(void); int run_hardware_decryption_test(void); int run_hardware_encryp_decrypt_test_random(void); int run_hardware_encryp_decrypt_test_input(char *input, uint8_t *cipher_text, uint8_t *dec_plain_text); int run_encrypted_read_test(char *outout, uint16_t address, uint8_t length); int run_encrypted_write_test(char *input, uint16_t address); int run_tests(void); #endif /* MAIN_H_ */
<reponame>iplo/Chain // Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Component updates can be either differential updates or full updates. // Full updates come in CRX format; differential updates come in CRX-style // archives, but have a different magic number. They contain "commands.json", a // list of commands for the patcher to follow. The patcher uses these commands, // the other files in the archive, and the files from the existing installation // of the component to create the contents of a full update, which is then // installed normally. // Component updates are specified by the 'codebasediff' attribute of an // updatecheck response: // <updatecheck codebase="http://example.com/extension_1.2.3.4.crx" // hash="12345" size="9854" status="ok" version="1.2.3.4" // prodversionmin="192.168.3.11" // codebasediff="http://example.com/diff_1.2.3.4.crx" // hashdiff="123" sizediff="101" // fp="1.123" /> // The component updater will attempt a differential update if it is available // and allowed to, and fall back to a full update if it fails. // // After installation (diff or full), the component updater records "fp", the // fingerprint of the installed files, to later identify the existing files to // the server so that a proper differential update can be provided next cycle. #ifndef CHROME_BROWSER_COMPONENT_UPDATER_COMPONENT_PATCHER_H_ #define CHROME_BROWSER_COMPONENT_UPDATER_COMPONENT_PATCHER_H_ #include "base/basictypes.h" #include "base/callback_forward.h" #include "base/compiler_specific.h" #include "chrome/browser/component_updater/component_unpacker.h" namespace base { class FilePath; } namespace component_updater { class ComponentInstaller; // Applies a delta patch to a single file. Specifically, creates a file at // |output_file| using |input_file| patched according to the algorithm // specified by |patch_type| using |patch_file|. Sets the value of error to // the error code of the failing patch operation, if there is such a failure. class ComponentPatcher { public: // The type of a patch file. enum PatchType { kPatchTypeUnknown, kPatchTypeCourgette, kPatchTypeBsdiff, }; virtual ComponentUnpacker::Error Patch(PatchType patch_type, const base::FilePath& input_file, const base::FilePath& patch_file, const base::FilePath& output_file, int* error) = 0; virtual ~ComponentPatcher() {} }; class ComponentPatcherCrossPlatform : public ComponentPatcher { public: ComponentPatcherCrossPlatform(); virtual ComponentUnpacker::Error Patch(PatchType patch_type, const base::FilePath& input_file, const base::FilePath& patch_file, const base::FilePath& output_file, int* error) OVERRIDE; private: DISALLOW_COPY_AND_ASSIGN(ComponentPatcherCrossPlatform); }; // This function takes an unpacked differential CRX (|input_dir|) and a // component installer, and creates a new (non-differential) unpacked CRX, which // is then installed normally. // The non-differential files are written into the |unpack_dir| directory. // When finished, calls the callback, passing error codes if any errors were // encountered. void DifferentialUpdatePatch( const base::FilePath& input_dir, const base::FilePath& unpack_dir, ComponentPatcher* component_patcher, ComponentInstaller* installer, base::Callback<void(ComponentUnpacker::Error, int)> callback); } // namespace component_updater #endif // CHROME_BROWSER_COMPONENT_UPDATER_COMPONENT_PATCHER_H_
#pragma once #define BONDAGE_VERSION_MAJOR 1 #define BONDAGE_VERSION_MINOR 0 #define BONDAGE_VERSION_PATCH 0 #ifdef _WIN32 # ifdef BONDAGE_BUILD # define BONDAGE_EXPORT __declspec(dllexport) # else # define BONDAGE_EXPORT __declspec(dllimport) # endif # define BONDAGE_BEGIN_WARNING_SCOPE \ __pragma(warning(push))\ __pragma(warning (disable : 4251)) //< needs to have dll-interface to be used by clients of class __pragma(warning (disable : 4481)) //< needs to have dll-interface to be used by clients of class # define BONDAGE_END_WARNING_SCOPE \ __pragma(warning(pop)) #else # define BONDAGE_EXPORT # define BONDAGE_BEGIN_WARNING_SCOPE # define BONDAGE_END_WARNING_SCOPE #endif
<reponame>cstom4994/SourceEngineRebuild //========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: The main manager of the input // // $Revision: $ // $NoKeywords: $ //===========================================================================// #ifndef INPUTMANAGER_H #define INPUTMANAGER_H #ifdef _WIN32 #pragma once #endif #include "gamemanager.h" #include "tier2/keybindings.h" #include "tier1/commandbuffer.h" #include "bitvec.h" //----------------------------------------------------------------------------- // Input management //----------------------------------------------------------------------------- class CInputManager : public CGameManager<> { public: // Inherited from IGameManager virtual bool Init(); virtual void Update(); // Add a command into the command queue void AddCommand(const char *pCommand); private: // Per-frame update of commands void ProcessCommands(); // Purpose: void PrintConCommandBaseDescription(const ConCommandBase *pVar); CKeyBindings m_KeyBindings; CBitVec<BUTTON_CODE_LAST> m_ButtonUpToEngine; CCommandBuffer m_CommandBuffer; }; //----------------------------------------------------------------------------- // Singleton accessor //----------------------------------------------------------------------------- extern CInputManager *g_pInputManager; #endif // INPUTMANAGER_H
<reponame>SoftReaper/Mesa-Renoir-deb<gh_stars>0 /************************************************************************** * * Copyright 2010-2018 VMware, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE * USE OR OTHER DEALINGS IN THE SOFTWARE. * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * **************************************************************************/ /** * @file * s3tc pixel format manipulation. * * @author <NAME> <<EMAIL>> */ #include <llvm/Config/llvm-config.h> #include "util/format/u_format.h" #include "util/u_math.h" #include "util/u_string.h" #include "util/u_cpu_detect.h" #include "util/u_debug.h" #include "lp_bld_arit.h" #include "lp_bld_type.h" #include "lp_bld_const.h" #include "lp_bld_conv.h" #include "lp_bld_gather.h" #include "lp_bld_format.h" #include "lp_bld_logic.h" #include "lp_bld_pack.h" #include "lp_bld_flow.h" #include "lp_bld_printf.h" #include "lp_bld_struct.h" #include "lp_bld_swizzle.h" #include "lp_bld_init.h" #include "lp_bld_debug.h" #include "lp_bld_intr.h" /** * Reverse an interleave2_half * (ie. pick every second element, independent lower/upper halfs) * sse2 can only do that with 32bit (shufps) or larger elements * natively. (Otherwise, and/pack (even) or shift/pack (odd) * could be used, ideally llvm would do that for us.) * XXX: Unfortunately, this does NOT translate to a shufps if those * are int vectors (and casting will not help, llvm needs to recognize it * as "real" float). Instead, llvm will use a pshufd/pshufd/punpcklqdq * sequence which I'm pretty sure is a lot worse despite domain transition * penalties with shufps (except maybe on Nehalem). */ static LLVMValueRef lp_build_uninterleave2_half(struct gallivm_state *gallivm, struct lp_type type, LLVMValueRef a, LLVMValueRef b, unsigned lo_hi) { LLVMValueRef shuffle, elems[LP_MAX_VECTOR_LENGTH]; unsigned i; assert(type.length <= LP_MAX_VECTOR_LENGTH); assert(lo_hi < 2); if (type.length * type.width == 256) { assert(type.length == 8); assert(type.width == 32); static const unsigned shufvals[8] = {0, 2, 8, 10, 4, 6, 12, 14}; for (i = 0; i < type.length; ++i) { elems[i] = lp_build_const_int32(gallivm, shufvals[i] + lo_hi); } } else { for (i = 0; i < type.length; ++i) { elems[i] = lp_build_const_int32(gallivm, 2*i + lo_hi); } } shuffle = LLVMConstVector(elems, type.length); return LLVMBuildShuffleVector(gallivm->builder, a, b, shuffle, ""); } /** * Build shuffle for extending vectors. */ static LLVMValueRef lp_build_const_extend_shuffle(struct gallivm_state *gallivm, unsigned n, unsigned length) { LLVMValueRef elems[LP_MAX_VECTOR_LENGTH]; unsigned i; assert(n <= length); assert(length <= LP_MAX_VECTOR_LENGTH); /* TODO: cache results in a static table */ for(i = 0; i < n; i++) { elems[i] = lp_build_const_int32(gallivm, i); } for (i = n; i < length; i++) { elems[i] = LLVMGetUndef(LLVMInt32TypeInContext(gallivm->context)); } return LLVMConstVector(elems, length); } static LLVMValueRef lp_build_const_unpackx2_shuffle(struct gallivm_state *gallivm, unsigned n) { LLVMValueRef elems[LP_MAX_VECTOR_LENGTH]; unsigned i, j; assert(n <= LP_MAX_VECTOR_LENGTH); /* TODO: cache results in a static table */ for(i = 0, j = 0; i < n; i += 2, ++j) { elems[i + 0] = lp_build_const_int32(gallivm, 0 + j); elems[i + 1] = lp_build_const_int32(gallivm, n + j); elems[n + i + 0] = lp_build_const_int32(gallivm, 0 + n/2 + j); elems[n + i + 1] = lp_build_const_int32(gallivm, n + n/2 + j); } return LLVMConstVector(elems, n * 2); } /* * broadcast 1 element to all elements */ static LLVMValueRef lp_build_const_shuffle1(struct gallivm_state *gallivm, unsigned index, unsigned n) { LLVMValueRef elems[LP_MAX_VECTOR_LENGTH]; unsigned i; assert(n <= LP_MAX_VECTOR_LENGTH); /* TODO: cache results in a static table */ for (i = 0; i < n; i++) { elems[i] = lp_build_const_int32(gallivm, index); } return LLVMConstVector(elems, n); } /* * move 1 element to pos 0, rest undef */ static LLVMValueRef lp_build_shuffle1undef(struct gallivm_state *gallivm, LLVMValueRef a, unsigned index, unsigned n) { LLVMValueRef elems[LP_MAX_VECTOR_LENGTH], shuf; unsigned i; assert(n <= LP_MAX_VECTOR_LENGTH); elems[0] = lp_build_const_int32(gallivm, index); for (i = 1; i < n; i++) { elems[i] = LLVMGetUndef(LLVMInt32TypeInContext(gallivm->context)); } shuf = LLVMConstVector(elems, n); return LLVMBuildShuffleVector(gallivm->builder, a, a, shuf, ""); } static boolean format_dxt1_variant(enum pipe_format format) { return format == PIPE_FORMAT_DXT1_RGB || format == PIPE_FORMAT_DXT1_RGBA || format == PIPE_FORMAT_DXT1_SRGB || format == PIPE_FORMAT_DXT1_SRGBA; } /** * Gather elements from scatter positions in memory into vectors. * This is customised for fetching texels from s3tc textures. * For SSE, typical value is length=4. * * @param length length of the offsets * @param colors the stored colors of the blocks will be extracted into this. * @param codewords the codewords of the blocks will be extracted into this. * @param alpha_lo used for storing lower 32bit of alpha components for dxt3/5 * @param alpha_hi used for storing higher 32bit of alpha components for dxt3/5 * @param base_ptr base pointer, should be a i8 pointer type. * @param offsets vector with offsets */ static void lp_build_gather_s3tc(struct gallivm_state *gallivm, unsigned length, const struct util_format_description *format_desc, LLVMValueRef *colors, LLVMValueRef *codewords, LLVMValueRef *alpha_lo, LLVMValueRef *alpha_hi, LLVMValueRef base_ptr, LLVMValueRef offsets) { LLVMBuilderRef builder = gallivm->builder; unsigned block_bits = format_desc->block.bits; unsigned i; LLVMValueRef elems[8]; LLVMTypeRef type32 = LLVMInt32TypeInContext(gallivm->context); LLVMTypeRef type64 = LLVMInt64TypeInContext(gallivm->context); LLVMTypeRef type32dxt; struct lp_type lp_type32dxt; memset(&lp_type32dxt, 0, sizeof lp_type32dxt); lp_type32dxt.width = 32; lp_type32dxt.length = block_bits / 32; type32dxt = lp_build_vec_type(gallivm, lp_type32dxt); assert(block_bits == 64 || block_bits == 128); assert(length == 1 || length == 4 || length == 8); for (i = 0; i < length; ++i) { elems[i] = lp_build_gather_elem(gallivm, length, block_bits, block_bits, TRUE, base_ptr, offsets, i, FALSE); elems[i] = LLVMBuildBitCast(builder, elems[i], type32dxt, ""); } if (length == 1) { LLVMValueRef elem = elems[0]; if (block_bits == 128) { *alpha_lo = LLVMBuildExtractElement(builder, elem, lp_build_const_int32(gallivm, 0), ""); *alpha_hi = LLVMBuildExtractElement(builder, elem, lp_build_const_int32(gallivm, 1), ""); *colors = LLVMBuildExtractElement(builder, elem, lp_build_const_int32(gallivm, 2), ""); *codewords = LLVMBuildExtractElement(builder, elem, lp_build_const_int32(gallivm, 3), ""); } else { *alpha_lo = LLVMGetUndef(type32); *alpha_hi = LLVMGetUndef(type32); *colors = LLVMBuildExtractElement(builder, elem, lp_build_const_int32(gallivm, 0), ""); *codewords = LLVMBuildExtractElement(builder, elem, lp_build_const_int32(gallivm, 1), ""); } } else { LLVMValueRef tmp[4], cc01, cc23; struct lp_type lp_type32, lp_type64; memset(&lp_type32, 0, sizeof lp_type32); lp_type32.width = 32; lp_type32.length = length; memset(&lp_type64, 0, sizeof lp_type64); lp_type64.width = 64; lp_type64.length = length/2; if (block_bits == 128) { if (length == 8) { for (i = 0; i < 4; ++i) { tmp[0] = elems[i]; tmp[1] = elems[i+4]; elems[i] = lp_build_concat(gallivm, tmp, lp_type32dxt, 2); } } lp_build_transpose_aos(gallivm, lp_type32, elems, tmp); *colors = tmp[2]; *codewords = tmp[3]; *alpha_lo = tmp[0]; *alpha_hi = tmp[1]; } else { LLVMTypeRef type64_vec = LLVMVectorType(type64, length/2); LLVMTypeRef type32_vec = LLVMVectorType(type32, length); for (i = 0; i < length; ++i) { /* no-op shuffle */ elems[i] = LLVMBuildShuffleVector(builder, elems[i], LLVMGetUndef(type32dxt), lp_build_const_extend_shuffle(gallivm, 2, 4), ""); } if (length == 8) { struct lp_type lp_type32_4 = {0}; lp_type32_4.width = 32; lp_type32_4.length = 4; for (i = 0; i < 4; ++i) { tmp[0] = elems[i]; tmp[1] = elems[i+4]; elems[i] = lp_build_concat(gallivm, tmp, lp_type32_4, 2); } } cc01 = lp_build_interleave2_half(gallivm, lp_type32, elems[0], elems[1], 0); cc23 = lp_build_interleave2_half(gallivm, lp_type32, elems[2], elems[3], 0); cc01 = LLVMBuildBitCast(builder, cc01, type64_vec, ""); cc23 = LLVMBuildBitCast(builder, cc23, type64_vec, ""); *colors = lp_build_interleave2_half(gallivm, lp_type64, cc01, cc23, 0); *codewords = lp_build_interleave2_half(gallivm, lp_type64, cc01, cc23, 1); *colors = LLVMBuildBitCast(builder, *colors, type32_vec, ""); *codewords = LLVMBuildBitCast(builder, *codewords, type32_vec, ""); } } } /** Convert from <n x i32> containing 2 x n rgb565 colors * to 2 <n x i32> rgba8888 colors * This is the most optimized version I can think of * should be nearly as fast as decoding only one color * NOTE: alpha channel will be set to 0 * @param colors is a <n x i32> vector containing the rgb565 colors */ static void color_expand2_565_to_8888(struct gallivm_state *gallivm, unsigned n, LLVMValueRef colors, LLVMValueRef *color0, LLVMValueRef *color1) { LLVMBuilderRef builder = gallivm->builder; LLVMValueRef r, g, b, rblo, glo; LLVMValueRef rgblomask, rb, rgb0, rgb1; struct lp_type type, type16, type8; assert(n > 1); memset(&type, 0, sizeof type); type.width = 32; type.length = n; memset(&type16, 0, sizeof type16); type16.width = 16; type16.length = 2 * n; memset(&type8, 0, sizeof type8); type8.width = 8; type8.length = 4 * n; rgblomask = lp_build_const_int_vec(gallivm, type16, 0x0707); colors = LLVMBuildBitCast(builder, colors, lp_build_vec_type(gallivm, type16), ""); /* move r into low 8 bits, b into high 8 bits, g into another reg (low bits) * make sure low bits of r are zero - could use AND but requires constant */ r = LLVMBuildLShr(builder, colors, lp_build_const_int_vec(gallivm, type16, 11), ""); r = LLVMBuildShl(builder, r, lp_build_const_int_vec(gallivm, type16, 3), ""); b = LLVMBuildShl(builder, colors, lp_build_const_int_vec(gallivm, type16, 11), ""); rb = LLVMBuildOr(builder, r, b, ""); rblo = LLVMBuildLShr(builder, rb, lp_build_const_int_vec(gallivm, type16, 5), ""); /* don't have byte shift hence need mask */ rblo = LLVMBuildAnd(builder, rblo, rgblomask, ""); rb = LLVMBuildOr(builder, rb, rblo, ""); /* make sure low bits of g are zero */ g = LLVMBuildAnd(builder, colors, lp_build_const_int_vec(gallivm, type16, 0x07e0), ""); g = LLVMBuildLShr(builder, g, lp_build_const_int_vec(gallivm, type16, 3), ""); glo = LLVMBuildLShr(builder, g, lp_build_const_int_vec(gallivm, type16, 6), ""); g = LLVMBuildOr(builder, g, glo, ""); rb = LLVMBuildBitCast(builder, rb, lp_build_vec_type(gallivm, type8), ""); g = LLVMBuildBitCast(builder, g, lp_build_vec_type(gallivm, type8), ""); rgb0 = lp_build_interleave2_half(gallivm, type8, rb, g, 0); rgb1 = lp_build_interleave2_half(gallivm, type8, rb, g, 1); rgb0 = LLVMBuildBitCast(builder, rgb0, lp_build_vec_type(gallivm, type), ""); rgb1 = LLVMBuildBitCast(builder, rgb1, lp_build_vec_type(gallivm, type), ""); /* rgb0 is rgb00, rgb01, rgb10, rgb11 * instead of rgb00, rgb10, rgb20, rgb30 hence need reshuffle * on x86 this _should_ just generate one shufps... */ *color0 = lp_build_uninterleave2_half(gallivm, type, rgb0, rgb1, 0); *color1 = lp_build_uninterleave2_half(gallivm, type, rgb0, rgb1, 1); } /** Convert from <n x i32> containing rgb565 colors * (in first 16 bits) to <n x i32> rgba8888 colors * bits 16-31 MBZ * NOTE: alpha channel will be set to 0 * @param colors is a <n x i32> vector containing the rgb565 colors */ static LLVMValueRef color_expand_565_to_8888(struct gallivm_state *gallivm, unsigned n, LLVMValueRef colors) { LLVMBuilderRef builder = gallivm->builder; LLVMValueRef rgba, r, g, b, rgblo, glo; LLVMValueRef rbhimask, g6mask, rgblomask; struct lp_type type; memset(&type, 0, sizeof type); type.width = 32; type.length = n; /* color expansion: * first extract and shift colors into their final locations * (high bits - low bits zero at this point) * then replicate highest bits to the lowest bits * note rb replication can be done in parallel but not g * (different shift) * r5mask = 0xf800, g6mask = 0x07e0, b5mask = 0x001f * rhigh = 8, ghigh = 5, bhigh = 19 * rblow = 5, glow = 6 * rgblowmask = 0x00070307 * r = colors >> rhigh * b = colors << bhigh * g = (colors & g6mask) << ghigh * rb = (r | b) rbhimask * rbtmp = rb >> rblow * gtmp = rb >> glow * rbtmp = rbtmp | gtmp * rbtmp = rbtmp & rgblowmask * rgb = rb | g | rbtmp */ g6mask = lp_build_const_int_vec(gallivm, type, 0x07e0); rbhimask = lp_build_const_int_vec(gallivm, type, 0x00f800f8); rgblomask = lp_build_const_int_vec(gallivm, type, 0x00070307); r = LLVMBuildLShr(builder, colors, lp_build_const_int_vec(gallivm, type, 8), ""); b = LLVMBuildShl(builder, colors, lp_build_const_int_vec(gallivm, type, 19), ""); g = LLVMBuildAnd(builder, colors, g6mask, ""); g = LLVMBuildShl(builder, g, lp_build_const_int_vec(gallivm, type, 5), ""); rgba = LLVMBuildOr(builder, r, b, ""); rgba = LLVMBuildAnd(builder, rgba, rbhimask, ""); rgblo = LLVMBuildLShr(builder, rgba, lp_build_const_int_vec(gallivm, type, 5), ""); glo = LLVMBuildLShr(builder, g, lp_build_const_int_vec(gallivm, type, 6), ""); rgblo = LLVMBuildOr(builder, rgblo, glo, ""); rgblo = LLVMBuildAnd(builder, rgblo, rgblomask, ""); rgba = LLVMBuildOr(builder, rgba, g, ""); rgba = LLVMBuildOr(builder, rgba, rgblo, ""); return rgba; } /* * Average two byte vectors. (Will always round up.) */ static LLVMValueRef lp_build_pavgb(struct lp_build_context *bld8, LLVMValueRef v0, LLVMValueRef v1) { struct gallivm_state *gallivm = bld8->gallivm; LLVMBuilderRef builder = gallivm->builder; assert(bld8->type.width == 8); assert(bld8->type.length == 16 || bld8->type.length == 32); if (LLVM_VERSION_MAJOR < 6) { LLVMValueRef intrargs[2]; char *intr_name = bld8->type.length == 32 ? "llvm.x86.avx2.pavg.b" : "llvm.x86.sse2.pavg.b"; intrargs[0] = v0; intrargs[1] = v1; return lp_build_intrinsic(builder, intr_name, bld8->vec_type, intrargs, 2, 0); } else { /* * Must match llvm's autoupgrade of pavg.b intrinsic to be useful. * You better hope the backend code manages to detect the pattern, and * the pattern doesn't change there... */ struct lp_type type_ext = bld8->type; LLVMTypeRef vec_type_ext; LLVMValueRef res; LLVMValueRef ext_one; type_ext.width = 16; vec_type_ext = lp_build_vec_type(gallivm, type_ext); ext_one = lp_build_const_vec(gallivm, type_ext, 1); v0 = LLVMBuildZExt(builder, v0, vec_type_ext, ""); v1 = LLVMBuildZExt(builder, v1, vec_type_ext, ""); res = LLVMBuildAdd(builder, v0, v1, ""); res = LLVMBuildAdd(builder, res, ext_one, ""); res = LLVMBuildLShr(builder, res, ext_one, ""); res = LLVMBuildTrunc(builder, res, bld8->vec_type, ""); return res; } } /** * Calculate 1/3(v1-v0) + v0 * and 2*1/3(v1-v0) + v0 */ static void lp_build_lerp23(struct lp_build_context *bld, LLVMValueRef v0, LLVMValueRef v1, LLVMValueRef *res0, LLVMValueRef *res1) { struct gallivm_state *gallivm = bld->gallivm; LLVMValueRef x, x_lo, x_hi, delta_lo, delta_hi; LLVMValueRef mul_lo, mul_hi, v0_lo, v0_hi, v1_lo, v1_hi, tmp; const struct lp_type type = bld->type; LLVMBuilderRef builder = bld->gallivm->builder; struct lp_type i16_type = lp_wider_type(type); struct lp_build_context bld2; assert(lp_check_value(type, v0)); assert(lp_check_value(type, v1)); assert(!type.floating && !type.fixed && !type.norm && type.width == 8); lp_build_context_init(&bld2, gallivm, i16_type); bld2.type.sign = TRUE; x = lp_build_const_int_vec(gallivm, bld->type, 255*1/3); /* FIXME: use native avx256 unpack/pack */ lp_build_unpack2(gallivm, type, i16_type, x, &x_lo, &x_hi); lp_build_unpack2(gallivm, type, i16_type, v0, &v0_lo, &v0_hi); lp_build_unpack2(gallivm, type, i16_type, v1, &v1_lo, &v1_hi); delta_lo = lp_build_sub(&bld2, v1_lo, v0_lo); delta_hi = lp_build_sub(&bld2, v1_hi, v0_hi); mul_lo = LLVMBuildMul(builder, x_lo, delta_lo, ""); mul_hi = LLVMBuildMul(builder, x_hi, delta_hi, ""); x_lo = LLVMBuildLShr(builder, mul_lo, lp_build_const_int_vec(gallivm, i16_type, 8), ""); x_hi = LLVMBuildLShr(builder, mul_hi, lp_build_const_int_vec(gallivm, i16_type, 8), ""); /* lerp optimization: pack now, do add afterwards */ tmp = lp_build_pack2(gallivm, i16_type, type, x_lo, x_hi); *res0 = lp_build_add(bld, tmp, v0); x_lo = LLVMBuildLShr(builder, mul_lo, lp_build_const_int_vec(gallivm, i16_type, 7), ""); x_hi = LLVMBuildLShr(builder, mul_hi, lp_build_const_int_vec(gallivm, i16_type, 7), ""); /* unlike above still need mask (but add still afterwards). */ x_lo = LLVMBuildAnd(builder, x_lo, lp_build_const_int_vec(gallivm, i16_type, 0xff), ""); x_hi = LLVMBuildAnd(builder, x_hi, lp_build_const_int_vec(gallivm, i16_type, 0xff), ""); tmp = lp_build_pack2(gallivm, i16_type, type, x_lo, x_hi); *res1 = lp_build_add(bld, tmp, v0); } /** * Convert from <n x i64> s3tc dxt1 to <4n x i8> RGBA AoS * @param colors is a <n x i32> vector with n x 2x16bit colors * @param codewords is a <n x i32> vector containing the codewords * @param i is a <n x i32> vector with the x pixel coordinate (0 to 3) * @param j is a <n x i32> vector with the y pixel coordinate (0 to 3) */ static LLVMValueRef s3tc_dxt1_full_to_rgba_aos(struct gallivm_state *gallivm, unsigned n, enum pipe_format format, LLVMValueRef colors, LLVMValueRef codewords, LLVMValueRef i, LLVMValueRef j) { LLVMBuilderRef builder = gallivm->builder; LLVMValueRef color0, color1, color2, color3, color2_2, color3_2; LLVMValueRef rgba, a, colors0, colors1, col0, col1, const2; LLVMValueRef bit_pos, sel_mask, sel_lo, sel_hi, indices; struct lp_type type, type8; struct lp_build_context bld8, bld32; boolean is_dxt1_variant = format_dxt1_variant(format); memset(&type, 0, sizeof type); type.width = 32; type.length = n; memset(&type8, 0, sizeof type8); type8.width = 8; type8.length = 4*n; assert(lp_check_value(type, i)); assert(lp_check_value(type, j)); a = lp_build_const_int_vec(gallivm, type, 0xff000000); lp_build_context_init(&bld32, gallivm, type); lp_build_context_init(&bld8, gallivm, type8); /* * works as follows: * - expand color0/color1 to rgba8888 * - calculate color2/3 (interpolation) according to color0 < color1 rules * - calculate color2/3 according to color0 >= color1 rules * - do selection of color2/3 according to comparison of color0/1 * - extract indices (vector shift). * - use compare/select to select the correct color. Since we have 2bit * indices (and 4 colors), needs at least three compare/selects. */ /* * expand the two colors */ col0 = LLVMBuildAnd(builder, colors, lp_build_const_int_vec(gallivm, type, 0x0000ffff), ""); col1 = LLVMBuildLShr(builder, colors, lp_build_const_int_vec(gallivm, type, 16), ""); if (n > 1) { color_expand2_565_to_8888(gallivm, n, colors, &color0, &color1); } else { color0 = color_expand_565_to_8888(gallivm, n, col0); color1 = color_expand_565_to_8888(gallivm, n, col1); } /* * interpolate colors * color2_1 is 2/3 color0 + 1/3 color1 * color3_1 is 1/3 color0 + 2/3 color1 * color2_2 is 1/2 color0 + 1/2 color1 * color3_2 is 0 */ colors0 = LLVMBuildBitCast(builder, color0, bld8.vec_type, ""); colors1 = LLVMBuildBitCast(builder, color1, bld8.vec_type, ""); /* can combine 2 lerps into one mostly - still looks expensive enough. */ lp_build_lerp23(&bld8, colors0, colors1, &color2, &color3); color2 = LLVMBuildBitCast(builder, color2, bld32.vec_type, ""); color3 = LLVMBuildBitCast(builder, color3, bld32.vec_type, ""); /* dxt3/5 always use 4-color encoding */ if (is_dxt1_variant) { /* fix up alpha */ if (format == PIPE_FORMAT_DXT1_RGBA || format == PIPE_FORMAT_DXT1_SRGBA) { color0 = LLVMBuildOr(builder, color0, a, ""); color1 = LLVMBuildOr(builder, color1, a, ""); color3 = LLVMBuildOr(builder, color3, a, ""); } /* * XXX with sse2 and 16x8 vectors, should use pavgb even when n == 1. * Much cheaper (but we don't care that much if n == 1). */ if ((util_get_cpu_caps()->has_sse2 && n == 4) || (util_get_cpu_caps()->has_avx2 && n == 8)) { color2_2 = lp_build_pavgb(&bld8, colors0, colors1); color2_2 = LLVMBuildBitCast(builder, color2_2, bld32.vec_type, ""); } else { struct lp_type i16_type = lp_wider_type(type8); struct lp_build_context bld2; LLVMValueRef v0_lo, v0_hi, v1_lo, v1_hi, addlo, addhi; lp_build_context_init(&bld2, gallivm, i16_type); bld2.type.sign = TRUE; /* * This isn't as expensive as it looks (the unpack is the same as * for lerp23), with correct rounding. * (Note that while rounding is correct, this will always round down, * whereas pavgb will always round up.) */ /* FIXME: use native avx256 unpack/pack */ lp_build_unpack2(gallivm, type8, i16_type, colors0, &v0_lo, &v0_hi); lp_build_unpack2(gallivm, type8, i16_type, colors1, &v1_lo, &v1_hi); addlo = lp_build_add(&bld2, v0_lo, v1_lo); addhi = lp_build_add(&bld2, v0_hi, v1_hi); addlo = LLVMBuildLShr(builder, addlo, lp_build_const_int_vec(gallivm, i16_type, 1), ""); addhi = LLVMBuildLShr(builder, addhi, lp_build_const_int_vec(gallivm, i16_type, 1), ""); color2_2 = lp_build_pack2(gallivm, i16_type, type8, addlo, addhi); color2_2 = LLVMBuildBitCast(builder, color2_2, bld32.vec_type, ""); } color3_2 = lp_build_const_int_vec(gallivm, type, 0); /* select between colors2/3 */ /* signed compare is faster saves some xors */ type.sign = TRUE; sel_mask = lp_build_compare(gallivm, type, PIPE_FUNC_GREATER, col0, col1); color2 = lp_build_select(&bld32, sel_mask, color2, color2_2); color3 = lp_build_select(&bld32, sel_mask, color3, color3_2); type.sign = FALSE; if (format == PIPE_FORMAT_DXT1_RGBA || format == PIPE_FORMAT_DXT1_SRGBA) { color2 = LLVMBuildOr(builder, color2, a, ""); } } const2 = lp_build_const_int_vec(gallivm, type, 2); /* extract 2-bit index values */ bit_pos = LLVMBuildShl(builder, j, const2, ""); bit_pos = LLVMBuildAdd(builder, bit_pos, i, ""); bit_pos = LLVMBuildAdd(builder, bit_pos, bit_pos, ""); /* * NOTE: This innocent looking shift is very expensive with x86/ssex. * Shifts with per-elemnent shift count get roughly translated to * extract (count), extract (value), shift, move (back to xmm), unpack * per element! * So about 20 instructions here for 4xi32. * Newer llvm versions (3.7+) will not do extract/insert but use a * a couple constant count vector shifts plus shuffles. About same * amount of instructions unfortunately... * Would get much worse with 8xi16 even... * We could actually do better here: * - subtract bit_pos from 128+30, shl 23, convert float to int... * - now do mul with codewords followed by shr 30... * But requires 32bit->32bit mul, sse41 only (well that's emulatable * with 2 32bit->64bit muls...) and not exactly cheap * AVX2, of course, fixes this nonsense. */ indices = LLVMBuildLShr(builder, codewords, bit_pos, ""); /* finally select the colors */ sel_lo = LLVMBuildAnd(builder, indices, bld32.one, ""); sel_lo = lp_build_compare(gallivm, type, PIPE_FUNC_EQUAL, sel_lo, bld32.one); color0 = lp_build_select(&bld32, sel_lo, color1, color0); color2 = lp_build_select(&bld32, sel_lo, color3, color2); sel_hi = LLVMBuildAnd(builder, indices, const2, ""); sel_hi = lp_build_compare(gallivm, type, PIPE_FUNC_EQUAL, sel_hi, const2); rgba = lp_build_select(&bld32, sel_hi, color2, color0); /* fix up alpha */ if (format == PIPE_FORMAT_DXT1_RGB || format == PIPE_FORMAT_DXT1_SRGB) { rgba = LLVMBuildOr(builder, rgba, a, ""); } return LLVMBuildBitCast(builder, rgba, bld8.vec_type, ""); } static LLVMValueRef s3tc_dxt1_to_rgba_aos(struct gallivm_state *gallivm, unsigned n, enum pipe_format format, LLVMValueRef colors, LLVMValueRef codewords, LLVMValueRef i, LLVMValueRef j) { return s3tc_dxt1_full_to_rgba_aos(gallivm, n, format, colors, codewords, i, j); } /** * Convert from <n x i128> s3tc dxt3 to <4n x i8> RGBA AoS * @param colors is a <n x i32> vector with n x 2x16bit colors * @param codewords is a <n x i32> vector containing the codewords * @param alphas is a <n x i64> vector containing the alpha values * @param i is a <n x i32> vector with the x pixel coordinate (0 to 3) * @param j is a <n x i32> vector with the y pixel coordinate (0 to 3) */ static LLVMValueRef s3tc_dxt3_to_rgba_aos(struct gallivm_state *gallivm, unsigned n, enum pipe_format format, LLVMValueRef colors, LLVMValueRef codewords, LLVMValueRef alpha_low, LLVMValueRef alpha_hi, LLVMValueRef i, LLVMValueRef j) { LLVMBuilderRef builder = gallivm->builder; LLVMValueRef rgba, tmp, tmp2; LLVMValueRef bit_pos, sel_mask; struct lp_type type, type8; struct lp_build_context bld; memset(&type, 0, sizeof type); type.width = 32; type.length = n; memset(&type8, 0, sizeof type8); type8.width = 8; type8.length = n*4; assert(lp_check_value(type, i)); assert(lp_check_value(type, j)); lp_build_context_init(&bld, gallivm, type); rgba = s3tc_dxt1_to_rgba_aos(gallivm, n, format, colors, codewords, i, j); rgba = LLVMBuildBitCast(builder, rgba, bld.vec_type, ""); /* * Extract alpha values. Since we now need to select from * which 32bit vector values are fetched, construct selection * mask from highest bit of bit_pos, and use select, then shift * according to the bit_pos (without the highest bit). * Note this is pointless for n == 1 case. Could just * directly use 64bit arithmetic if we'd extract 64bit * alpha value instead of 2x32... */ /* pos = 4*(4j+i) */ bit_pos = LLVMBuildShl(builder, j, lp_build_const_int_vec(gallivm, type, 2), ""); bit_pos = LLVMBuildAdd(builder, bit_pos, i, ""); bit_pos = LLVMBuildShl(builder, bit_pos, lp_build_const_int_vec(gallivm, type, 2), ""); sel_mask = LLVMBuildLShr(builder, bit_pos, lp_build_const_int_vec(gallivm, type, 5), ""); sel_mask = LLVMBuildSub(builder, sel_mask, bld.one, ""); tmp = lp_build_select(&bld, sel_mask, alpha_low, alpha_hi); bit_pos = LLVMBuildAnd(builder, bit_pos, lp_build_const_int_vec(gallivm, type, 0xffffffdf), ""); /* Warning: slow shift with per element count (without avx2) */ /* * Could do pshufb here as well - just use appropriate 2 bits in bit_pos * to select the right byte with pshufb. Then for the remaining one bit * just do shift/select. */ tmp = LLVMBuildLShr(builder, tmp, bit_pos, ""); /* combined expand from a4 to a8 and shift into position */ tmp = LLVMBuildShl(builder, tmp, lp_build_const_int_vec(gallivm, type, 28), ""); tmp2 = LLVMBuildLShr(builder, tmp, lp_build_const_int_vec(gallivm, type, 4), ""); tmp = LLVMBuildOr(builder, tmp, tmp2, ""); rgba = LLVMBuildOr(builder, tmp, rgba, ""); return LLVMBuildBitCast(builder, rgba, lp_build_vec_type(gallivm, type8), ""); } static LLVMValueRef lp_build_lerpdxta(struct gallivm_state *gallivm, LLVMValueRef alpha0, LLVMValueRef alpha1, LLVMValueRef code, LLVMValueRef sel_mask, unsigned n) { /* * note we're doing lerp in 16bit since 32bit pmulld is only available in sse41 * (plus pmullw is actually faster...) * we just pretend our 32bit values (which are really only 8bit) are 16bits. * Note that this is obviously a disaster for the scalar case. */ LLVMBuilderRef builder = gallivm->builder; LLVMValueRef delta, ainterp; LLVMValueRef weight5, weight7, weight; struct lp_type type32, type16, type8; struct lp_build_context bld16; memset(&type32, 0, sizeof type32); type32.width = 32; type32.length = n; memset(&type16, 0, sizeof type16); type16.width = 16; type16.length = 2*n; type16.sign = TRUE; memset(&type8, 0, sizeof type8); type8.width = 8; type8.length = 4*n; lp_build_context_init(&bld16, gallivm, type16); /* 255/7 is a bit off - increase accuracy at the expense of shift later */ sel_mask = LLVMBuildBitCast(builder, sel_mask, bld16.vec_type, ""); weight5 = lp_build_const_int_vec(gallivm, type16, 255*64/5); weight7 = lp_build_const_int_vec(gallivm, type16, 255*64/7); weight = lp_build_select(&bld16, sel_mask, weight7, weight5); alpha0 = LLVMBuildBitCast(builder, alpha0, bld16.vec_type, ""); alpha1 = LLVMBuildBitCast(builder, alpha1, bld16.vec_type, ""); code = LLVMBuildBitCast(builder, code, bld16.vec_type, ""); /* we'll get garbage in the elements which had code 0 (or larger than 5 or 7) but we don't care */ code = LLVMBuildSub(builder, code, bld16.one, ""); weight = LLVMBuildMul(builder, weight, code, ""); weight = LLVMBuildLShr(builder, weight, lp_build_const_int_vec(gallivm, type16, 6), ""); delta = LLVMBuildSub(builder, alpha1, alpha0, ""); ainterp = LLVMBuildMul(builder, delta, weight, ""); ainterp = LLVMBuildLShr(builder, ainterp, lp_build_const_int_vec(gallivm, type16, 8), ""); ainterp = LLVMBuildBitCast(builder, ainterp, lp_build_vec_type(gallivm, type8), ""); alpha0 = LLVMBuildBitCast(builder, alpha0, lp_build_vec_type(gallivm, type8), ""); ainterp = LLVMBuildAdd(builder, alpha0, ainterp, ""); ainterp = LLVMBuildBitCast(builder, ainterp, lp_build_vec_type(gallivm, type32), ""); return ainterp; } static LLVMValueRef s3tc_dxt5_alpha_channel(struct gallivm_state *gallivm, bool is_signed, unsigned n, LLVMValueRef alpha_hi, LLVMValueRef alpha_lo, LLVMValueRef i, LLVMValueRef j) { LLVMBuilderRef builder = gallivm->builder; struct lp_type type, type8; LLVMValueRef tmp, alpha0, alpha1, alphac, alphac0, bit_pos, shift; LLVMValueRef sel_mask, tmp_mask, alpha, alpha64, code_s; LLVMValueRef mask6, mask7, ainterp; LLVMTypeRef i64t = LLVMInt64TypeInContext(gallivm->context); LLVMTypeRef i32t = LLVMInt32TypeInContext(gallivm->context); struct lp_build_context bld32; memset(&type, 0, sizeof type); type.width = 32; type.length = n; memset(&type8, 0, sizeof type8); type8.width = 8; type8.length = n; type8.sign = is_signed; lp_build_context_init(&bld32, gallivm, type); /* this looks pretty complex for vectorization: * extract a0/a1 values * extract code * select weights for interpolation depending on a0 > a1 * mul weights by code - 1 * lerp a0/a1/weights * use selects for getting either a0, a1, interp a, interp a/0.0, interp a/1.0 */ alpha0 = LLVMBuildAnd(builder, alpha_lo, lp_build_const_int_vec(gallivm, type, 0xff), ""); if (is_signed) { alpha0 = LLVMBuildTrunc(builder, alpha0, lp_build_vec_type(gallivm, type8), ""); alpha0 = LLVMBuildSExt(builder, alpha0, lp_build_vec_type(gallivm, type), ""); } alpha1 = LLVMBuildLShr(builder, alpha_lo, lp_build_const_int_vec(gallivm, type, 8), ""); alpha1 = LLVMBuildAnd(builder, alpha1, lp_build_const_int_vec(gallivm, type, 0xff), ""); if (is_signed) { alpha1 = LLVMBuildTrunc(builder, alpha1, lp_build_vec_type(gallivm, type8), ""); alpha1 = LLVMBuildSExt(builder, alpha1, lp_build_vec_type(gallivm, type), ""); } /* pos = 3*(4j+i) */ bit_pos = LLVMBuildShl(builder, j, lp_build_const_int_vec(gallivm, type, 2), ""); bit_pos = LLVMBuildAdd(builder, bit_pos, i, ""); tmp = LLVMBuildAdd(builder, bit_pos, bit_pos, ""); bit_pos = LLVMBuildAdd(builder, bit_pos, tmp, ""); /* get rid of first 2 bytes - saves shifts of alpha_lo/hi */ bit_pos = LLVMBuildAdd(builder, bit_pos, lp_build_const_int_vec(gallivm, type, 16), ""); if (n == 1) { struct lp_type type64; memset(&type64, 0, sizeof type64); type64.width = 64; type64.length = 1; /* This is pretty pointless could avoid by just directly extracting 64bit in the first place but makes it more complicated elsewhere */ alpha_lo = LLVMBuildZExt(builder, alpha_lo, i64t, ""); alpha_hi = LLVMBuildZExt(builder, alpha_hi, i64t, ""); alphac0 = LLVMBuildShl(builder, alpha_hi, lp_build_const_int_vec(gallivm, type64, 32), ""); alphac0 = LLVMBuildOr(builder, alpha_lo, alphac0, ""); shift = LLVMBuildZExt(builder, bit_pos, i64t, ""); alphac0 = LLVMBuildLShr(builder, alphac0, shift, ""); alphac0 = LLVMBuildTrunc(builder, alphac0, i32t, ""); alphac = LLVMBuildAnd(builder, alphac0, lp_build_const_int_vec(gallivm, type, 0x7), ""); } else { /* * Using non-native vector length here (actually, with avx2 and * n == 4 llvm will indeed expand to ymm regs...) * At least newer llvm versions handle that ok. * llvm 3.7+ will even handle the emulated 64bit shift with variable * shift count without extraction (and it's actually easier to * emulate than the 32bit one). */ alpha64 = LLVMBuildShuffleVector(builder, alpha_lo, alpha_hi, lp_build_const_unpackx2_shuffle(gallivm, n), ""); alpha64 = LLVMBuildBitCast(builder, alpha64, LLVMVectorType(i64t, n), ""); shift = LLVMBuildZExt(builder, bit_pos, LLVMVectorType(i64t, n), ""); alphac = LLVMBuildLShr(builder, alpha64, shift, ""); alphac = LLVMBuildTrunc(builder, alphac, bld32.vec_type, ""); alphac = LLVMBuildAnd(builder, alphac, lp_build_const_int_vec(gallivm, type, 0x7), ""); } /* signed compare is faster saves some xors */ type.sign = TRUE; /* alpha0 > alpha1 selection */ sel_mask = lp_build_compare(gallivm, type, PIPE_FUNC_GREATER, alpha0, alpha1); ainterp = lp_build_lerpdxta(gallivm, alpha0, alpha1, alphac, sel_mask, n); /* * if a0 > a1 then we select a0 for case 0, a1 for case 1, interp otherwise. * else we select a0 for case 0, a1 for case 1, * interp for case 2-5, 00 for 6 and 0xff(ffffff) for 7 * a = (c == 0) ? a0 : a1 * a = (c > 1) ? ainterp : a * Finally handle case 6/7 for !(a0 > a1) * a = (!(a0 > a1) && c == 6) ? 0 : a (andnot with mask) * a = (!(a0 > a1) && c == 7) ? 0xffffffff : a (or with mask) */ tmp_mask = lp_build_compare(gallivm, type, PIPE_FUNC_EQUAL, alphac, bld32.zero); alpha = lp_build_select(&bld32, tmp_mask, alpha0, alpha1); tmp_mask = lp_build_compare(gallivm, type, PIPE_FUNC_GREATER, alphac, bld32.one); alpha = lp_build_select(&bld32, tmp_mask, ainterp, alpha); code_s = LLVMBuildAnd(builder, alphac, LLVMBuildNot(builder, sel_mask, ""), ""); mask6 = lp_build_compare(gallivm, type, PIPE_FUNC_EQUAL, code_s, lp_build_const_int_vec(gallivm, type, 6)); mask7 = lp_build_compare(gallivm, type, PIPE_FUNC_EQUAL, code_s, lp_build_const_int_vec(gallivm, type, 7)); if (is_signed) { alpha = lp_build_select(&bld32, mask6, lp_build_const_int_vec(gallivm, type, -127), alpha); alpha = lp_build_select(&bld32, mask7, lp_build_const_int_vec(gallivm, type, 127), alpha); } else { alpha = LLVMBuildAnd(builder, alpha, LLVMBuildNot(builder, mask6, ""), ""); alpha = LLVMBuildOr(builder, alpha, mask7, ""); } /* There can be garbage in upper bits, mask them off for rgtc formats */ alpha = LLVMBuildAnd(builder, alpha, lp_build_const_int_vec(gallivm, type, 0xff), ""); return alpha; } /** * Convert from <n x i128> s3tc dxt5 to <4n x i8> RGBA AoS * @param colors is a <n x i32> vector with n x 2x16bit colors * @param codewords is a <n x i32> vector containing the codewords * @param alphas is a <n x i64> vector containing the alpha values * @param i is a <n x i32> vector with the x pixel coordinate (0 to 3) * @param j is a <n x i32> vector with the y pixel coordinate (0 to 3) */ static LLVMValueRef s3tc_dxt5_full_to_rgba_aos(struct gallivm_state *gallivm, unsigned n, enum pipe_format format, LLVMValueRef colors, LLVMValueRef codewords, LLVMValueRef alpha_lo, LLVMValueRef alpha_hi, LLVMValueRef i, LLVMValueRef j) { LLVMBuilderRef builder = gallivm->builder; LLVMValueRef rgba, alpha; struct lp_type type, type8; struct lp_build_context bld32; memset(&type, 0, sizeof type); type.width = 32; type.length = n; memset(&type8, 0, sizeof type8); type8.width = 8; type8.length = n*4; assert(lp_check_value(type, i)); assert(lp_check_value(type, j)); lp_build_context_init(&bld32, gallivm, type); assert(lp_check_value(type, i)); assert(lp_check_value(type, j)); rgba = s3tc_dxt1_to_rgba_aos(gallivm, n, format, colors, codewords, i, j); rgba = LLVMBuildBitCast(builder, rgba, bld32.vec_type, ""); alpha = s3tc_dxt5_alpha_channel(gallivm, false, n, alpha_hi, alpha_lo, i, j); alpha = LLVMBuildShl(builder, alpha, lp_build_const_int_vec(gallivm, type, 24), ""); rgba = LLVMBuildOr(builder, alpha, rgba, ""); return LLVMBuildBitCast(builder, rgba, lp_build_vec_type(gallivm, type8), ""); } static void lp_build_gather_s3tc_simple_scalar(struct gallivm_state *gallivm, const struct util_format_description *format_desc, LLVMValueRef *dxt_block, LLVMValueRef ptr) { LLVMBuilderRef builder = gallivm->builder; unsigned block_bits = format_desc->block.bits; LLVMValueRef elem, shuf; LLVMTypeRef type32 = LLVMIntTypeInContext(gallivm->context, 32); LLVMTypeRef src_type = LLVMIntTypeInContext(gallivm->context, block_bits); LLVMTypeRef src_ptr_type = LLVMPointerType(src_type, 0); LLVMTypeRef type32_4 = LLVMVectorType(type32, 4); assert(block_bits == 64 || block_bits == 128); ptr = LLVMBuildBitCast(builder, ptr, src_ptr_type, ""); elem = LLVMBuildLoad(builder, ptr, ""); if (block_bits == 128) { /* just return block as is */ *dxt_block = LLVMBuildBitCast(builder, elem, type32_4, ""); } else { LLVMTypeRef type32_2 = LLVMVectorType(type32, 2); shuf = lp_build_const_extend_shuffle(gallivm, 2, 4); elem = LLVMBuildBitCast(builder, elem, type32_2, ""); *dxt_block = LLVMBuildShuffleVector(builder, elem, LLVMGetUndef(type32_2), shuf, ""); } } static void s3tc_store_cached_block(struct gallivm_state *gallivm, LLVMValueRef *col, LLVMValueRef tag_value, LLVMValueRef hash_index, LLVMValueRef cache) { LLVMBuilderRef builder = gallivm->builder; LLVMValueRef ptr, indices[3]; LLVMTypeRef type_ptr4x32; unsigned count; type_ptr4x32 = LLVMPointerType(LLVMVectorType(LLVMInt32TypeInContext(gallivm->context), 4), 0); indices[0] = lp_build_const_int32(gallivm, 0); indices[1] = lp_build_const_int32(gallivm, LP_BUILD_FORMAT_CACHE_MEMBER_TAGS); indices[2] = hash_index; ptr = LLVMBuildGEP(builder, cache, indices, ARRAY_SIZE(indices), ""); LLVMBuildStore(builder, tag_value, ptr); indices[1] = lp_build_const_int32(gallivm, LP_BUILD_FORMAT_CACHE_MEMBER_DATA); hash_index = LLVMBuildMul(builder, hash_index, lp_build_const_int32(gallivm, 16), ""); for (count = 0; count < 4; count++) { indices[2] = hash_index; ptr = LLVMBuildGEP(builder, cache, indices, ARRAY_SIZE(indices), ""); ptr = LLVMBuildBitCast(builder, ptr, type_ptr4x32, ""); LLVMBuildStore(builder, col[count], ptr); hash_index = LLVMBuildAdd(builder, hash_index, lp_build_const_int32(gallivm, 4), ""); } } static LLVMValueRef s3tc_lookup_cached_pixel(struct gallivm_state *gallivm, LLVMValueRef ptr, LLVMValueRef index) { LLVMBuilderRef builder = gallivm->builder; LLVMValueRef member_ptr, indices[3]; indices[0] = lp_build_const_int32(gallivm, 0); indices[1] = lp_build_const_int32(gallivm, LP_BUILD_FORMAT_CACHE_MEMBER_DATA); indices[2] = index; member_ptr = LLVMBuildGEP(builder, ptr, indices, ARRAY_SIZE(indices), ""); return LLVMBuildLoad(builder, member_ptr, "cache_data"); } static LLVMValueRef s3tc_lookup_tag_data(struct gallivm_state *gallivm, LLVMValueRef ptr, LLVMValueRef index) { LLVMBuilderRef builder = gallivm->builder; LLVMValueRef member_ptr, indices[3]; indices[0] = lp_build_const_int32(gallivm, 0); indices[1] = lp_build_const_int32(gallivm, LP_BUILD_FORMAT_CACHE_MEMBER_TAGS); indices[2] = index; member_ptr = LLVMBuildGEP(builder, ptr, indices, ARRAY_SIZE(indices), ""); return LLVMBuildLoad(builder, member_ptr, "tag_data"); } #if LP_BUILD_FORMAT_CACHE_DEBUG static void s3tc_update_cache_access(struct gallivm_state *gallivm, LLVMValueRef ptr, unsigned count, unsigned index) { LLVMBuilderRef builder = gallivm->builder; LLVMValueRef member_ptr, cache_access; assert(index == LP_BUILD_FORMAT_CACHE_MEMBER_ACCESS_TOTAL || index == LP_BUILD_FORMAT_CACHE_MEMBER_ACCESS_MISS); member_ptr = lp_build_struct_get_ptr(gallivm, ptr, index, ""); cache_access = LLVMBuildLoad(builder, member_ptr, "cache_access"); cache_access = LLVMBuildAdd(builder, cache_access, LLVMConstInt(LLVMInt64TypeInContext(gallivm->context), count, 0), ""); LLVMBuildStore(builder, cache_access, member_ptr); } #endif /** * Calculate 1/3(v1-v0) + v0 and 2*1/3(v1-v0) + v0. * The lerp is performed between the first 2 32bit colors * in the source vector, both results are returned packed in result vector. */ static LLVMValueRef lp_build_lerp23_single(struct lp_build_context *bld, LLVMValueRef v01) { struct gallivm_state *gallivm = bld->gallivm; LLVMValueRef x, mul, delta, res, v0, v1, elems[8]; const struct lp_type type = bld->type; LLVMBuilderRef builder = bld->gallivm->builder; struct lp_type i16_type = lp_wider_type(type); struct lp_type i32_type = lp_wider_type(i16_type); struct lp_build_context bld2; assert(!type.floating && !type.fixed && !type.norm && type.width == 8); lp_build_context_init(&bld2, gallivm, i16_type); bld2.type.sign = TRUE; /* weights 256/3, 256*2/3, with correct rounding */ elems[0] = elems[1] = elems[2] = elems[3] = lp_build_const_elem(gallivm, i16_type, 255*1/3); elems[4] = elems[5] = elems[6] = elems[7] = lp_build_const_elem(gallivm, i16_type, 171); x = LLVMConstVector(elems, 8); /* * v01 has col0 in 32bit elem 0, col1 in elem 1. * Interleave/unpack will give us separate v0/v1 vectors. */ v01 = lp_build_interleave2(gallivm, i32_type, v01, v01, 0); v01 = LLVMBuildBitCast(builder, v01, bld->vec_type, ""); lp_build_unpack2(gallivm, type, i16_type, v01, &v0, &v1); delta = lp_build_sub(&bld2, v1, v0); mul = LLVMBuildMul(builder, x, delta, ""); mul = LLVMBuildLShr(builder, mul, lp_build_const_int_vec(gallivm, i16_type, 8), ""); /* lerp optimization: pack now, do add afterwards */ res = lp_build_pack2(gallivm, i16_type, type, mul, bld2.undef); /* only lower 2 elems are valid - for these v0 is really v0 */ return lp_build_add(bld, res, v01); } /* * decode one dxt1 block. */ static void s3tc_decode_block_dxt1(struct gallivm_state *gallivm, enum pipe_format format, LLVMValueRef dxt_block, LLVMValueRef *col) { LLVMBuilderRef builder = gallivm->builder; LLVMValueRef color01, color23, color01_16, color0123; LLVMValueRef rgba, tmp, a, sel_mask, indices, code, const2; struct lp_type type8, type32, type16, type64; struct lp_build_context bld8, bld32, bld16, bld64; unsigned i; boolean is_dxt1_variant = format_dxt1_variant(format); memset(&type32, 0, sizeof type32); type32.width = 32; type32.length = 4; type32.sign = TRUE; memset(&type8, 0, sizeof type8); type8.width = 8; type8.length = 16; memset(&type16, 0, sizeof type16); type16.width = 16; type16.length = 8; memset(&type64, 0, sizeof type64); type64.width = 64; type64.length = 2; a = lp_build_const_int_vec(gallivm, type32, 0xff000000); const2 = lp_build_const_int_vec(gallivm, type32, 2); lp_build_context_init(&bld32, gallivm, type32); lp_build_context_init(&bld16, gallivm, type16); lp_build_context_init(&bld8, gallivm, type8); lp_build_context_init(&bld64, gallivm, type64); if (is_dxt1_variant) { color01 = lp_build_shuffle1undef(gallivm, dxt_block, 0, 4); code = lp_build_shuffle1undef(gallivm, dxt_block, 1, 4); } else { color01 = lp_build_shuffle1undef(gallivm, dxt_block, 2, 4); code = lp_build_shuffle1undef(gallivm, dxt_block, 3, 4); } code = LLVMBuildBitCast(builder, code, bld8.vec_type, ""); /* expand bytes to dwords */ code = lp_build_interleave2(gallivm, type8, code, code, 0); code = lp_build_interleave2(gallivm, type8, code, code, 0); /* * works as follows: * - expand color0/color1 to rgba8888 * - calculate color2/3 (interpolation) according to color0 < color1 rules * - calculate color2/3 according to color0 >= color1 rules * - do selection of color2/3 according to comparison of color0/1 * - extract indices. * - use compare/select to select the correct color. Since we have 2bit * indices (and 4 colors), needs at least three compare/selects. */ /* * expand the two colors */ color01 = LLVMBuildBitCast(builder, color01, bld16.vec_type, ""); color01 = lp_build_interleave2(gallivm, type16, color01, bld16.zero, 0); color01_16 = LLVMBuildBitCast(builder, color01, bld32.vec_type, ""); color01 = color_expand_565_to_8888(gallivm, 4, color01_16); /* * interpolate colors * color2_1 is 2/3 color0 + 1/3 color1 * color3_1 is 1/3 color0 + 2/3 color1 * color2_2 is 1/2 color0 + 1/2 color1 * color3_2 is 0 */ /* TODO: since this is now always scalar, should * probably just use control flow here instead of calculating * both cases and then selection */ if (format == PIPE_FORMAT_DXT1_RGBA || format == PIPE_FORMAT_DXT1_SRGBA) { color01 = LLVMBuildOr(builder, color01, a, ""); } /* can combine 2 lerps into one mostly */ color23 = lp_build_lerp23_single(&bld8, color01); color23 = LLVMBuildBitCast(builder, color23, bld32.vec_type, ""); /* dxt3/5 always use 4-color encoding */ if (is_dxt1_variant) { LLVMValueRef color23_2, color2_2; if (util_get_cpu_caps()->has_sse2) { LLVMValueRef intrargs[2]; intrargs[0] = LLVMBuildBitCast(builder, color01, bld8.vec_type, ""); /* same interleave as for lerp23 - correct result in 2nd element */ intrargs[1] = lp_build_interleave2(gallivm, type32, color01, color01, 0); intrargs[1] = LLVMBuildBitCast(builder, intrargs[1], bld8.vec_type, ""); color2_2 = lp_build_pavgb(&bld8, intrargs[0], intrargs[1]); } else { LLVMValueRef v01, v0, v1, vhalf; /* * This isn't as expensive as it looks (the unpack is the same as * for lerp23, which is the reason why we do the pointless * interleave2 too), with correct rounding (the two lower elements * will be the same). */ v01 = lp_build_interleave2(gallivm, type32, color01, color01, 0); v01 = LLVMBuildBitCast(builder, v01, bld8.vec_type, ""); lp_build_unpack2(gallivm, type8, type16, v01, &v0, &v1); vhalf = lp_build_add(&bld16, v0, v1); vhalf = LLVMBuildLShr(builder, vhalf, bld16.one, ""); color2_2 = lp_build_pack2(gallivm, type16, type8, vhalf, bld16.undef); } /* shuffle in color 3 as elem 2 zero, color 2 elem 1 */ color23_2 = LLVMBuildBitCast(builder, color2_2, bld64.vec_type, ""); color23_2 = LLVMBuildLShr(builder, color23_2, lp_build_const_int_vec(gallivm, type64, 32), ""); color23_2 = LLVMBuildBitCast(builder, color23_2, bld32.vec_type, ""); tmp = LLVMBuildBitCast(builder, color01_16, bld64.vec_type, ""); tmp = LLVMBuildLShr(builder, tmp, lp_build_const_int_vec(gallivm, type64, 32), ""); tmp = LLVMBuildBitCast(builder, tmp, bld32.vec_type, ""); sel_mask = lp_build_compare(gallivm, type32, PIPE_FUNC_GREATER, color01_16, tmp); sel_mask = lp_build_interleave2(gallivm, type32, sel_mask, sel_mask, 0); color23 = lp_build_select(&bld32, sel_mask, color23, color23_2); } if (util_get_cpu_caps()->has_ssse3) { /* * Use pshufb as mini-lut. (Only doable with intrinsics as the * final shuffles are non-constant. pshufb is awesome!) */ LLVMValueRef shuf[16], low2mask; LLVMValueRef intrargs[2], lut_ind, lut_adj; color01 = LLVMBuildBitCast(builder, color01, bld64.vec_type, ""); color23 = LLVMBuildBitCast(builder, color23, bld64.vec_type, ""); color0123 = lp_build_interleave2(gallivm, type64, color01, color23, 0); color0123 = LLVMBuildBitCast(builder, color0123, bld32.vec_type, ""); if (format == PIPE_FORMAT_DXT1_RGB || format == PIPE_FORMAT_DXT1_SRGB) { color0123 = LLVMBuildOr(builder, color0123, a, ""); } /* shuffle as r0r1r2r3g0g1... */ for (i = 0; i < 4; i++) { shuf[4*i] = lp_build_const_int32(gallivm, 0 + i); shuf[4*i+1] = lp_build_const_int32(gallivm, 4 + i); shuf[4*i+2] = lp_build_const_int32(gallivm, 8 + i); shuf[4*i+3] = lp_build_const_int32(gallivm, 12 + i); } color0123 = LLVMBuildBitCast(builder, color0123, bld8.vec_type, ""); color0123 = LLVMBuildShuffleVector(builder, color0123, bld8.undef, LLVMConstVector(shuf, 16), ""); /* lowest 2 bits of each 8 bit value contain index into "LUT" */ low2mask = lp_build_const_int_vec(gallivm, type8, 3); /* add 0/4/8/12 for r/g/b/a */ lut_adj = lp_build_const_int_vec(gallivm, type32, 0x0c080400); lut_adj = LLVMBuildBitCast(builder, lut_adj, bld8.vec_type, ""); intrargs[0] = color0123; for (i = 0; i < 4; i++) { lut_ind = LLVMBuildAnd(builder, code, low2mask, ""); lut_ind = LLVMBuildOr(builder, lut_ind, lut_adj, ""); intrargs[1] = lut_ind; col[i] = lp_build_intrinsic(builder, "llvm.x86.ssse3.pshuf.b.128", bld8.vec_type, intrargs, 2, 0); col[i] = LLVMBuildBitCast(builder, col[i], bld32.vec_type, ""); code = LLVMBuildBitCast(builder, code, bld32.vec_type, ""); code = LLVMBuildLShr(builder, code, const2, ""); code = LLVMBuildBitCast(builder, code, bld8.vec_type, ""); } } else { /* Thanks to vectorization can do 4 texels in parallel */ LLVMValueRef color0, color1, color2, color3; if (format == PIPE_FORMAT_DXT1_RGB || format == PIPE_FORMAT_DXT1_SRGB) { color01 = LLVMBuildOr(builder, color01, a, ""); color23 = LLVMBuildOr(builder, color23, a, ""); } color0 = LLVMBuildShuffleVector(builder, color01, bld32.undef, lp_build_const_shuffle1(gallivm, 0, 4), ""); color1 = LLVMBuildShuffleVector(builder, color01, bld32.undef, lp_build_const_shuffle1(gallivm, 1, 4), ""); color2 = LLVMBuildShuffleVector(builder, color23, bld32.undef, lp_build_const_shuffle1(gallivm, 0, 4), ""); color3 = LLVMBuildShuffleVector(builder, color23, bld32.undef, lp_build_const_shuffle1(gallivm, 1, 4), ""); code = LLVMBuildBitCast(builder, code, bld32.vec_type, ""); for (i = 0; i < 4; i++) { /* select the colors */ LLVMValueRef selmasklo, rgba01, rgba23, bitlo; bitlo = bld32.one; indices = LLVMBuildAnd(builder, code, bitlo, ""); selmasklo = lp_build_compare(gallivm, type32, PIPE_FUNC_EQUAL, indices, bitlo); rgba01 = lp_build_select(&bld32, selmasklo, color1, color0); LLVMValueRef selmaskhi; indices = LLVMBuildAnd(builder, code, const2, ""); selmaskhi = lp_build_compare(gallivm, type32, PIPE_FUNC_EQUAL, indices, const2); rgba23 = lp_build_select(&bld32, selmasklo, color3, color2); rgba = lp_build_select(&bld32, selmaskhi, rgba23, rgba01); /* * Note that this will give "wrong" order. * col0 will be rgba0, rgba4, rgba8, rgba12, col1 rgba1, rgba5, ... * This would be easily fixable by using different shuffle, bitlo/hi * vectors above (and different shift), but seems slightly easier to * deal with for dxt3/dxt5 alpha too. So instead change lookup. */ col[i] = rgba; code = LLVMBuildLShr(builder, code, const2, ""); } } } /* * decode one dxt3 block. */ static void s3tc_decode_block_dxt3(struct gallivm_state *gallivm, enum pipe_format format, LLVMValueRef dxt_block, LLVMValueRef *col) { LLVMBuilderRef builder = gallivm->builder; LLVMValueRef alpha, alphas0, alphas1, shift4_16, a[4], mask8hi; struct lp_type type32, type8, type16; unsigned i; memset(&type32, 0, sizeof type32); type32.width = 32; type32.length = 4; memset(&type8, 0, sizeof type8); type8.width = 8; type8.length = 16; memset(&type16, 0, sizeof type16); type16.width = 16; type16.length = 8; s3tc_decode_block_dxt1(gallivm, format, dxt_block, col); shift4_16 = lp_build_const_int_vec(gallivm, type16, 4); mask8hi = lp_build_const_int_vec(gallivm, type32, 0xff000000); alpha = LLVMBuildBitCast(builder, dxt_block, lp_build_vec_type(gallivm, type8), ""); alpha = lp_build_interleave2(gallivm, type8, alpha, alpha, 0); alpha = LLVMBuildBitCast(builder, alpha, lp_build_vec_type(gallivm, type16), ""); alpha = LLVMBuildAnd(builder, alpha, lp_build_const_int_vec(gallivm, type16, 0xf00f), ""); alphas0 = LLVMBuildLShr(builder, alpha, shift4_16, ""); alphas1 = LLVMBuildShl(builder, alpha, shift4_16, ""); alpha = LLVMBuildOr(builder, alphas0, alpha, ""); alpha = LLVMBuildOr(builder, alphas1, alpha, ""); alpha = LLVMBuildBitCast(builder, alpha, lp_build_vec_type(gallivm, type32), ""); /* * alpha now contains elems 0,1,2,3,... (ubytes) * we need 0,4,8,12, 1,5,9,13 etc. in dwords to match color (which * is just as easy as "natural" order - 3 shift/and instead of 6 unpack). */ a[0] = LLVMBuildShl(builder, alpha, lp_build_const_int_vec(gallivm, type32, 24), ""); a[1] = LLVMBuildShl(builder, alpha, lp_build_const_int_vec(gallivm, type32, 16), ""); a[1] = LLVMBuildAnd(builder, a[1], mask8hi, ""); a[2] = LLVMBuildShl(builder, alpha, lp_build_const_int_vec(gallivm, type32, 8), ""); a[2] = LLVMBuildAnd(builder, a[2], mask8hi, ""); a[3] = LLVMBuildAnd(builder, alpha, mask8hi, ""); for (i = 0; i < 4; i++) { col[i] = LLVMBuildOr(builder, col[i], a[i], ""); } } static LLVMValueRef lp_build_lerpdxta_block(struct gallivm_state *gallivm, LLVMValueRef alpha0, LLVMValueRef alpha1, LLVMValueRef code, LLVMValueRef sel_mask) { LLVMBuilderRef builder = gallivm->builder; LLVMValueRef delta, ainterp; LLVMValueRef weight5, weight7, weight; struct lp_type type16; struct lp_build_context bld; memset(&type16, 0, sizeof type16); type16.width = 16; type16.length = 8; type16.sign = TRUE; lp_build_context_init(&bld, gallivm, type16); /* * 256/7 is only 36.57 so we'd lose quite some precision. Since it would * actually be desirable to do this here with even higher accuracy than * even 8 bit (more or less required for rgtc, albeit that's not handled * here right now), shift the weights after multiplication by code. */ weight5 = lp_build_const_int_vec(gallivm, type16, 256*64/5); weight7 = lp_build_const_int_vec(gallivm, type16, 256*64/7); weight = lp_build_select(&bld, sel_mask, weight7, weight5); /* * we'll get garbage in the elements which had code 0 (or larger than * 5 or 7) but we don't care (or rather, need to fix up anyway). */ code = LLVMBuildSub(builder, code, bld.one, ""); weight = LLVMBuildMul(builder, weight, code, ""); weight = LLVMBuildLShr(builder, weight, lp_build_const_int_vec(gallivm, type16, 6), ""); delta = LLVMBuildSub(builder, alpha1, alpha0, ""); ainterp = LLVMBuildMul(builder, delta, weight, ""); ainterp = LLVMBuildLShr(builder, ainterp, lp_build_const_int_vec(gallivm, type16, 8), ""); /* lerp is done later (with packed values) */ return ainterp; } /* * decode one dxt5 block. */ static void s3tc_decode_block_dxt5(struct gallivm_state *gallivm, enum pipe_format format, LLVMValueRef dxt_block, LLVMValueRef *col) { LLVMBuilderRef builder = gallivm->builder; LLVMValueRef alpha, alpha0, alpha1, ares; LLVMValueRef ainterp, ainterp0, ainterp1, shuffle1, sel_mask, sel_mask2; LLVMValueRef a[4], acode, tmp0, tmp1; LLVMTypeRef i64t, i32t; struct lp_type type32, type64, type8, type16; struct lp_build_context bld16, bld8; unsigned i; memset(&type32, 0, sizeof type32); type32.width = 32; type32.length = 4; memset(&type64, 0, sizeof type64); type64.width = 64; type64.length = 2; memset(&type8, 0, sizeof type8); type8.width = 8; type8.length = 16; memset(&type16, 0, sizeof type16); type16.width = 16; type16.length = 8; lp_build_context_init(&bld16, gallivm, type16); lp_build_context_init(&bld8, gallivm, type8); i64t = lp_build_vec_type(gallivm, type64); i32t = lp_build_vec_type(gallivm, type32); s3tc_decode_block_dxt1(gallivm, format, dxt_block, col); /* * three possible strategies for vectorizing alpha: * 1) compute all 8 values then use scalar extraction * (i.e. have all 8 alpha values packed in one 64bit scalar * and do something like ax = vals >> (codex * 8) followed * by inserting these values back into color) * 2) same as 8 but just use pshufb as a mini-LUT for selection. * (without pshufb would need boatloads of cmp/selects trying to * keep things vectorized for essentially scalar selection). * 3) do something similar to the uncached case * needs more calculations (need to calc 16 values instead of 8 though * that's only an issue for the lerp which we need to do twice otherwise * everything still fits into 128bit) but keeps things vectorized mostly. * Trying 3) here though not sure it's really faster... * With pshufb, we try 2) (cheaper and more accurate) */ /* * Ideally, we'd use 2 variable 16bit shifts here (byte shifts wouldn't * help since code crosses 8bit boundaries). But variable shifts are * AVX2 only, and even then only dword/quadword (intel _really_ hates * shifts!). Instead, emulate by 16bit muls. * Also, the required byte shuffles are essentially non-emulatable, so * require ssse3 (albeit other archs might do them fine). * This is not directly tied to ssse3 - just need sane byte shuffles. * But ordering is going to be different below so use same condition. */ /* vectorize alpha */ alpha = LLVMBuildBitCast(builder, dxt_block, i64t, ""); alpha0 = LLVMBuildAnd(builder, alpha, lp_build_const_int_vec(gallivm, type64, 0xff), ""); alpha0 = LLVMBuildBitCast(builder, alpha0, bld16.vec_type, ""); alpha = LLVMBuildBitCast(builder, alpha, bld16.vec_type, ""); alpha1 = LLVMBuildLShr(builder, alpha, lp_build_const_int_vec(gallivm, type16, 8), ""); alpha = LLVMBuildBitCast(builder, alpha, i64t, ""); shuffle1 = lp_build_const_shuffle1(gallivm, 0, 8); alpha0 = LLVMBuildShuffleVector(builder, alpha0, alpha0, shuffle1, ""); alpha1 = LLVMBuildShuffleVector(builder, alpha1, alpha1, shuffle1, ""); type16.sign = TRUE; sel_mask = lp_build_compare(gallivm, type16, PIPE_FUNC_GREATER, alpha0, alpha1); type16.sign = FALSE; sel_mask = LLVMBuildBitCast(builder, sel_mask, bld8.vec_type, ""); if (!util_get_cpu_caps()->has_ssse3) { LLVMValueRef acodeg, mask1, acode0, acode1; /* extraction of the 3 bit values into something more useful is HARD */ /* first steps are actually scalar */ acode = LLVMBuildLShr(builder, alpha, lp_build_const_int_vec(gallivm, type64, 16), ""); tmp0 = LLVMBuildAnd(builder, acode, lp_build_const_int_vec(gallivm, type64, 0xffffff), ""); tmp1 = LLVMBuildLShr(builder, acode, lp_build_const_int_vec(gallivm, type64, 24), ""); tmp0 = LLVMBuildBitCast(builder, tmp0, i32t, ""); tmp1 = LLVMBuildBitCast(builder, tmp1, i32t, ""); acode = lp_build_interleave2(gallivm, type32, tmp0, tmp1, 0); /* now have 2x24bit in 4x32bit, order 01234567, 89..., undef, undef */ tmp0 = LLVMBuildAnd(builder, acode, lp_build_const_int_vec(gallivm, type32, 0xfff), ""); tmp1 = LLVMBuildLShr(builder, acode, lp_build_const_int_vec(gallivm, type32, 12), ""); acode = lp_build_interleave2(gallivm, type32, tmp0, tmp1, 0); /* now have 4x12bit in 4x32bit, order 0123, 4567, ,,, */ tmp0 = LLVMBuildAnd(builder, acode, lp_build_const_int_vec(gallivm, type32, 0x3f), ""); tmp1 = LLVMBuildLShr(builder, acode, lp_build_const_int_vec(gallivm, type32, 6), ""); /* use signed pack doesn't matter and otherwise need sse41 */ type32.sign = type16.sign = TRUE; acode = lp_build_pack2(gallivm, type32, type16, tmp0, tmp1); type32.sign = type16.sign = FALSE; /* now have 8x6bit in 8x16bit, 01, 45, 89, ..., 23, 67, ... */ acode0 = LLVMBuildAnd(builder, acode, lp_build_const_int_vec(gallivm, type16, 0x7), ""); acode1 = LLVMBuildLShr(builder, acode, lp_build_const_int_vec(gallivm, type16, 3), ""); acode = lp_build_pack2(gallivm, type16, type8, acode0, acode1); /* acode0 contains elems 0,4,8,12,2,6,10,14, acode1 1,5,9,... */ acodeg = LLVMBuildAnd(builder, acode, LLVMBuildNot(builder, sel_mask, ""), ""); mask1 = lp_build_compare(gallivm, type8, PIPE_FUNC_EQUAL, acode, bld8.one); sel_mask = LLVMBuildBitCast(builder, sel_mask, bld16.vec_type, ""); ainterp0 = lp_build_lerpdxta_block(gallivm, alpha0, alpha1, acode0, sel_mask); ainterp1 = lp_build_lerpdxta_block(gallivm, alpha0, alpha1, acode1, sel_mask); sel_mask = LLVMBuildBitCast(builder, sel_mask, bld8.vec_type, ""); ainterp = lp_build_pack2(gallivm, type16, type8, ainterp0, ainterp1); alpha0 = lp_build_pack2(gallivm, type16, type8, alpha0, alpha0); alpha1 = lp_build_pack2(gallivm, type16, type8, alpha1, alpha1); ainterp = LLVMBuildAdd(builder, ainterp, alpha0, ""); /* Fix up val01 */ sel_mask2 = lp_build_compare(gallivm, type8, PIPE_FUNC_EQUAL, acode, bld8.zero); ainterp = lp_build_select(&bld8, sel_mask2, alpha0, ainterp); ainterp = lp_build_select(&bld8, mask1, alpha1, ainterp); /* fix up val67 if a0 <= a1 */ sel_mask2 = lp_build_compare(gallivm, type8, PIPE_FUNC_EQUAL, acodeg, lp_build_const_int_vec(gallivm, type8, 6)); ares = LLVMBuildAnd(builder, ainterp, LLVMBuildNot(builder, sel_mask2, ""), ""); sel_mask2 = lp_build_compare(gallivm, type8, PIPE_FUNC_EQUAL, acodeg, lp_build_const_int_vec(gallivm, type8, 7)); ares = LLVMBuildOr(builder, ares, sel_mask2, ""); /* unpack in right order (0,4,8,12,1,5,..) */ /* this gives us zero, a0, zero, a4, zero, a8, ... for tmp0 */ tmp0 = lp_build_interleave2(gallivm, type8, bld8.zero, ares, 0); tmp1 = lp_build_interleave2(gallivm, type8, bld8.zero, ares, 1); tmp0 = LLVMBuildBitCast(builder, tmp0, bld16.vec_type, ""); tmp1 = LLVMBuildBitCast(builder, tmp1, bld16.vec_type, ""); a[0] = lp_build_interleave2(gallivm, type16, bld16.zero, tmp0, 0); a[1] = lp_build_interleave2(gallivm, type16, bld16.zero, tmp1, 0); a[2] = lp_build_interleave2(gallivm, type16, bld16.zero, tmp0, 1); a[3] = lp_build_interleave2(gallivm, type16, bld16.zero, tmp1, 1); } else { LLVMValueRef elems[16], intrargs[2], shufa, mulclo, mulchi, mask8hi; LLVMTypeRef type16s = LLVMInt16TypeInContext(gallivm->context); LLVMTypeRef type8s = LLVMInt8TypeInContext(gallivm->context); unsigned i, j; /* * Ideally, we'd use 2 variable 16bit shifts here (byte shifts wouldn't * help since code crosses 8bit boundaries). But variable shifts are * AVX2 only, and even then only dword/quadword (intel _really_ hates * shifts!). Instead, emulate by 16bit muls. * Also, the required byte shuffles are essentially non-emulatable, so * require ssse3 (albeit other archs might do them fine, but the * complete path is ssse3 only for now). */ for (i = 0, j = 0; i < 16; i += 8, j += 3) { elems[i+0] = elems[i+1] = elems[i+2] = lp_build_const_int32(gallivm, j+2); elems[i+3] = elems[i+4] = lp_build_const_int32(gallivm, j+3); elems[i+5] = elems[i+6] = elems[i+7] = lp_build_const_int32(gallivm, j+4); } shufa = LLVMConstVector(elems, 16); alpha = LLVMBuildBitCast(builder, alpha, bld8.vec_type, ""); acode = LLVMBuildShuffleVector(builder, alpha, bld8.undef, shufa, ""); acode = LLVMBuildBitCast(builder, acode, bld16.vec_type, ""); /* * Put 0/2/4/6 into high 3 bits of 16 bits (save AND mask) * Do the same for 1/3/5/7 (albeit still need mask there - ideally * we'd place them into bits 4-7 so could save shift but impossible.) */ for (i = 0; i < 8; i += 4) { elems[i+0] = LLVMConstInt(type16s, 1 << (13-0), 0); elems[i+1] = LLVMConstInt(type16s, 1 << (13-6), 0); elems[i+2] = LLVMConstInt(type16s, 1 << (13-4), 0); elems[i+3] = LLVMConstInt(type16s, 1 << (13-2), 0); } mulclo = LLVMConstVector(elems, 8); for (i = 0; i < 8; i += 4) { elems[i+0] = LLVMConstInt(type16s, 1 << (13-3), 0); elems[i+1] = LLVMConstInt(type16s, 1 << (13-9), 0); elems[i+2] = LLVMConstInt(type16s, 1 << (13-7), 0); elems[i+3] = LLVMConstInt(type16s, 1 << (13-5), 0); } mulchi = LLVMConstVector(elems, 8); tmp0 = LLVMBuildMul(builder, acode, mulclo, ""); tmp1 = LLVMBuildMul(builder, acode, mulchi, ""); tmp0 = LLVMBuildLShr(builder, tmp0, lp_build_const_int_vec(gallivm, type16, 13), ""); tmp1 = LLVMBuildLShr(builder, tmp1, lp_build_const_int_vec(gallivm, type16, 5), ""); tmp1 = LLVMBuildAnd(builder, tmp1, lp_build_const_int_vec(gallivm, type16, 0x700), ""); acode = LLVMBuildOr(builder, tmp0, tmp1, ""); acode = LLVMBuildBitCast(builder, acode, bld8.vec_type, ""); /* * Note that ordering is different here to non-ssse3 path: * 0/1/2/3/4/5... */ LLVMValueRef weight0, weight1, weight, delta; LLVMValueRef constff_elem7, const0_elem6; /* weights, correctly rounded (round(256*x/7)) */ elems[0] = LLVMConstInt(type16s, 256, 0); elems[1] = LLVMConstInt(type16s, 0, 0); elems[2] = LLVMConstInt(type16s, 219, 0); elems[3] = LLVMConstInt(type16s, 183, 0); elems[4] = LLVMConstInt(type16s, 146, 0); elems[5] = LLVMConstInt(type16s, 110, 0); elems[6] = LLVMConstInt(type16s, 73, 0); elems[7] = LLVMConstInt(type16s, 37, 0); weight0 = LLVMConstVector(elems, 8); elems[0] = LLVMConstInt(type16s, 256, 0); elems[1] = LLVMConstInt(type16s, 0, 0); elems[2] = LLVMConstInt(type16s, 205, 0); elems[3] = LLVMConstInt(type16s, 154, 0); elems[4] = LLVMConstInt(type16s, 102, 0); elems[5] = LLVMConstInt(type16s, 51, 0); elems[6] = LLVMConstInt(type16s, 0, 0); elems[7] = LLVMConstInt(type16s, 0, 0); weight1 = LLVMConstVector(elems, 8); weight0 = LLVMBuildBitCast(builder, weight0, bld8.vec_type, ""); weight1 = LLVMBuildBitCast(builder, weight1, bld8.vec_type, ""); weight = lp_build_select(&bld8, sel_mask, weight0, weight1); weight = LLVMBuildBitCast(builder, weight, bld16.vec_type, ""); for (i = 0; i < 16; i++) { elems[i] = LLVMConstNull(type8s); } elems[7] = LLVMConstInt(type8s, 255, 0); constff_elem7 = LLVMConstVector(elems, 16); for (i = 0; i < 16; i++) { elems[i] = LLVMConstInt(type8s, 255, 0); } elems[6] = LLVMConstInt(type8s, 0, 0); const0_elem6 = LLVMConstVector(elems, 16); /* standard simple lerp - but the version we need isn't available */ delta = LLVMBuildSub(builder, alpha0, alpha1, ""); ainterp = LLVMBuildMul(builder, delta, weight, ""); ainterp = LLVMBuildLShr(builder, ainterp, lp_build_const_int_vec(gallivm, type16, 8), ""); ainterp = LLVMBuildBitCast(builder, ainterp, bld8.vec_type, ""); alpha1 = LLVMBuildBitCast(builder, alpha1, bld8.vec_type, ""); ainterp = LLVMBuildAdd(builder, ainterp, alpha1, ""); ainterp = LLVMBuildBitCast(builder, ainterp, bld16.vec_type, ""); ainterp = lp_build_pack2(gallivm, type16, type8, ainterp, bld16.undef); /* fixing 0/0xff case is slightly more complex */ constff_elem7 = LLVMBuildAnd(builder, constff_elem7, LLVMBuildNot(builder, sel_mask, ""), ""); const0_elem6 = LLVMBuildOr(builder, const0_elem6, sel_mask, ""); ainterp = LLVMBuildOr(builder, ainterp, constff_elem7, ""); ainterp = LLVMBuildAnd(builder, ainterp, const0_elem6, ""); /* now pick all 16 elements at once! */ intrargs[0] = ainterp; intrargs[1] = acode; ares = lp_build_intrinsic(builder, "llvm.x86.ssse3.pshuf.b.128", bld8.vec_type, intrargs, 2, 0); ares = LLVMBuildBitCast(builder, ares, i32t, ""); mask8hi = lp_build_const_int_vec(gallivm, type32, 0xff000000); a[0] = LLVMBuildShl(builder, ares, lp_build_const_int_vec(gallivm, type32, 24), ""); a[1] = LLVMBuildShl(builder, ares, lp_build_const_int_vec(gallivm, type32, 16), ""); a[1] = LLVMBuildAnd(builder, a[1], mask8hi, ""); a[2] = LLVMBuildShl(builder, ares, lp_build_const_int_vec(gallivm, type32, 8), ""); a[2] = LLVMBuildAnd(builder, a[2], mask8hi, ""); a[3] = LLVMBuildAnd(builder, ares, mask8hi, ""); } for (i = 0; i < 4; i++) { a[i] = LLVMBuildBitCast(builder, a[i], i32t, ""); col[i] = LLVMBuildOr(builder, col[i], a[i], ""); } } static void generate_update_cache_one_block(struct gallivm_state *gallivm, LLVMValueRef function, const struct util_format_description *format_desc) { LLVMBasicBlockRef block; LLVMBuilderRef old_builder; LLVMValueRef ptr_addr; LLVMValueRef hash_index; LLVMValueRef cache; LLVMValueRef dxt_block, tag_value; LLVMValueRef col[LP_MAX_VECTOR_LENGTH]; ptr_addr = LLVMGetParam(function, 0); hash_index = LLVMGetParam(function, 1); cache = LLVMGetParam(function, 2); lp_build_name(ptr_addr, "ptr_addr" ); lp_build_name(hash_index, "hash_index"); lp_build_name(cache, "cache_addr"); /* * Function body */ old_builder = gallivm->builder; block = LLVMAppendBasicBlockInContext(gallivm->context, function, "entry"); gallivm->builder = LLVMCreateBuilderInContext(gallivm->context); LLVMPositionBuilderAtEnd(gallivm->builder, block); lp_build_gather_s3tc_simple_scalar(gallivm, format_desc, &dxt_block, ptr_addr); switch (format_desc->format) { case PIPE_FORMAT_DXT1_RGB: case PIPE_FORMAT_DXT1_RGBA: case PIPE_FORMAT_DXT1_SRGB: case PIPE_FORMAT_DXT1_SRGBA: s3tc_decode_block_dxt1(gallivm, format_desc->format, dxt_block, col); break; case PIPE_FORMAT_DXT3_RGBA: case PIPE_FORMAT_DXT3_SRGBA: s3tc_decode_block_dxt3(gallivm, format_desc->format, dxt_block, col); break; case PIPE_FORMAT_DXT5_RGBA: case PIPE_FORMAT_DXT5_SRGBA: s3tc_decode_block_dxt5(gallivm, format_desc->format, dxt_block, col); break; default: assert(0); s3tc_decode_block_dxt1(gallivm, format_desc->format, dxt_block, col); break; } tag_value = LLVMBuildPtrToInt(gallivm->builder, ptr_addr, LLVMInt64TypeInContext(gallivm->context), ""); s3tc_store_cached_block(gallivm, col, tag_value, hash_index, cache); LLVMBuildRetVoid(gallivm->builder); LLVMDisposeBuilder(gallivm->builder); gallivm->builder = old_builder; gallivm_verify_function(gallivm, function); } static void update_cached_block(struct gallivm_state *gallivm, const struct util_format_description *format_desc, LLVMValueRef ptr_addr, LLVMValueRef hash_index, LLVMValueRef cache) { LLVMBuilderRef builder = gallivm->builder; LLVMModuleRef module = gallivm->module; char name[256]; LLVMTypeRef i8t = LLVMInt8TypeInContext(gallivm->context); LLVMTypeRef pi8t = LLVMPointerType(i8t, 0); LLVMValueRef function, inst; LLVMBasicBlockRef bb; LLVMValueRef args[3]; snprintf(name, sizeof name, "%s_update_cache_one_block", format_desc->short_name); function = LLVMGetNamedFunction(module, name); if (!function) { LLVMTypeRef ret_type; LLVMTypeRef arg_types[3]; LLVMTypeRef function_type; unsigned arg; /* * Generate the function prototype. */ ret_type = LLVMVoidTypeInContext(gallivm->context); arg_types[0] = pi8t; arg_types[1] = LLVMInt32TypeInContext(gallivm->context); arg_types[2] = LLVMTypeOf(cache); // XXX: put right type here function_type = LLVMFunctionType(ret_type, arg_types, ARRAY_SIZE(arg_types), 0); function = LLVMAddFunction(module, name, function_type); for (arg = 0; arg < ARRAY_SIZE(arg_types); ++arg) if (LLVMGetTypeKind(arg_types[arg]) == LLVMPointerTypeKind) lp_add_function_attr(function, arg + 1, LP_FUNC_ATTR_NOALIAS); LLVMSetFunctionCallConv(function, LLVMFastCallConv); LLVMSetVisibility(function, LLVMHiddenVisibility); generate_update_cache_one_block(gallivm, function, format_desc); } args[0] = ptr_addr; args[1] = hash_index; args[2] = cache; LLVMBuildCall(builder, function, args, ARRAY_SIZE(args), ""); bb = LLVMGetInsertBlock(builder); inst = LLVMGetLastInstruction(bb); LLVMSetInstructionCallConv(inst, LLVMFastCallConv); } /* * cached lookup */ static LLVMValueRef compressed_fetch_cached(struct gallivm_state *gallivm, const struct util_format_description *format_desc, unsigned n, LLVMValueRef base_ptr, LLVMValueRef offset, LLVMValueRef i, LLVMValueRef j, LLVMValueRef cache) { LLVMBuilderRef builder = gallivm->builder; unsigned count, low_bit, log2size; LLVMValueRef color, offset_stored, addr, ptr_addrtrunc, tmp; LLVMValueRef ij_index, hash_index, hash_mask, block_index; LLVMTypeRef i8t = LLVMInt8TypeInContext(gallivm->context); LLVMTypeRef i32t = LLVMInt32TypeInContext(gallivm->context); LLVMTypeRef i64t = LLVMInt64TypeInContext(gallivm->context); struct lp_type type; struct lp_build_context bld32; memset(&type, 0, sizeof type); type.width = 32; type.length = n; lp_build_context_init(&bld32, gallivm, type); /* * compute hash - we use direct mapped cache, the hash function could * be better but it needs to be simple * per-element: * compare offset with offset stored at tag (hash) * if not equal extract block, store block, update tag * extract color from cache * assemble colors */ low_bit = util_logbase2(format_desc->block.bits / 8); log2size = util_logbase2(LP_BUILD_FORMAT_CACHE_SIZE); addr = LLVMBuildPtrToInt(builder, base_ptr, i64t, ""); ptr_addrtrunc = LLVMBuildPtrToInt(builder, base_ptr, i32t, ""); ptr_addrtrunc = lp_build_broadcast_scalar(&bld32, ptr_addrtrunc); /* For the hash function, first mask off the unused lowest bits. Then just do some xor with address bits - only use lower 32bits */ ptr_addrtrunc = LLVMBuildAdd(builder, offset, ptr_addrtrunc, ""); ptr_addrtrunc = LLVMBuildLShr(builder, ptr_addrtrunc, lp_build_const_int_vec(gallivm, type, low_bit), ""); /* This only really makes sense for size 64,128,256 */ hash_index = ptr_addrtrunc; ptr_addrtrunc = LLVMBuildLShr(builder, ptr_addrtrunc, lp_build_const_int_vec(gallivm, type, 2*log2size), ""); hash_index = LLVMBuildXor(builder, ptr_addrtrunc, hash_index, ""); tmp = LLVMBuildLShr(builder, hash_index, lp_build_const_int_vec(gallivm, type, log2size), ""); hash_index = LLVMBuildXor(builder, hash_index, tmp, ""); hash_mask = lp_build_const_int_vec(gallivm, type, LP_BUILD_FORMAT_CACHE_SIZE - 1); hash_index = LLVMBuildAnd(builder, hash_index, hash_mask, ""); ij_index = LLVMBuildShl(builder, i, lp_build_const_int_vec(gallivm, type, 2), ""); ij_index = LLVMBuildAdd(builder, ij_index, j, ""); block_index = LLVMBuildShl(builder, hash_index, lp_build_const_int_vec(gallivm, type, 4), ""); block_index = LLVMBuildAdd(builder, ij_index, block_index, ""); if (n > 1) { color = bld32.undef; for (count = 0; count < n; count++) { LLVMValueRef index, cond, colorx; LLVMValueRef block_indexx, hash_indexx, addrx, offsetx, ptr_addrx; struct lp_build_if_state if_ctx; index = lp_build_const_int32(gallivm, count); offsetx = LLVMBuildExtractElement(builder, offset, index, ""); addrx = LLVMBuildZExt(builder, offsetx, i64t, ""); addrx = LLVMBuildAdd(builder, addrx, addr, ""); block_indexx = LLVMBuildExtractElement(builder, block_index, index, ""); hash_indexx = LLVMBuildLShr(builder, block_indexx, lp_build_const_int32(gallivm, 4), ""); offset_stored = s3tc_lookup_tag_data(gallivm, cache, hash_indexx); cond = LLVMBuildICmp(builder, LLVMIntNE, offset_stored, addrx, ""); lp_build_if(&if_ctx, gallivm, cond); { ptr_addrx = LLVMBuildIntToPtr(builder, addrx, LLVMPointerType(i8t, 0), ""); update_cached_block(gallivm, format_desc, ptr_addrx, hash_indexx, cache); #if LP_BUILD_FORMAT_CACHE_DEBUG s3tc_update_cache_access(gallivm, cache, 1, LP_BUILD_FORMAT_CACHE_MEMBER_ACCESS_MISS); #endif } lp_build_endif(&if_ctx); colorx = s3tc_lookup_cached_pixel(gallivm, cache, block_indexx); color = LLVMBuildInsertElement(builder, color, colorx, lp_build_const_int32(gallivm, count), ""); } } else { LLVMValueRef cond; struct lp_build_if_state if_ctx; tmp = LLVMBuildZExt(builder, offset, i64t, ""); addr = LLVMBuildAdd(builder, tmp, addr, ""); offset_stored = s3tc_lookup_tag_data(gallivm, cache, hash_index); cond = LLVMBuildICmp(builder, LLVMIntNE, offset_stored, addr, ""); lp_build_if(&if_ctx, gallivm, cond); { tmp = LLVMBuildIntToPtr(builder, addr, LLVMPointerType(i8t, 0), ""); update_cached_block(gallivm, format_desc, tmp, hash_index, cache); #if LP_BUILD_FORMAT_CACHE_DEBUG s3tc_update_cache_access(gallivm, cache, 1, LP_BUILD_FORMAT_CACHE_MEMBER_ACCESS_MISS); #endif } lp_build_endif(&if_ctx); color = s3tc_lookup_cached_pixel(gallivm, cache, block_index); } #if LP_BUILD_FORMAT_CACHE_DEBUG s3tc_update_cache_access(gallivm, cache, n, LP_BUILD_FORMAT_CACHE_MEMBER_ACCESS_TOTAL); #endif return LLVMBuildBitCast(builder, color, LLVMVectorType(i8t, n * 4), ""); } static LLVMValueRef s3tc_dxt5_to_rgba_aos(struct gallivm_state *gallivm, unsigned n, enum pipe_format format, LLVMValueRef colors, LLVMValueRef codewords, LLVMValueRef alpha_lo, LLVMValueRef alpha_hi, LLVMValueRef i, LLVMValueRef j) { return s3tc_dxt5_full_to_rgba_aos(gallivm, n, format, colors, codewords, alpha_lo, alpha_hi, i, j); } /** * @param n number of pixels processed (usually n=4, but it should also work with n=1 * and multiples of 4) * @param base_ptr base pointer (32bit or 64bit pointer depending on the architecture) * @param offset <n x i32> vector with the relative offsets of the S3TC blocks * @param i is a <n x i32> vector with the x subpixel coordinate (0..3) * @param j is a <n x i32> vector with the y subpixel coordinate (0..3) * @return a <4*n x i8> vector with the pixel RGBA values in AoS */ LLVMValueRef lp_build_fetch_s3tc_rgba_aos(struct gallivm_state *gallivm, const struct util_format_description *format_desc, unsigned n, LLVMValueRef base_ptr, LLVMValueRef offset, LLVMValueRef i, LLVMValueRef j, LLVMValueRef cache) { LLVMValueRef rgba; LLVMTypeRef i8t = LLVMInt8TypeInContext(gallivm->context); LLVMBuilderRef builder = gallivm->builder; assert(format_desc->layout == UTIL_FORMAT_LAYOUT_S3TC); assert(format_desc->block.width == 4); assert(format_desc->block.height == 4); assert((n == 1) || (n % 4 == 0)); /* debug_printf("format = %d\n", format_desc->format);*/ if (cache) { rgba = compressed_fetch_cached(gallivm, format_desc, n, base_ptr, offset, i, j, cache); return rgba; } /* * Could use n > 8 here with avx2, but doesn't seem faster. */ if (n > 4) { unsigned count; LLVMTypeRef i8_vectype = LLVMVectorType(i8t, 4 * n); LLVMTypeRef i128_type = LLVMIntTypeInContext(gallivm->context, 128); LLVMTypeRef i128_vectype = LLVMVectorType(i128_type, n / 4); LLVMTypeRef i324_vectype = LLVMVectorType(LLVMInt32TypeInContext( gallivm->context), 4); LLVMValueRef offset4, i4, j4, rgba4[LP_MAX_VECTOR_LENGTH/16]; struct lp_type lp_324_vectype = lp_type_uint_vec(32, 128); assert(n / 4 <= ARRAY_SIZE(rgba4)); rgba = LLVMGetUndef(i128_vectype); for (count = 0; count < n / 4; count++) { LLVMValueRef colors, codewords, alpha_lo = NULL, alpha_hi = NULL; i4 = lp_build_extract_range(gallivm, i, count * 4, 4); j4 = lp_build_extract_range(gallivm, j, count * 4, 4); offset4 = lp_build_extract_range(gallivm, offset, count * 4, 4); lp_build_gather_s3tc(gallivm, 4, format_desc, &colors, &codewords, &alpha_lo, &alpha_hi, base_ptr, offset4); switch (format_desc->format) { case PIPE_FORMAT_DXT1_RGB: case PIPE_FORMAT_DXT1_RGBA: case PIPE_FORMAT_DXT1_SRGB: case PIPE_FORMAT_DXT1_SRGBA: rgba4[count] = s3tc_dxt1_to_rgba_aos(gallivm, 4, format_desc->format, colors, codewords, i4, j4); break; case PIPE_FORMAT_DXT3_RGBA: case PIPE_FORMAT_DXT3_SRGBA: rgba4[count] = s3tc_dxt3_to_rgba_aos(gallivm, 4, format_desc->format, colors, codewords, alpha_lo, alpha_hi, i4, j4); break; case PIPE_FORMAT_DXT5_RGBA: case PIPE_FORMAT_DXT5_SRGBA: rgba4[count] = s3tc_dxt5_to_rgba_aos(gallivm, 4, format_desc->format, colors, codewords, alpha_lo, alpha_hi, i4, j4); break; default: assert(0); rgba4[count] = LLVMGetUndef(LLVMVectorType(i8t, 4)); break; } /* shuffles typically give best results with dword elements...*/ rgba4[count] = LLVMBuildBitCast(builder, rgba4[count], i324_vectype, ""); } rgba = lp_build_concat(gallivm, rgba4, lp_324_vectype, n / 4); rgba = LLVMBuildBitCast(builder, rgba, i8_vectype, ""); } else { LLVMValueRef colors, codewords, alpha_lo = NULL, alpha_hi = NULL; lp_build_gather_s3tc(gallivm, n, format_desc, &colors, &codewords, &alpha_lo, &alpha_hi, base_ptr, offset); switch (format_desc->format) { case PIPE_FORMAT_DXT1_RGB: case PIPE_FORMAT_DXT1_RGBA: case PIPE_FORMAT_DXT1_SRGB: case PIPE_FORMAT_DXT1_SRGBA: rgba = s3tc_dxt1_to_rgba_aos(gallivm, n, format_desc->format, colors, codewords, i, j); break; case PIPE_FORMAT_DXT3_RGBA: case PIPE_FORMAT_DXT3_SRGBA: rgba = s3tc_dxt3_to_rgba_aos(gallivm, n, format_desc->format, colors, codewords, alpha_lo, alpha_hi, i, j); break; case PIPE_FORMAT_DXT5_RGBA: case PIPE_FORMAT_DXT5_SRGBA: rgba = s3tc_dxt5_to_rgba_aos(gallivm, n, format_desc->format, colors, codewords, alpha_lo, alpha_hi, i, j); break; default: assert(0); rgba = LLVMGetUndef(LLVMVectorType(i8t, 4*n)); break; } } /* always return just decompressed values - srgb conversion is done later */ return rgba; } /** * Gather elements from scatter positions in memory into vectors. * This is customised for fetching texels from s3tc textures. * For SSE, typical value is length=4. * * @param length length of the offsets * @param colors the stored colors of the blocks will be extracted into this. * @param codewords the codewords of the blocks will be extracted into this. * @param alpha_lo used for storing lower 32bit of alpha components for dxt3/5 * @param alpha_hi used for storing higher 32bit of alpha components for dxt3/5 * @param base_ptr base pointer, should be a i8 pointer type. * @param offsets vector with offsets */ static void lp_build_gather_rgtc(struct gallivm_state *gallivm, unsigned length, const struct util_format_description *format_desc, LLVMValueRef *red_lo, LLVMValueRef *red_hi, LLVMValueRef *green_lo, LLVMValueRef *green_hi, LLVMValueRef base_ptr, LLVMValueRef offsets) { LLVMBuilderRef builder = gallivm->builder; unsigned block_bits = format_desc->block.bits; unsigned i; LLVMValueRef elems[8]; LLVMTypeRef type32 = LLVMInt32TypeInContext(gallivm->context); LLVMTypeRef type64 = LLVMInt64TypeInContext(gallivm->context); LLVMTypeRef type32dxt; struct lp_type lp_type32dxt; memset(&lp_type32dxt, 0, sizeof lp_type32dxt); lp_type32dxt.width = 32; lp_type32dxt.length = block_bits / 32; type32dxt = lp_build_vec_type(gallivm, lp_type32dxt); assert(block_bits == 64 || block_bits == 128); assert(length == 1 || length == 4 || length == 8); for (i = 0; i < length; ++i) { elems[i] = lp_build_gather_elem(gallivm, length, block_bits, block_bits, TRUE, base_ptr, offsets, i, FALSE); elems[i] = LLVMBuildBitCast(builder, elems[i], type32dxt, ""); } if (length == 1) { LLVMValueRef elem = elems[0]; *red_lo = LLVMBuildExtractElement(builder, elem, lp_build_const_int32(gallivm, 0), ""); *red_hi = LLVMBuildExtractElement(builder, elem, lp_build_const_int32(gallivm, 1), ""); if (block_bits == 128) { *green_lo = LLVMBuildExtractElement(builder, elem, lp_build_const_int32(gallivm, 2), ""); *green_hi = LLVMBuildExtractElement(builder, elem, lp_build_const_int32(gallivm, 3), ""); } else { *green_lo = NULL; *green_hi = NULL; } } else { LLVMValueRef tmp[4]; struct lp_type lp_type32, lp_type64; memset(&lp_type32, 0, sizeof lp_type32); lp_type32.width = 32; lp_type32.length = length; lp_type32.sign = lp_type32dxt.sign; memset(&lp_type64, 0, sizeof lp_type64); lp_type64.width = 64; lp_type64.length = length/2; if (block_bits == 128) { if (length == 8) { for (i = 0; i < 4; ++i) { tmp[0] = elems[i]; tmp[1] = elems[i+4]; elems[i] = lp_build_concat(gallivm, tmp, lp_type32dxt, 2); } } lp_build_transpose_aos(gallivm, lp_type32, elems, tmp); *green_lo = tmp[2]; *green_hi = tmp[3]; *red_lo = tmp[0]; *red_hi = tmp[1]; } else { LLVMValueRef red01, red23; LLVMTypeRef type64_vec = LLVMVectorType(type64, length/2); LLVMTypeRef type32_vec = LLVMVectorType(type32, length); for (i = 0; i < length; ++i) { /* no-op shuffle */ elems[i] = LLVMBuildShuffleVector(builder, elems[i], LLVMGetUndef(type32dxt), lp_build_const_extend_shuffle(gallivm, 2, 4), ""); } if (length == 8) { struct lp_type lp_type32_4 = {0}; lp_type32_4.width = 32; lp_type32_4.length = 4; for (i = 0; i < 4; ++i) { tmp[0] = elems[i]; tmp[1] = elems[i+4]; elems[i] = lp_build_concat(gallivm, tmp, lp_type32_4, 2); } } red01 = lp_build_interleave2_half(gallivm, lp_type32, elems[0], elems[1], 0); red23 = lp_build_interleave2_half(gallivm, lp_type32, elems[2], elems[3], 0); red01 = LLVMBuildBitCast(builder, red01, type64_vec, ""); red23 = LLVMBuildBitCast(builder, red23, type64_vec, ""); *red_lo = lp_build_interleave2_half(gallivm, lp_type64, red01, red23, 0); *red_hi = lp_build_interleave2_half(gallivm, lp_type64, red01, red23, 1); *red_lo = LLVMBuildBitCast(builder, *red_lo, type32_vec, ""); *red_hi = LLVMBuildBitCast(builder, *red_hi, type32_vec, ""); *green_lo = NULL; *green_hi = NULL; } } } static LLVMValueRef rgtc1_to_rgba_aos(struct gallivm_state *gallivm, unsigned n, enum pipe_format format, LLVMValueRef red_lo, LLVMValueRef red_hi, LLVMValueRef i, LLVMValueRef j) { LLVMBuilderRef builder = gallivm->builder; bool is_signed = (format == PIPE_FORMAT_RGTC1_SNORM); LLVMValueRef red = s3tc_dxt5_alpha_channel(gallivm, is_signed, n, red_hi, red_lo, i, j); LLVMValueRef rgba; struct lp_type type, type8; memset(&type, 0, sizeof type); type.width = 32; type.length = n; memset(&type8, 0, sizeof type8); type8.width = 8; type8.length = n*4; rgba = lp_build_const_int_vec(gallivm, type, is_signed ? (0x7f << 24) : (0xff << 24)); rgba = LLVMBuildOr(builder, rgba, red, ""); return LLVMBuildBitCast(builder, rgba, lp_build_vec_type(gallivm, type8), ""); } static LLVMValueRef rgtc2_to_rgba_aos(struct gallivm_state *gallivm, unsigned n, enum pipe_format format, LLVMValueRef red_lo, LLVMValueRef red_hi, LLVMValueRef green_lo, LLVMValueRef green_hi, LLVMValueRef i, LLVMValueRef j) { LLVMBuilderRef builder = gallivm->builder; bool is_signed = (format == PIPE_FORMAT_RGTC2_SNORM); LLVMValueRef red = s3tc_dxt5_alpha_channel(gallivm, is_signed, n, red_hi, red_lo, i, j); LLVMValueRef green = s3tc_dxt5_alpha_channel(gallivm, is_signed, n, green_hi, green_lo, i, j); LLVMValueRef rgba; struct lp_type type, type8; memset(&type, 0, sizeof type); type.width = 32; type.length = n; memset(&type8, 0, sizeof type8); type8.width = 8; type8.length = n*4; rgba = lp_build_const_int_vec(gallivm, type, is_signed ? (0x7f << 24) : (0xff << 24)); rgba = LLVMBuildOr(builder, rgba, red, ""); green = LLVMBuildShl(builder, green, lp_build_const_int_vec(gallivm, type, 8), ""); rgba = LLVMBuildOr(builder, rgba, green, ""); return LLVMBuildBitCast(builder, rgba, lp_build_vec_type(gallivm, type8), ""); } static LLVMValueRef latc1_to_rgba_aos(struct gallivm_state *gallivm, unsigned n, enum pipe_format format, LLVMValueRef red_lo, LLVMValueRef red_hi, LLVMValueRef i, LLVMValueRef j) { LLVMBuilderRef builder = gallivm->builder; bool is_signed = (format == PIPE_FORMAT_LATC1_SNORM); LLVMValueRef red = s3tc_dxt5_alpha_channel(gallivm, is_signed, n, red_hi, red_lo, i, j); LLVMValueRef rgba, temp; struct lp_type type, type8; memset(&type, 0, sizeof type); type.width = 32; type.length = n; memset(&type8, 0, sizeof type8); type8.width = 8; type8.length = n*4; rgba = lp_build_const_int_vec(gallivm, type, is_signed ? (0x7f << 24) : (0xff << 24)); rgba = LLVMBuildOr(builder, rgba, red, ""); temp = LLVMBuildShl(builder, red, lp_build_const_int_vec(gallivm, type, 8), ""); rgba = LLVMBuildOr(builder, rgba, temp, ""); temp = LLVMBuildShl(builder, red, lp_build_const_int_vec(gallivm, type, 16), ""); rgba = LLVMBuildOr(builder, rgba, temp, ""); return LLVMBuildBitCast(builder, rgba, lp_build_vec_type(gallivm, type8), ""); } static LLVMValueRef latc2_to_rgba_aos(struct gallivm_state *gallivm, unsigned n, enum pipe_format format, LLVMValueRef red_lo, LLVMValueRef red_hi, LLVMValueRef green_lo, LLVMValueRef green_hi, LLVMValueRef i, LLVMValueRef j) { LLVMBuilderRef builder = gallivm->builder; bool is_signed = (format == PIPE_FORMAT_LATC2_SNORM); LLVMValueRef red = s3tc_dxt5_alpha_channel(gallivm, is_signed, n, red_hi, red_lo, i, j); LLVMValueRef green = s3tc_dxt5_alpha_channel(gallivm, is_signed, n, green_hi, green_lo, i, j); LLVMValueRef rgba, temp; struct lp_type type, type8; memset(&type, 0, sizeof type); type.width = 32; type.length = n; memset(&type8, 0, sizeof type8); type8.width = 8; type8.length = n*4; temp = LLVMBuildShl(builder, red, lp_build_const_int_vec(gallivm, type, 8), ""); rgba = LLVMBuildOr(builder, red, temp, ""); temp = LLVMBuildShl(builder, red, lp_build_const_int_vec(gallivm, type, 16), ""); rgba = LLVMBuildOr(builder, rgba, temp, ""); temp = LLVMBuildShl(builder, green, lp_build_const_int_vec(gallivm, type, 24), ""); rgba = LLVMBuildOr(builder, rgba, temp, ""); return LLVMBuildBitCast(builder, rgba, lp_build_vec_type(gallivm, type8), ""); } /** * @param n number of pixels processed (usually n=4, but it should also work with n=1 * and multiples of 4) * @param base_ptr base pointer (32bit or 64bit pointer depending on the architecture) * @param offset <n x i32> vector with the relative offsets of the S3TC blocks * @param i is a <n x i32> vector with the x subpixel coordinate (0..3) * @param j is a <n x i32> vector with the y subpixel coordinate (0..3) * @return a <4*n x i8> vector with the pixel RGBA values in AoS */ LLVMValueRef lp_build_fetch_rgtc_rgba_aos(struct gallivm_state *gallivm, const struct util_format_description *format_desc, unsigned n, LLVMValueRef base_ptr, LLVMValueRef offset, LLVMValueRef i, LLVMValueRef j, LLVMValueRef cache) { LLVMValueRef rgba; LLVMTypeRef i8t = LLVMInt8TypeInContext(gallivm->context); LLVMBuilderRef builder = gallivm->builder; LLVMValueRef red_lo, red_hi, green_lo, green_hi; assert(format_desc->layout == UTIL_FORMAT_LAYOUT_RGTC); assert(format_desc->block.width == 4); assert(format_desc->block.height == 4); assert((n == 1) || (n % 4 == 0)); if (n > 4) { unsigned count; LLVMTypeRef i128_type = LLVMIntTypeInContext(gallivm->context, 128); LLVMTypeRef i128_vectype = LLVMVectorType(i128_type, n / 4); LLVMTypeRef i8_vectype = LLVMVectorType(i8t, 4 * n); LLVMTypeRef i324_vectype = LLVMVectorType(LLVMInt32TypeInContext( gallivm->context), 4); LLVMValueRef offset4, i4, j4, rgba4[LP_MAX_VECTOR_LENGTH/16]; struct lp_type lp_324_vectype = lp_type_uint_vec(32, 128); rgba = LLVMGetUndef(i128_vectype); for (count = 0; count < n / 4; count++) { i4 = lp_build_extract_range(gallivm, i, count * 4, 4); j4 = lp_build_extract_range(gallivm, j, count * 4, 4); offset4 = lp_build_extract_range(gallivm, offset, count * 4, 4); lp_build_gather_rgtc(gallivm, 4, format_desc, &red_lo, &red_hi, &green_lo, &green_hi, base_ptr, offset4); switch (format_desc->format) { case PIPE_FORMAT_RGTC1_UNORM: case PIPE_FORMAT_RGTC1_SNORM: rgba4[count] = rgtc1_to_rgba_aos(gallivm, 4, format_desc->format, red_lo, red_hi, i4, j4); break; case PIPE_FORMAT_RGTC2_UNORM: case PIPE_FORMAT_RGTC2_SNORM: rgba4[count] = rgtc2_to_rgba_aos(gallivm, 4, format_desc->format, red_lo, red_hi, green_lo, green_hi, i4, j4); break; case PIPE_FORMAT_LATC1_UNORM: case PIPE_FORMAT_LATC1_SNORM: rgba4[count] = latc1_to_rgba_aos(gallivm, 4, format_desc->format, red_lo, red_hi, i4, j4); break; case PIPE_FORMAT_LATC2_UNORM: case PIPE_FORMAT_LATC2_SNORM: rgba4[count] = latc2_to_rgba_aos(gallivm, 4, format_desc->format, red_lo, red_hi, green_lo, green_hi, i4, j4); break; default: assert(0); rgba4[count] = LLVMGetUndef(LLVMVectorType(i8t, 4)); break; } /* shuffles typically give best results with dword elements...*/ rgba4[count] = LLVMBuildBitCast(builder, rgba4[count], i324_vectype, ""); } rgba = lp_build_concat(gallivm, rgba4, lp_324_vectype, n / 4); rgba = LLVMBuildBitCast(builder, rgba, i8_vectype, ""); } else { LLVMValueRef red_lo, red_hi, green_lo, green_hi; lp_build_gather_rgtc(gallivm, n, format_desc, &red_lo, &red_hi, &green_lo, &green_hi, base_ptr, offset); switch (format_desc->format) { case PIPE_FORMAT_RGTC1_UNORM: case PIPE_FORMAT_RGTC1_SNORM: rgba = rgtc1_to_rgba_aos(gallivm, n, format_desc->format, red_lo, red_hi, i, j); break; case PIPE_FORMAT_RGTC2_UNORM: case PIPE_FORMAT_RGTC2_SNORM: rgba = rgtc2_to_rgba_aos(gallivm, n, format_desc->format, red_lo, red_hi, green_lo, green_hi, i, j); break; case PIPE_FORMAT_LATC1_UNORM: case PIPE_FORMAT_LATC1_SNORM: rgba = latc1_to_rgba_aos(gallivm, n, format_desc->format, red_lo, red_hi, i, j); break; case PIPE_FORMAT_LATC2_UNORM: case PIPE_FORMAT_LATC2_SNORM: rgba = latc2_to_rgba_aos(gallivm, n, format_desc->format, red_lo, red_hi, green_lo, green_hi, i, j); break; default: assert(0); rgba = LLVMGetUndef(LLVMVectorType(i8t, 4*n)); break; } } return rgba; }
#ifndef TALLYOUTACCOUNT_H #define TALLYOUTACCOUNT_H #include <QWidget> #include <QMessageBox> #include "walletmodel.h" class WalletModel; namespace Ui { class TallyOutAccount; } class TallyOutAccount : public QWidget { Q_OBJECT public: explicit TallyOutAccount(QWidget *parent = 0); ~TallyOutAccount(); void setModel(WalletModel *_model); void processSendCoinsReturn(const WalletModel::SendCoinsReturn &sendCoinsReturn, const QString &msgArg = QString()); void setinfo(WalletModel::keepupaccountInfo info); WalletModel::keepupaccountInfo getinfo(); void clearinfo(); std::string m_error; private Q_SLOTS: void on_pushButton_Cancle_pressed(); void on_pushButton_OK_pressed(); private: Ui::TallyOutAccount *ui; WalletModel *walletmodel; bool fNewRecipientAllowed; bool m_isLocked; int eTag; WalletModel::keepupaccountInfo info_; bool setlabel_errmsg(); Q_SIGNALS: void next(bool); }; #endif // TALLYOUTACCOUNT_H
/***************************************************************************** SvfCore4Simd.h Author: <NAME>, 2016 Objects of this class should be aligned on 16-bytes boudaries if VP requires alignment. This class can be inherited but is not polymorph. Template parameters: - VD: class writing and reading memory with SIMD vectors (destination access). Typically, the fstb::DataAlign classes for aligned and unaligned data. Requires: static bool VD::check_ptr (const void *ptr) noexcept; static fstb::Vf32 VD::load_f32 (const void *ptr) noexcept; static void VD::store_f32 (void *ptr, const fstb::Vf32 val) noexcept; - VS: same as VD, but for reading only (source access) Requires: static bool VS::check_ptr (const void *ptr) noexcept; static fstb::Vf32 VS::load_f32 (const void *ptr) noexcept; - VP: same as VD, but for parametering and internal data. Requires: same as VD. - MX: output mixer, creating the final output from the input (v0) and the raw outputs (v1 and v2). Requires: static fstb::Vf32 MX::mix (const fstb::Vf32 &v0, const fstb::Vf32 &v1, const fstb::Vf32 &v2, const fstb::Vf32 &v0m, const fstb::Vf32 &v1m, const fstb::Vf32 &v2m) noexcept; static float MX::mix (float v0, float v1, float v2, float v0m, float v1m, float v2m) noexcept; static void MX::inc (fstb::Vf32 &v0m, fstb::Vf32 &v1m, fstb::Vf32 &v2m, const fstb::Vf32 &v0mi, const fstb::Vf32 &v1mi, const fstb::Vf32 &v2mi) noexcept; Implements: v0 = input t0 = v0 - ic2eq t1 = g0 * t0 + g1 * ic1eq t2 = g2 * t0 + g0 * ic1eq v1 = t1 + ic1eq v2 = t2 + ic2eq ic1eq = 2 * t1 + ic1eq ic2eq = 2 * t2 + ic2eq output = v0 * v0m + v1 * v1m + v2 * v2m Specifically, for the output: low = v2 band = v1 high = v0 - k * v1 - v2 notch = v0 - k * v1 = low + high bell = v0 + gi * v1 = input + gi * band allp = v0 - 2 * k * v1 = 2 * notch - input Coefficients are not calculated in this class and should follow: k = 1 / Q w = PI * f0 / fs s1 = sin ( w) s2 = sin (2 * w) nrm = 1 / (2 + k * s2) g0 = s2 * nrm g1 = (-2 * s1 * s1 - k * s2) * nrm g2 = 2 * s1 * s1 * nrm Reference: <NAME>, Linear Trapezoidal State Variable Filter (SVF) in state increment form: state += val, 2014-06-07, updated 2014-07-03, http://www.cytomic.com/technical-papers --- Legal stuff --- This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://sam.zoy.org/wtfpl/COPYING for more details. *Tab=3***********************************************************************/ #pragma once #if ! defined (mfx_dsp_iir_SvfCore4Simd_HEADER_INCLUDED) #define mfx_dsp_iir_SvfCore4Simd_HEADER_INCLUDED #if defined (_MSC_VER) #pragma warning (4 : 4250) #endif /*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ #include "fstb/def.h" #include "fstb/Vf32.h" #include "mfx/dsp/iir/SvfCore4SimdData.h" #include "mfx/dsp/iir/SvfMixerDefault.h" #include <array> namespace mfx { namespace dsp { namespace iir { template <class VD, class VS, class VP, class MX = SvfMixerDefault> class SvfCore4Simd { /*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ public: static const int _nbr_units = SvfCore4SimdData::_nbr_units; // Number of processing units static const int _latency_2x2 = _nbr_units / 2 - 1; // Latency for 2-way processing, samples static const int _latency_serial = _nbr_units - 1; // Latency for serial processing, samples typedef VD V128Dst; typedef VS V128Src; typedef VP V128Par; typedef MX Mixer; typedef SvfCore4SimdData::VectFloat4 VectFloat4; SvfCore4Simd () noexcept; SvfCore4Simd (const SvfCore4Simd <VD, VS, VP, MX> &other) noexcept; ~SvfCore4Simd () = default; SvfCore4Simd <VD, VS, VP, MX> & operator = (const SvfCore4Simd <VD, VS, VP, MX> &other) noexcept; void neutralise () noexcept; void neutralise_one (int unit) noexcept; void set_coefs (const VectFloat4 g0, const VectFloat4 g1, const VectFloat4 g2) noexcept; void set_coefs_one (int unit, float g0, float g1, float g2) noexcept; void get_coefs_one (int unit, float &g0, float &g1, float &g2) const noexcept; void set_mix (const VectFloat4 v0m, const VectFloat4 v1m, const VectFloat4 v2m) noexcept; void set_mix_one (int unit, float v0m, float v1m, float v2m) noexcept; void get_mix_one (int unit, float &v0m, float &v1m, float &v2m) const noexcept; void copy_z_eq (const SvfCore4Simd <VD, VS, VP, MX> &other) noexcept; void clear_buffers () noexcept; void clear_buffers_one (int unit) noexcept; // Parallel fstb_FORCEINLINE fstb::Vf32 process_sample_par (const fstb::Vf32 &x) noexcept; fstb_FORCEINLINE fstb::Vf32 process_sample_par (const fstb::Vf32 &x, const fstb::Vf32 &g0, const fstb::Vf32 &g1, const fstb::Vf32 &g2) noexcept; fstb_FORCEINLINE fstb::Vf32 process_sample_par (const fstb::Vf32 &x, const fstb::Vf32 &g0, const fstb::Vf32 &g1, const fstb::Vf32 &g2, const fstb::Vf32 &v0m, const fstb::Vf32 &v1m, const fstb::Vf32 &v2m) noexcept; fstb_FORCEINLINE fstb::Vf32 process_sample_par_inc (const fstb::Vf32 &x, const fstb::Vf32 &g0i, const fstb::Vf32 &g1i, const fstb::Vf32 &g2i, const fstb::Vf32 &v0mi, const fstb::Vf32 &v1mi, const fstb::Vf32 &v2mi) noexcept; fstb_FORCEINLINE std::array <fstb::Vf32, 2> process_sample_par_mm (const fstb::Vf32 &x) noexcept; fstb_FORCEINLINE std::array <fstb::Vf32, 2> process_sample_par_mm (const fstb::Vf32 &x, const fstb::Vf32 &g0, const fstb::Vf32 &g1, const fstb::Vf32 &g2) noexcept; fstb_FORCEINLINE std::array <fstb::Vf32, 2> process_sample_par_mm_inc (const fstb::Vf32 &x, const fstb::Vf32 &g0i, const fstb::Vf32 &g1i, const fstb::Vf32 &g2i) noexcept; void process_block_par (fstb::Vf32 dst_ptr [], const fstb::Vf32 src_ptr [], int nbr_spl) noexcept; void process_block_par (fstb::Vf32 dst_ptr [], const fstb::Vf32 src_ptr [], int nbr_spl, const fstb::Vf32 g0_ptr [], const fstb::Vf32 g1_ptr [], const fstb::Vf32 g2_ptr []) noexcept; void process_block_par (fstb::Vf32 dst_ptr [], const fstb::Vf32 src_ptr [], int nbr_spl, const fstb::Vf32 g0_ptr [], const fstb::Vf32 g1_ptr [], const fstb::Vf32 g2_ptr [], const fstb::Vf32 v0m_ptr [], const fstb::Vf32 v1m_ptr [], const fstb::Vf32 v2m_ptr []) noexcept; void process_block_par (fstb::Vf32 dst_ptr [], const fstb::Vf32 src_ptr [], int nbr_spl, const fstb::Vf32 &g0i, const fstb::Vf32 &g1i, const fstb::Vf32 &g2i, const fstb::Vf32 &v0mi, const fstb::Vf32 &v1mi, const fstb::Vf32 &v2mi) noexcept; // 2x2 with latency fstb_FORCEINLINE fstb::Vf32 process_sample_2x2_lat (const fstb::Vf32 &x) noexcept; fstb_FORCEINLINE fstb::Vf32 process_sample_2x2_lat (const fstb::Vf32 &x, const fstb::Vf32 &g0, const fstb::Vf32 &g1, const fstb::Vf32 &g2) noexcept; fstb_FORCEINLINE fstb::Vf32 process_sample_2x2_lat (const fstb::Vf32 &x, const fstb::Vf32 &g0, const fstb::Vf32 &g1, const fstb::Vf32 &g2, const fstb::Vf32 &v0m, const fstb::Vf32 &v1m, const fstb::Vf32 &v2m) noexcept; fstb_FORCEINLINE fstb::Vf32 process_sample_2x2_lat_inc (const fstb::Vf32 &x, const fstb::Vf32 &g0i, const fstb::Vf32 &g1i, const fstb::Vf32 &g2i, const fstb::Vf32 &v0mi, const fstb::Vf32 &v1mi, const fstb::Vf32 &v2mi) noexcept; void process_block_2x2_lat (float dst_ptr [], const float src_ptr [], int nbr_spl) noexcept; void process_block_2x2_lat (float dst_ptr [], const float src_ptr [], int nbr_spl, const fstb::Vf32 g0_ptr [], const fstb::Vf32 g1_ptr [], const fstb::Vf32 g2_ptr []) noexcept; void process_block_2x2_lat (float dst_ptr [], const float src_ptr [], int nbr_spl, const fstb::Vf32 g0_ptr [], const fstb::Vf32 g1_ptr [], const fstb::Vf32 g2_ptr [], const fstb::Vf32 v0m_ptr [], const fstb::Vf32 v1m_ptr [], const fstb::Vf32 v2m_ptr []) noexcept; void process_block_2x2_lat (float dst_ptr [], const float src_ptr [], int nbr_spl, const fstb::Vf32 &g0i, const fstb::Vf32 &g1i, const fstb::Vf32 &g2i, const fstb::Vf32 &v0mi, const fstb::Vf32 &v1mi, const fstb::Vf32 &v2mi) noexcept; // 2x2, immediate fstb_FORCEINLINE fstb::Vf32 process_sample_2x2_imm (const fstb::Vf32 &x) noexcept; fstb_FORCEINLINE fstb::Vf32 process_sample_2x2_imm (const fstb::Vf32 &x, const fstb::Vf32 &g0i, const fstb::Vf32 &g1i, const fstb::Vf32 &g2i, const fstb::Vf32 &v0mi, const fstb::Vf32 &v1mi, const fstb::Vf32 &v2mi) noexcept; void process_block_2x2_imm (float dst_ptr [], const float src_ptr [], int nbr_spl) noexcept; void process_block_2x2_imm (float dst_ptr [], const float src_ptr [], int nbr_spl, const fstb::Vf32 &g0i, const fstb::Vf32 &g1i, const fstb::Vf32 &g2i, const fstb::Vf32 &v0mi, const fstb::Vf32 &v1mi, const fstb::Vf32 &v2mi) noexcept; // Serial with latency fstb_FORCEINLINE float process_sample_ser_lat (float x_s) noexcept; fstb_FORCEINLINE float process_sample_ser_lat (float x_s, const fstb::Vf32 &g0, const fstb::Vf32 &g1, const fstb::Vf32 &g2) noexcept; fstb_FORCEINLINE float process_sample_ser_lat (float x_s, const fstb::Vf32 &g0, const fstb::Vf32 &g1, const fstb::Vf32 &g2, const fstb::Vf32 &v0m, const fstb::Vf32 &v1m, const fstb::Vf32 &v2m) noexcept; fstb_FORCEINLINE float process_sample_ser_lat_inc (float x_s, const fstb::Vf32 &g0i, const fstb::Vf32 &g1i, const fstb::Vf32 &g2i, const fstb::Vf32 &v0mi, const fstb::Vf32 &v1mi, const fstb::Vf32 &v2mi) noexcept; void process_block_ser_lat (float dst_ptr [], const float src_ptr [], int nbr_spl) noexcept; void process_block_ser_lat (float dst_ptr [], const float src_ptr [], int nbr_spl, const fstb::Vf32 g0_ptr [], const fstb::Vf32 g1_ptr [], const fstb::Vf32 g2_ptr []) noexcept; void process_block_ser_lat (float dst_ptr [], const float src_ptr [], int nbr_spl, const fstb::Vf32 g0_ptr [], const fstb::Vf32 g1_ptr [], const fstb::Vf32 g2_ptr [], const fstb::Vf32 v0m_ptr [], const fstb::Vf32 v1m_ptr [], const fstb::Vf32 v2m_ptr []) noexcept; void process_block_ser_lat (float dst_ptr [], const float src_ptr [], int nbr_spl, const fstb::Vf32 &g0i, const fstb::Vf32 &g1i, const fstb::Vf32 &g2i, const fstb::Vf32 &v0mi, const fstb::Vf32 &v1mi, const fstb::Vf32 &v2mi) noexcept; // Serial, immediate fstb_FORCEINLINE float process_sample_ser_imm (float x_s) noexcept; fstb_FORCEINLINE float process_sample_ser_imm (float x_s, const fstb::Vf32 &g0i, const fstb::Vf32 &g1i, const fstb::Vf32 &g2i, const fstb::Vf32 &v0mi, const fstb::Vf32 &v1mi, const fstb::Vf32 &v2mi) noexcept; void process_block_ser_imm (float dst_ptr [], const float src_ptr [], int nbr_spl) noexcept; void process_block_ser_imm (float dst_ptr [], const float src_ptr [], int nbr_spl, const fstb::Vf32 &g0i, const fstb::Vf32 &g1i, const fstb::Vf32 &g2i, const fstb::Vf32 &v0mi, const fstb::Vf32 &v1mi, const fstb::Vf32 &v2mi) noexcept; /*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ protected: /*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ private: fstb_FORCEINLINE void process_block_ser_imm_pre (const float src_ptr []) noexcept; fstb_FORCEINLINE void process_block_2x2_imm_pre (const float src_ptr []) noexcept; fstb_FORCEINLINE void process_block_ser_imm_post (float dst_ptr []) noexcept; fstb_FORCEINLINE void process_block_ser_imm_post (float dst_ptr [], const fstb::Vf32 &g0i, const fstb::Vf32 &g1i, const fstb::Vf32 &g2i, const fstb::Vf32 &v0mi, const fstb::Vf32 &v1mi, const fstb::Vf32 &v2mi) noexcept; fstb_FORCEINLINE void process_block_2x2_imm_post (float dst_ptr []) noexcept; fstb_FORCEINLINE void process_block_2x2_imm_post (float dst_ptr [], const fstb::Vf32 &g0i, const fstb::Vf32 &g1i, const fstb::Vf32 &g2i, const fstb::Vf32 &v0mi, const fstb::Vf32 &v1mi, const fstb::Vf32 &v2mi) noexcept; static fstb_FORCEINLINE float process_sample_single_stage (SvfCore4SimdData &data, float x_s, int stage, int stage_y) noexcept; static fstb_FORCEINLINE void iterate_parallel (const fstb::Vf32 &v0, fstb::Vf32 &v1, fstb::Vf32 &v2, fstb::Vf32 &ic1eq, fstb::Vf32 &ic2eq, const fstb::Vf32 &g0, const fstb::Vf32 &g1, const fstb::Vf32 &g2) noexcept; static fstb_FORCEINLINE void increment (SvfCore4SimdData &data, const fstb::Vf32 &g0i, const fstb::Vf32 &g1i, const fstb::Vf32 &g2i, const fstb::Vf32 &v0mi, const fstb::Vf32 &v1mi, const fstb::Vf32 &v2mi) noexcept; static fstb_FORCEINLINE void increment (fstb::Vf32 &g0, fstb::Vf32 &g1, fstb::Vf32 &g2, fstb::Vf32 &v0m, fstb::Vf32 &v1m, fstb::Vf32 &v2m, const fstb::Vf32 &g0i, const fstb::Vf32 &g1i, const fstb::Vf32 &g2i, const fstb::Vf32 &v0mi, const fstb::Vf32 &v1mi, const fstb::Vf32 &v2mi) noexcept; static fstb_FORCEINLINE void increment (fstb::Vf32 &g0, fstb::Vf32 &g1, fstb::Vf32 &g2, const fstb::Vf32 &g0i, const fstb::Vf32 &g1i, const fstb::Vf32 &g2i) noexcept; SvfCore4SimdData _data; /*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ private: bool operator == (const SvfCore4Simd <VD, VS, VP, MX> &other) const = delete; bool operator != (const SvfCore4Simd <VD, VS, VP, MX> &other) const = delete; }; // class SvfCore4Simd } // namespace iir } // namespace dsp } // namespace mfx #include "mfx/dsp/iir/SvfCore4Simd.hpp" #endif // mfx_dsp_iir_SvfCore4Simd_HEADER_INCLUDED /*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
<filename>src/function/relu.h #ifndef RELU_H #define RELU_H /* relu : 1次元配列の各要素に対してReLUを通す関数 Parameters ---------- input_x : array of pointer to float 一次元配列 len : int 一次元配列の要素数 */ void relu(float *, int); #endif
// // Copyright (c) 2015 <NAME> // // 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. #import <Foundation/Foundation.h> #import <CoreBluetooth/CoreBluetooth.h> typedef NS_ENUM(NSUInteger, YBlePeripheralState) { YBlePeripheralStateIdle = 0, YBlePeripheralStateConnecting, YBlePeripheralStateConnected, YBlePeripheralStateDisconnecting, }; @class YBleCentral; @class YBleService, YBleCharacteristic; typedef void(^PeripheralNameUpdatedBlock)(NSString *name); typedef void(^PeripheralStateUpdatedBlock)(YBlePeripheralState state, NSError *error); typedef void(^ServicesDiscoveredBlock)(YBleService *service, NSError *error); typedef void(^ValueUpdatedBlock)(NSData *data, NSError *error); typedef void(^ValueWrittenBlock)(NSData *data, NSError *error); typedef void(^NotificationStateBlock)(BOOL notifying, NSError *error); typedef void(^RssiUpdatedBlock)(NSNumber *rssi, NSError *error); @interface YBlePeripheral : NSObject @property (weak, readonly) YBleCentral *central; @property (strong, readonly) CBPeripheral *cbperipheral; @property (strong, readonly) NSUUID *uuid; @property (strong, readonly) NSString *name; @property (assign, readonly) YBlePeripheralState state; @property (strong, readonly) NSDictionary *advertisementData; @property (strong, readonly) NSNumber *rssi; @property (strong, readonly) NSDate *lastFound; @property (copy, readwrite) PeripheralNameUpdatedBlock nameUpdateBlock; @property (copy, readwrite) PeripheralStateUpdatedBlock stateUpdateBlock; - (instancetype)initWithCBPeripheral:(CBPeripheral *)peripheral central:(YBleCentral *)central; // options is same as CBCentralManager's Peripheral Connection Options - (void)connectWithOptions:(NSDictionary *)options; - (void)connect; - (void)disconnect; - (void)discoverServices:(NSArray *)services discovered:(ServicesDiscoveredBlock)block; - (void)readRssiCallback:(RssiUpdatedBlock)block; /***** * there are three groups of get value updated from characteristic. do not mix use them for single characteristic. */ - (void)setValueUpdatedBlock:(ValueUpdatedBlock)block forCharacteristic:(YBleCharacteristic *)characteristic; - (void)readCharacteristic:(YBleCharacteristic *)characteristic; - (void)setCharacteristic:(YBleCharacteristic *)characteristic notifying:(BOOL)notifying stateCallback:(NotificationStateBlock)stateBlock; - (void)readCharacteristic:(YBleCharacteristic *)characteristic callback:(ValueUpdatedBlock)block; - (void)setCharacteristic:(YBleCharacteristic *)characteristic notifying:(BOOL)notifying stateCallback:(NotificationStateBlock)stateBlock valueCallback:(ValueUpdatedBlock)valueBlock; /* *****/ - (void)writeCharacteristic:(YBleCharacteristic *)characteristic value:(NSData *)data callback:(ValueWrittenBlock)callback; @end @interface CBPeripheral (universeralIdentifier) - (NSUUID *)uuid; @end @interface YBleService : NSObject @property (strong, readonly) CBUUID *uuid; @property (strong, readonly) NSDictionary *characteristics; - (instancetype)initWithUUID:(CBUUID *)uuid; - (void)addCharacteristic:(YBleCharacteristic*)characteristic; @end @interface YBleCharacteristic : NSObject @property (strong, readonly) CBUUID *uuid; @property (weak, readonly) YBleService *service; @property (assign, readonly) BOOL isNotifying; @property (assign, readonly) CBCharacteristicProperties properties; - (instancetype)initWithUUID:(CBUUID *)uuid; - (void)readValue:(ValueUpdatedBlock)block; - (void)writeValue:(NSData *)value callback:(ValueWrittenBlock)block; @end
<reponame>lrsantos11/PCx-LRS /* solve for the predictor and corrector steps * * PCx 1.1 11/97 * * Authors: <NAME>, <NAME>, <NAME>, <NAME>. * * (C) 1996 University of Chicago. See COPYRIGHT in main directory. */ #include <math.h> #include <stdio.h> #include "main.h" #include "memory.h" TestGondzio (A, Factor, scale, Current, Predictor, Corrector, comp_xs, comp_rw) MMTtype *A; NgPeyton *Factor; double *scale; Iterate *Current, *Predictor, *Corrector; double *comp_xs, *comp_rw; { int SolveAugmented(); int NumRows, NumCols, NumBounds, i, irow; int CorrectionNumber; int ContinueCorrecting; double *tmp_col, *tmp_row; double *x, *s, *pi, *r, *w; double *dx, *ds, *dpi, *dr, *dw; double *dx2, *ds2, *dpi2, *dr2, *dw2; /*******************************************************************/ /* Initialize and transfer to local pointers */ /*******************************************************************/ x = Current->x; dx = Predictor->x; dx2 = Corrector->x; s = Current->s; ds = Predictor->s; ds2 = Corrector->s; w = Current->w; dw = Predictor->w; dw2 = Corrector->w; r = Current->r; dr = Predictor->r; dr2 = Corrector->r; pi = Current->pi; dpi = Predictor->pi; dpi2 = Corrector->pi; NumRows = A->NumRows; NumCols = A->NumCols; NumBounds = Current->NumBounds; tmp_row = NewDouble(NumRows, "tmp_row"); tmp_col = NewDouble(NumCols, "tmp_row"); /* First equation */ RealSparseMatrixVectorProduct (A->Value, A->pBeginRow, A->pEndRow, A->Row, dx2, tmp_row, &(A->NumRows), &(A->NumCols)); printf("First Equation:\n"); for (i = 0; i < NumRows; i++) if (fabs(tmp_row[i]) > 1.0e-8) printf("tmp_row[%d] = %f\n", i, tmp_row[i]); /* Second equation */ RealSparseMatrixTransposeVectorProduct (A->Value, A->pBeginRow, A->pEndRow, A->Row, dpi2, tmp_col, &(A->NumRows), &(A->NumCols)); for (i = 0; i < NumCols; i++) tmp_col[i] += ds2[i]; for (i = 0; i < NumBounds; i++) { irow = Current->BoundIndex[i] - 1; tmp_col[irow] -= dr2[i]; } printf("Second Equation:\n"); for (i = 0; i < NumCols; i++) if (fabs(tmp_col[i]) > 1.0e-8) printf("tmp_col[%d] = %f\n", i, tmp_col[i]); /* third equation */ printf("Third Equation:\n"); for (i = 0; i < NumBounds; i++) { irow = Current->BoundIndex[i] - 1; if (fabs(dx2[irow] + dw2[i]) > 1.0e-8) printf("dx2[%d] = %f dw2 = %f\n", i, dx2[irow], dw2[i]); } /* fourth equation */ printf("Fourth Equation:\n"); for (i = 0; i < NumCols; i++) tmp_col[i] = s[i] * dx2[i] + x[i] * ds2[i]; for (i = 0; i < NumCols; i++) if (tmp_col[i] + comp_xs[i] > 1.0e-8) printf("%d: tmp_col = %f comp_xs = %f\n", i, tmp_col[i], comp_xs[i]); /* fifth equation */ printf("Fifth equation:\n"); for (i = 0; i < NumBounds; i++) tmp_col[i] = r[i] * dw2[i] + w[i] * dr2[i]; for (i = 0; i < NumBounds; i++) if (tmp_col[i] - comp_rw[i] > 1.0e-8) printf("%d: tmp_col = %f comp_rw = %f\n", tmp_col[i], comp_rw[i]); Free((char *) tmp_col); Free((char *) tmp_row); return 0; }
<filename>src/solar2.c #if HAVE_CONFIG_H #include <config.h> #endif #include <stdio.h> #define __STDC_VERSION__ 199901L #define _USE_MATH_DEFINES #include <math.h> #include <solar-common.h> #include <solar2.h> /*#define PI 3.1415926 #define ZENITH -.83*/ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunsuffixed-float-constants" const double ZENITH = -.83; #pragma GCC diagnostic pop __attribute__ ((const, leaf, nothrow, warn_unused_result)) double calculateSunrise( int year, int month, int day, double lat, double lng, int localOffset, int daylightSavings, bool sunset) { /* localOffset will be <0 for western hemisphere and >0 for eastern hemisphere daylightSavings should be 1 if it is in effect during the summer otherwise it should be 0 */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunsuffixed-float-constants" /* 1. first calculate the day of the year */ double N1 = floor (275.0 * (double) month / 9.0); double N2 = floor ((double) (month + 9) / 12.0); double N31 = 4 * floor ((double) year / 4.0); double N3 = (1 + floor ((year - 4 * N31 + 2) / 3.0)); double N = N1 - (N2 * N3) + day - 30; /* 2. convert the longitude to hour value and calculate an approximate time */ double lngHour = lng / 15.0; double t; double M; double L1, L2, L; double RA1, RA; double Lquadrant; double RAquadrant; double sinDec, cosDec; double cosH1, cosH2, cosH3; double cosH; double H; double T; double UT; if (! sunset) t = N + ((6 - lngHour) / 24.0); /* if rising time is desired: */ else t = N + ((18 - lngHour) / 24.0); /* if setting time is desired: */ /* 3. calculate the Sun's mean anomaly */ M = (0.9856 * t) - 3.289; /* 4. calculate the Sun's true longitude */ L1 = 1.916 * sin ((M_PI / 180) * M); L2 = 0.020 * sin (2 *(M_PI / 180) * M); L = fmod (M + L1 + L2 + 282.634, 360.0); /* 5a. calculate the Sun's right ascension */ RA1 = 0.91764 * tan ((M_PI/180)*L); RA = fmod (180/M_PI*atan (RA1), 360.0); /* 5b. right ascension value needs to be in the same quadrant as L */ Lquadrant = floor ( L/90) * 90; RAquadrant = floor (RA/90) * 90; RA = RA + (Lquadrant - RAquadrant); /* 5c. right ascension value needs to be converted into hours */ RA = RA / 15.0; /* 6. calculate the Sun's declination */ /*float*/ sinDec = 0.39782 * sin ((M_PI/180)*L); /*float*/ cosDec = cos (asin (sinDec)); /* 7a. calculate the Sun's local hour angle */ cosH1 = sin ((M_PI/180)*ZENITH); cosH2 = sin ((M_PI/180)*lat); cosH3 = cos ((M_PI/180)*lat); /*float*/ cosH = (cosH1 - (sinDec * cosH2)) / (cosDec * cosH3); /* if (cosH > 1) the sun never rises on this location (on the specified date) if (cosH < -1) the sun never sets on this location (on the specified date) */ /* 7b. finish calculating H and convert into hours */ /*float*/ H = 360 - (180/M_PI) * acos (cosH); /* if if rising time is desired: */ /*float H = acos(cosH)*/ /* if setting time is desired: */ /*float H = (180/PI)*acos(cosH)*/ /* if setting time is desired: */ H = H / 15; /* 8. calculate local mean time of rising/setting */ /*float*/ T = H + RA - (0.06571 * t) - 6.622; /* 9. adjust back to UTC */ /*float*/ UT = fmod (T - lngHour, 24.0); /* 10. convert UT value to local time zone of latitude/longitude */ return UT + localOffset + daylightSavings; #pragma GCC diagnostic pop }
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */ /** * \file blood_pressure_monitor.c * \brief Blood Pressure Monitor Specialization Implementation * * Copyright (C) 2010 Signove Tecnologia Corporation. * All rights reserved. * Contact: Signove Tecnologia Corporation (<EMAIL>) * * $LICENSE_TEXT:BEGIN$ * 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 and appearing * in the file LICENSE included in the packaging of this file; 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 * $LICENSE_TEXT:END$ * * \date Jun 24, 2010 * \author <NAME>, <NAME> */ #include <stdio.h> #include "src/specializations/blood_pressure_monitor.h" #include "src/util/bytelib.h" #include "src/dim/mds.h" #include "src/dim/nomenclature.h" #include "src/util/dateutil.h" #include "communication/parser/encoder_ASN1.h" #include "communication/parser/struct_cleaner.h" /** * @defgroup DeviceSpecializations Device Specializations * @brief IEEE 11073-20601 Device Specializations. For more * information about device specializations at IEEE library * , see documentation on \ref SpecializationDescription "IEEE device specializations" * @page SpecializationDescription IEEE Device Specialization * * * The ISO/IEEE 11073-104zz device specializations define mandatory * objects and attributes that shall exist within an agents configuration. * Furthermore, each of the specializations defines mandatory elements * (e.g., including mandatory actions and methods) of the service and * communication models, which have to be supported by an agent following * that specialization. * * \par Procedure to add a new specialization * * The manager is the entity responsible for the management of all * specializations and it is the start point to add any new standard * specialization. The steps to add a new specialization are described * below: * * 1 – Create a new configuration (one configuration for each * specialization). A standard configuration is represented in * the system by a struct named StdConfiguration. This struct * has the following attributes that must be defined: * * \b dev_config_id – The hexadecimal constant for the device. * * \b configure_action – Returns the configuration of the device. * * \b ds_to_string_function – Process the MDS received by manager * from device and returns a string. * * 2 – Register the new configuration. * In the manager_init() function of manager.c file the developer * has to add one or more calls to the function std_configurations_register_conf * (struct StdConfiguration *config). This will register the new * configuration within the manager. * * For example, the following code registers the standard configuration of * the <em>Pulse Oximeter Monitor</em> specialization (the specialization * provides two different standard configurations). * * \code * * std_configurations_register_conf(pulse_oximeter_create_std_config_ID0190()); * std_configurations_register_conf(pulse_oximeter_create_std_config_ID0191()); * * \endcode * */ /** * \defgroup BloodPressure Blood Pressure Monitor * \ingroup DeviceSpecializations * \brief Blood Pressure Monitor IEEE specialization * * A blood pressure monitor is a device that measures blood pressure * [i.e., systolic, diastolic, and mean arterial pressure (MAP)] and, * optionally, pulse noninvasively. Blood pressure monitor devices * considered in this standard typically inflate a cuff to occlude an * artery and then to measure the reaction of the artery while the * pressure is released with the results being converted into systolic, * diastolic, and MAP values. Optionally, pulse rate may be determined * at the same time. * * Blood pressure monitor devices may use a variety of techniques for * measuring blood pressure and pulse rate. One typical method is the * oscillometric method where oscillations in cuff pressure are analyzed * to obtain blood pressure values. Another technique is the automated * auscultatory method where the device uses a microphone to detect * Korotkoff sounds during cuff deflation. * * Auscultatory devices measure the systolic and diastolic values * and estimates the MAP. In home monitors, the oscillometric method * is typically used, allowing the measurement to be done electronically. * On the oscillometric method, small pressure changes (oscillations) * occur in the cuff as a result of blood pressure pulses during the * inflation or deflation of the cuff and are detected. These oscillations, * which first increase and then decrease, are stored together with * the corresponding cuff pressure values in the automated sphygmomanometer. * With these stored values, the systolic, diastolic, and mean blood * pressure values can be mathematically derived using an appropriate algorithm. * * The blood pressure receives two different measurements: 1) Systolic, diastolic, MAP * and 2) Pulse rate. * * The measures are read from a Numeric object and data are saved at * numeric->compound_basic_nu_observed_value->value field. The following example reads * systolic, diastolic and MAP data, and simply prints them. * * \code * * struct MDS_object* obj1 = mds_get_object_by_handle(HANDLE_MEASUREMENT_1); * * if (obj1 != NULL && obj1->choice == MDS_OBJ_METRIC) { * * if (obj1->u.metric.choice == METRIC_NUMERIC){ * struct Numeric* numeric = &obj1->u.metric.u.numeric; * * if (numeric->compound_basic_nu_observed_value.count > 0){ * unsigned char *unit_label = mds_get_unit_code_string(numeric->metric.unit_code); * * sprintf(str, "%s Pressure systolic (%s): %.2f,", str, unit_label, * numeric->compound_basic_nu_observed_value.value[0]); * sprintf(str, "%s diastolic: %.2f,",str, * numeric->compound_basic_nu_observed_value.value[1]); * sprintf(str, "%s mean: %.2f\n", str, * numeric->compound_basic_nu_observed_value.value[2]); * * sprintf(str, "%s Measurement time: %2.X/%.2X/%.2X %.2X:%.2X:%.2X\n", str, * numeric->metric.absolute_time_stamp.day, * numeric->metric.absolute_time_stamp.month, * numeric->metric.absolute_time_stamp.year, * numeric->metric.absolute_time_stamp.hour, * numeric->metric.absolute_time_stamp.minute, * numeric->metric.absolute_time_stamp.second); * } * } * } * * \endcode * * @{ */ /** Measurement 1: Systolic, diastolic, MAP */ #define HANDLE_MEASUREMENT_1 1 /** Measurement 2: Pulse rate */ #define HANDLE_MEASUREMENT_2 2 /** * Returns the standard configuration for <em>Blood Pressure Monitor</em> specialization (02BC). * For more information about <em>Blood Pressure Monitor</em> specialization, see IEEE 11073-10407 * Standard (Section 6.4, page 7). * * \return an StdConfiguration struct that represents the standard configuration (a StdConfiguration instance) * for <em>Blood Pressure Monitor</em> specialization. */ static ConfigObjectList *blood_pressure_monitor_get_config_ID02BC() { ConfigObjectList *std_object_list = malloc(sizeof(ConfigObjectList)); std_object_list->count = 2; std_object_list->length = 108; std_object_list->value = malloc(sizeof(ConfigObject) * std_object_list->count); std_object_list->value[0].obj_class = MDC_MOC_VMO_METRIC_NU; std_object_list->value[0].obj_handle = HANDLE_MEASUREMENT_1; AttributeList *attr_list1 = malloc(sizeof(AttributeList)); attr_list1->count = 6; attr_list1->length = 56; attr_list1->value = malloc(attr_list1->count * sizeof(AVA_Type)); attr_list1->value[0].attribute_id = MDC_ATTR_ID_TYPE; attr_list1->value[0].attribute_value.length = 4; ByteStreamWriter *bsw = byte_stream_writer_instance(4); write_intu16(bsw, MDC_PART_SCADA); write_intu16(bsw, MDC_PRESS_BLD_NONINV); attr_list1->value[0].attribute_value.value = bsw->buffer; attr_list1->value[1].attribute_id = MDC_ATTR_METRIC_SPEC_SMALL; attr_list1->value[1].attribute_value.length = 2; free(bsw); bsw = byte_stream_writer_instance(2); write_intu16(bsw, 0xF040); // 0xF0 0x40 intermittent, stored data, upd & msmt aperiodic, agent init, measured attr_list1->value[1].attribute_value.value = bsw->buffer; attr_list1->value[2].attribute_id = MDC_ATTR_METRIC_STRUCT_SMALL; attr_list1->value[2].attribute_value.length = 2; free(bsw); bsw = byte_stream_writer_instance(2); write_intu16(bsw, 0x0303); attr_list1->value[2].attribute_value.value = bsw->buffer; attr_list1->value[3].attribute_id = MDC_ATTR_ID_PHYSIO_LIST; attr_list1->value[3].attribute_value.length = 10; free(bsw); bsw = byte_stream_writer_instance(10); write_intu16(bsw, 0x0003); // MetricIdList.count = 3 write_intu16(bsw, 0x0006); // MetricIdList.length = 6 write_intu16(bsw, MDC_PRESS_BLD_NONINV_SYS); write_intu16(bsw, MDC_PRESS_BLD_NONINV_DIA); write_intu16(bsw, MDC_PRESS_BLD_NONINV_MEAN); attr_list1->value[3].attribute_value.value = bsw->buffer; attr_list1->value[4].attribute_id = MDC_ATTR_UNIT_CODE; attr_list1->value[4].attribute_value.length = 2; free(bsw); bsw = byte_stream_writer_instance(2); write_intu16(bsw, MDC_DIM_MMHG); attr_list1->value[4].attribute_value.value = bsw->buffer; attr_list1->value[5].attribute_id = MDC_ATTR_ATTRIBUTE_VAL_MAP; attr_list1->value[5].attribute_value.length = 12; free(bsw); bsw = byte_stream_writer_instance(12); write_intu16(bsw, 0x0002); // AttrValMap.count = 2 write_intu16(bsw, 0x0008); // AttrValMap.length = 8 write_intu16(bsw, MDC_ATTR_NU_CMPD_VAL_OBS_BASIC); write_intu16(bsw, 0x000A); // value length 10 write_intu16(bsw, MDC_ATTR_TIME_STAMP_ABS); write_intu16(bsw, 0x0008); // value length 8 attr_list1->value[5].attribute_value.value = bsw->buffer; std_object_list->value[1].obj_class = MDC_MOC_VMO_METRIC_NU; std_object_list->value[1].obj_handle = HANDLE_MEASUREMENT_2; AttributeList *attr_list2 = malloc(sizeof(AttributeList)); attr_list2->count = 4; attr_list2->length = 36; attr_list2->value = malloc(attr_list2->count * sizeof(AVA_Type)); attr_list2->value[0].attribute_id = MDC_ATTR_ID_TYPE; attr_list2->value[0].attribute_value.length = 4; free(bsw); bsw = byte_stream_writer_instance(4); write_intu16(bsw, MDC_PART_SCADA); write_intu16(bsw, MDC_PULS_RATE_NON_INV); attr_list2->value[0].attribute_value.value = bsw->buffer; attr_list2->value[1].attribute_id = MDC_ATTR_METRIC_SPEC_SMALL; attr_list2->value[1].attribute_value.length = 2; free(bsw); bsw = byte_stream_writer_instance(2); write_intu16(bsw, 0xF040); // 0xF0 0x40 intermittent, stored data, upd & msmt aperiodic, agent init, measured attr_list2->value[1].attribute_value.value = bsw->buffer; attr_list2->value[2].attribute_id = MDC_ATTR_UNIT_CODE; attr_list2->value[2].attribute_value.length = 2; free(bsw); bsw = byte_stream_writer_instance(2); write_intu16(bsw, MDC_DIM_BEAT_PER_MIN); attr_list2->value[2].attribute_value.value = bsw->buffer; attr_list2->value[3].attribute_id = MDC_ATTR_ATTRIBUTE_VAL_MAP; attr_list2->value[3].attribute_value.length = 12; free(bsw); bsw = byte_stream_writer_instance(12); write_intu16(bsw, 0x0002); // AttrValMap.count = 2 write_intu16(bsw, 0x0008); // AttrValMap.length = 8 write_intu16(bsw, MDC_ATTR_NU_VAL_OBS_BASIC); write_intu16(bsw, 0x0002); // value length 2 write_intu16(bsw, MDC_ATTR_TIME_STAMP_ABS); write_intu16(bsw, 0x0008); // value length 8 attr_list2->value[3].attribute_value.value = bsw->buffer; std_object_list->value[0].attributes = *attr_list1; std_object_list->value[1].attributes = *attr_list2; free(attr_list1); free(attr_list2); free(bsw); return std_object_list; } /** * Populates an event report APDU. */ static DATA_apdu *blood_pressure_populate_event_report(void *edata) { DATA_apdu *data; EventReportArgumentSimple evt; ScanReportInfoFixed scan; ObservationScanFixedList scan_fixed; ObservationScanFixed measure[2]; AbsoluteTime nu_time; BasicNuObsValueCmp nu_pressure; BasicNuObsValue nu_pulse_rate; struct blood_pressure_event_report_data *evtdata; data = calloc(sizeof(DATA_apdu), 1); evtdata = (struct blood_pressure_event_report_data*) edata; nu_time = date_util_create_absolute_time(evtdata->century * 100 + evtdata->year, evtdata->month, evtdata->day, evtdata->hour, evtdata->minute, evtdata->second, evtdata->sec_fractions); nu_pressure.count = 0x03; nu_pressure.length = 0x06; nu_pressure.value = calloc(sizeof(BasicNuObsValue), 3); nu_pressure.value[0] = evtdata->systolic; nu_pressure.value[1] = evtdata->diastolic; nu_pressure.value[2] = evtdata->mean; nu_pulse_rate = evtdata->pulse_rate; // will be filled afterwards by service_* function data->invoke_id = 0xffff; data->message.choice = ROIV_CMIP_CONFIRMED_EVENT_REPORT_CHOSEN; data->message.length = 54; evt.obj_handle = 0; evt.event_time = 0xFFFFFFFF; evt.event_type = MDC_NOTI_SCAN_REPORT_FIXED; evt.event_info.length = 44; scan.data_req_id = 0xF000; scan.scan_report_no = 0; scan_fixed.count = 2; scan_fixed.length = 36; scan_fixed.value = measure; measure[0].obj_handle = 1; measure[0].obs_val_data.length = 18; ByteStreamWriter *writer0 = byte_stream_writer_instance( measure[0].obs_val_data.length); encode_basicnuobsvaluecmp(writer0, &nu_pressure); encode_absolutetime(writer0, &nu_time); measure[1].obj_handle = 2; measure[1].obs_val_data.length = 10; ByteStreamWriter *writer1 = byte_stream_writer_instance( measure[1].obs_val_data.length); encode_basicnuobsvalue(writer1, &nu_pulse_rate); encode_absolutetime(writer1, &nu_time); measure[0].obs_val_data.value = writer0->buffer; measure[1].obs_val_data.value = writer1->buffer; scan.obs_scan_fixed = scan_fixed; ByteStreamWriter *scan_writer = byte_stream_writer_instance( evt.event_info.length); encode_scanreportinfofixed(scan_writer, &scan); del_byte_stream_writer(writer0, 1); del_byte_stream_writer(writer1, 1); del_basicnuobsvaluecmp(&nu_pressure); evt.event_info.value = scan_writer->buffer; data->message.u.roiv_cmipEventReport = evt; del_byte_stream_writer(scan_writer, 0); return data; } /** * Creates the standard configuration for <em>Blood Pressure Monitor</em> specialization (02BC). * For more information about <em>Blood Pressure Monitor</em> specialization, see IEEE 11073-10407 * Standard (Section 6.4, page 7). * * \return an StdConfiguration struct that represents the standard configuration (a StdConfiguration instance) * for <em>Blood Pressure Monitor</em> specialization just created. */ struct StdConfiguration *blood_pressure_monitor_create_std_config_ID02BC() { struct StdConfiguration *result = calloc(1, sizeof(struct StdConfiguration)); result->dev_config_id = 0x02BC; result->configure_action = &blood_pressure_monitor_get_config_ID02BC; result->event_report = &blood_pressure_populate_event_report; return result; } /** @} */
<filename>ABFramework/iOS/Components (Functional)/ABStoreKitHelper/ABStoreKitHelper.h // // ABStoreKitHelper.h // ABFramework // // Created by <NAME> on 2/23/13. // Copyright (c) 2013 Ablfx. All rights reserved. // #import <Foundation/Foundation.h> #import <StoreKit/StoreKit.h> #ifndef ABSTOREKITHELPER_LOGGING #define ABSTOREKITHELPER_LOGGING 1 #endif /** * Types */ typedef NS_ENUM(NSInteger, ABStoreKitItemType) { ABStoreKitItemTypeNone, ABStoreKitItemTypeConsumable, ABStoreKitItemTypeNonConsumable, ABStoreKitItemTypeAutoRenewableSubscription, ABStoreKitItemTypeNonRenewingSubscription, ABStoreKitItemTypeFreeSubscription, ABStoreKitItemTypeFake }; typedef NS_ENUM(NSInteger, ABStoreKitTimeInterval) { ABStoreKitTimeIntervalNone, ABStoreKitTimeIntervalOneMonth, ABStoreKitTimeIntervalOneYear }; typedef NS_ENUM(NSInteger, ABStoreKitError) { ABStoreKitErrorNone, ABStoreKitErrorPurchaseNotAllowed, ABStoreKitErrorProductNotValidated, ABStoreKitErrorGeneral }; typedef void (^ABStoreKitBlock) (NSString *productIdentifier, BOOL successful, ABStoreKitError error); typedef void (^ABStoreKitRestoreBlock) (NSArray *restoredItems, BOOL hasProducts, ABStoreKitError error); /** * ABStoreKitItem */ @interface ABStoreKitItem : NSObject <NSCoding> +(id) itemWithProductIdentifier:(NSString*)productIdentifier type:(ABStoreKitItemType)type; +(id) itemWithProductIdentifier:(NSString*)productIdentifier type:(ABStoreKitItemType)type subscriptionTimeInterval:(ABStoreKitTimeInterval)interval; -(NSDate*) subscriptionExpireDate; @property (nonatomic, assign) ABStoreKitItemType type; @property (nonatomic, copy) NSString *productIdentifier; @property (nonatomic, copy) NSString *transactionIdentifier; @property (nonatomic, strong) NSDate *transactionDate; @property (nonatomic, assign) ABStoreKitTimeInterval subscriptionTimeInterval; @end /** * ABStoreKitHelper */ @interface ABStoreKitHelper : NSObject { // } //Utility /** * Call this once on launch to setup everything up (don't forget to set "storeKitItems"), * actually why not do it in same step: [[ABStoreKitHelper sharedHelper] setStoreKitItems:...]; */ + (id) sharedHelper; //Helper /** * Returns YES if a specfic product was purchased */ -(BOOL) isPurchased:(NSString*)productIdentifier; //Subscriptions /** * Returns YES if a subscription is still active (Offline check) */ -(BOOL) isSubscriptionActive:(NSString*)productIdentifier; /** * Returns an array of ABStoreKitItem's for a subscription product identifier, if it has been purchased/restored (nil otherwise) * * If an Auto-Renewable subscription was renewed atleast once this array will contain multiple instances of ABStoreKitItem's * with the same product identifier with alternating "transactionDate"'s */ -(NSArray*) purchasedInstancesOfSubscription:(NSString*)productIdentifier; /** * Returns YES if a date is in the active timespan(s) of a specific subscription / or an array of subscriptions */ -(BOOL) isDate:(NSDate*)date inSubscription:(NSString*)productIdentifier; -(BOOL) isDate:(NSDate*)date inSubscriptions:(NSArray*)productIdentifiers; //Purchase /** * Perform a purchase request */ -(void) purchaseProduct:(NSString*)productIdentifier block:(ABStoreKitBlock)block; //Restore /** * Restore all previous purchases */ -(void) restorePurchases:(ABStoreKitRestoreBlock)block; //Misc /** * Log all purchased subscriptions */ -(void) logSubscriptions; /** * Fake purchase a specific product, if product is a subscription it will always be active */ -(void) fakePurchaseProduct:(NSString*)productIdentifier; -(void) removeAllFakePurchases; /** * Set of ABStoreKitItem's, you need to set all you intend to use! */ @property (nonatomic, strong) NSSet *storeKitItems; @end
<filename>src/types.c #include "types.h" u8 getZeroU8() { return 0; } u16 getZeroU16() { return 0; } u32 getZeroU32() { return 0; } u8 rol8(u8 value, u16 number) { return (value << number) | (value >> (8 - number)); } u16 rol16(u16 value, u16 number) { return (value << number) | (value >> (16 - number)); } u32 rol32(u32 value, u16 number) { return (value << number) | (value >> (32 - number)); } u8 ror8(u8 value, u16 number) { return (value >> number) | (value << (8 - number)); } u16 ror16(u16 value, u16 number) { return (value >> number) | (value << (16 - number)); } u32 ror32(u32 value, u16 number) { return (value >> number) | (value << (32 - number)); }
/* * This header is generated by classdump-dyld 1.5 * on Wednesday, April 28, 2021 at 9:09:23 PM Mountain Standard Time * Operating System: Version 14.5 (Build 18L204) * Image Source: /System/Library/PrivateFrameworks/HomeKitDaemon.framework/HomeKitDaemon * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>. */ @class NSString, HMDAccessoryNetworkCredential; @interface HMDUnpairedHAPAccessoryConfiguration : NSObject { BOOL _requiresUserConsent; NSString* _homeName; NSString* _setupCode; /*^block*/id _setupCodeProvider; HMDAccessoryNetworkCredential* _networkCredential; NSString* _isoCountryCode; } @property (readonly) NSString * homeName; //@synthesize homeName=_homeName - In the implementation block @property (readonly) NSString * setupCode; //@synthesize setupCode=_setupCode - In the implementation block @property (readonly) id setupCodeProvider; //@synthesize setupCodeProvider=_setupCodeProvider - In the implementation block @property (readonly) BOOL requiresUserConsent; //@synthesize requiresUserConsent=_requiresUserConsent - In the implementation block @property (readonly) HMDAccessoryNetworkCredential * networkCredential; //@synthesize networkCredential=_networkCredential - In the implementation block @property (readonly) NSString * isoCountryCode; //@synthesize isoCountryCode=_isoCountryCode - In the implementation block -(NSString *)isoCountryCode; -(NSString *)homeName; -(NSString *)setupCode; -(BOOL)requiresUserConsent; -(id)initWithHomeName:(id)arg1 setupCode:(id)arg2 setupCodeProvider:(/*^block*/id)arg3 requiresUserConsent:(BOOL)arg4 networkCredential:(id)arg5 country:(id)arg6 ; -(HMDAccessoryNetworkCredential *)networkCredential; -(id)setupCodeProvider; @end
<reponame>nspotrepka/ofxPDSP<filename>src/math/simd/core/allocator.h #ifndef OFX_SIMDFLOATS_ALLOCATOR_H_INCLUDED #define OFX_SIMDFLOATS_ALLOCATOR_H_INCLUDED #include <stdlib.h> #include "flags.h" #include "../vectors/vect_ops.h" // allocate array of memory-aligned floats to the given pointers, also set all the floats to zero // set the pointer to nullptr if it can't get the the memory void ofx_allocate_aligned(float* &toAllocate, int len); // free the memory and set the pointer to nullptr void ofx_deallocate_aligned(float* &toDelete ); #endif // OFX_SIMDFLOATS_ALLOCATOR_H_INCLUDED
<reponame>raphaelchang/quadthingy-software<gh_stars>1-10 /* Copyright 2012 <NAME> aka barthess. You may use this work without restrictions, as long as this notice is included. The work is provided "as is" without warranty of any kind, neither express nor implied. */ #ifndef EE25XX_H #define EE25XX_H #include "hal.h" #if defined(HAL_USE_EEPROM) && HAL_USE_EEPROM && EEPROM_USE_EE25XX #define EEPROM_DEV_25XX 25 /** * @extends EepromFileConfig */ typedef struct { _eeprom_file_config_data /** * Driver connected to IC. */ SPIDriver *spip; /** * Config associated with SPI driver. */ const SPIConfig *spicfg; } SPIEepromFileConfig; /** * @brief @p SPIEepromFileStream specific data. */ #define _eeprom_file_stream_data_spi \ _eeprom_file_stream_data /** * @extends EepromFileStream * * @brief EEPROM file stream driver class for SPI device. */ typedef struct { const struct EepromFileStreamVMT *vmt; _eeprom_file_stream_data_spi /* Overwritten parent data member. */ const SPIEepromFileConfig *cfg; } SPIEepromFileStream; /** * Open SPI EEPROM IC as file and return pointer to the file stream object * @note Fucntion allways successfully open file. All checking makes * in read/write functions. */ EepromFileStream *SPIEepromFileOpen(SPIEepromFileStream *efs, const SPIEepromFileConfig *eepcfg, const EepromDevice *eepdev); #define SPIEepromFileOpen(efs, eepcfg, eepdev) \ EepromFileOpen((EepromFileStream *)efs, (EepromFileConfig *)eepcfg, eepdev); #endif /* #if defined(EEPROM_USE_EE25XX) && EEPROM_USE_EE25XX */ #endif // EE25XX_H
<gh_stars>1-10 /* * DroidPwMgmt.h * * Created on: 01 Sep, 2014 * Author: <NAME>, <EMAIL> */ #ifndef DROID_PW_MGMT_ESSENTIALS_H_ #define DROID_PW_MGMT_ESSENTIALS_H_ #define CPU_FILE_GOVERNOR "/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor" #define CPU_FILE_SET_FREQ "/sys/devices/system/cpu/cpu0/cpufreq/scaling_setspeed" #define CPU_FILE_FREQ_INFO "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_cur_freq" #define CPU_FILE_MIN_FREQ "/sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq" #define CPU_FILE_MAX_FREQ "/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq" #define CPU_FILE_VOLTAGE "/sys/bus/i2c/drivers/INA231/4-0040/sensor_V" #define CPU_FILE_CURRENT "/sys/bus/i2c/drivers/INA231/4-0040/sensor_A" #define CPU_FILE_POWER "/sys/bus/i2c/drivers/INA231/4-0040/sensor_W" #define GPU_FILE_CURRENT "/sys/bus/i2c/drivers/INA231/4-0044/sensor_A" #define GPU_FILE_POWER "/sys/bus/i2c/drivers/INA231/4-0044/sensor_W" #define GPU_FILE_SET_MIN_FREQ "/sys/devices/platform/pvrsrvkm.0/sgx_dvfs_min_lock" #define GPU_FILE_SET_MAX_FREQ "/sys/devices/platform/pvrsrvkm.0/sgx_dvfs_max_lock" #define GPU_FILE_FREQ_INFO "/sys/module/pvrsrvkm/parameters/sgx_gpu_clk" #define GPU_FILE_UTILIZATION "/sys/module/pvrsrvkm/parameters/sgx_gpu_utilization" #endif /* DROID_PW_MGMT_ESSENTIALS_H_ */
// Author : XuBenHao // Version : 1.0.0 // Mail : <EMAIL> // Copyright : XuBenHao 2020 - 2030 #ifndef APP_UI_PRATICALARRAYLISTWIDGET_H #define APP_UI_PRATICALARRAYLISTWIDGET_H #include "../header.h" namespace Ui { class PraticalArrayListWidget; } class PraticalArrayListWidget : public QWidget { Q_OBJECT public: explicit PraticalArrayListWidget(QWidget *parent = nullptr); ~PraticalArrayListWidget(); Q_SIGNALS: void ShowDataStruct( const QString& strName_, const QVariant& nVar_); private slots: void Pre(bool checked_); void DeleteArray(bool checked_); void CreateArray(bool checked_); void ListClicked(const QModelIndex& index); private: void Initialize(); private: QStandardItemModel* theModel; private: Ui::PraticalArrayListWidget *ui; }; #endif // PRATICALARRAYLISTWIDGET_H
<reponame>afullstopdot/ft_traceroute<filename>src/icmp/icmpcode.c #include <traceroute.h> /* ** Print a description string corresponding to an ICMP "destination unreachable" error ** ** The IPv4 function is similar, albeit longer, ** as there are more ICMPv4 "destination unreachable" codes */ const char *icmpcode_v4(int code) { static char errbuf[100]; switch (code) { case 0: return (ft_strdup("network unreachable")); case 1: return (ft_strdup("host unreachable")); case 2: return (ft_strdup("protocol unreachable")); case 3: return (ft_strdup("port unreachable")); case 4: return (ft_strdup("fragmentation required but DF bit set")); case 5: return (ft_strdup("source route failed")); case 6: return (ft_strdup("destination network unknown")); case 7: return (ft_strdup("destination host unknown")); case 8: return (ft_strdup("source host isolated (obsolete)")); case 9: return (ft_strdup("destination network administratively prohibited")); case 10: return (ft_strdup("destination host administratively prohibited")); case 11: return (ft_strdup("network unreachable for TOS")); case 12: return (ft_strdup("host unreachable for TOS")); case 13: return (ft_strdup("communication administratively prohibited by filtering")); case 14: return (ft_strdup("host recedence violation")); case 15: return (ft_strdup("precedence cutoff in effect")); default: sprintf(errbuf, "[unknown code %d]", code); return (errbuf); } } const char *icmpcode_v6(int code) { static char errbuf[100]; switch (code) { case ICMP6_DST_UNREACH_NOROUTE: return (ft_strdup("no route to host")); case ICMP6_DST_UNREACH_ADMIN: return (ft_strdup("administratively prohibited")); // case ICMP6_DST_UNREACH_NOTNEIGHBOR: // return (ft_strdup("not a neighbor")); case ICMP6_DST_UNREACH_ADDR: return (ft_strdup("address unreachable")); case ICMP6_DST_UNREACH_NOPORT: return (ft_strdup("port unreachable")); default: sprintf(errbuf, "[unknown code %d]", code); return errbuf; } }
<filename>apache2/re_operators.c /* * ModSecurity for Apache 2.x, http://www.modsecurity.org/ * Copyright (c) 2004-2013 Trustwave Holdings, Inc. (http://www.trustwave.com/) * * 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 * * If any of the files related to licensing are missing or if you have any * other questions related to licensing please contact Trustwave Holdings, Inc. * directly using the email address <EMAIL>. */ #include "re.h" #include "msc_pcre.h" #include "msc_geo.h" #include "msc_gsb.h" #include "apr_lib.h" #include "apr_strmatch.h" #include "acmp.h" #include "msc_util.h" #include "msc_tree.h" #include "msc_crypt.h" #if APR_HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #include "libinjection/libinjection.h" /** * */ void msre_engine_op_register(msre_engine *engine, const char *name, fn_op_param_init_t fn1, fn_op_execute_t fn2) { msre_op_metadata *metadata = (msre_op_metadata *)apr_pcalloc(engine->mp, sizeof(msre_op_metadata)); if (metadata == NULL) return; metadata->name = name; metadata->param_init = fn1; metadata->execute = fn2; apr_table_setn(engine->operators, name, (void *)metadata); } /** * */ msre_op_metadata *msre_engine_op_resolve(msre_engine *engine, const char *name) { return (msre_op_metadata *)apr_table_get(engine->operators, name); } /* -- Operators -- */ /* unconditionalMatch */ static int msre_op_unconditionalmatch_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { *error_msg = "Unconditional match in SecAction."; /* Always match. */ return 1; } /* noMatch */ static int msre_op_nomatch_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { *error_msg = "No match."; /* Never match. */ return 0; } /* ipmatch */ /** * \brief Init function to ipmatch operator * * \param rule ModSecurity rule struct * \param error_msg Error message * * \retval 1 On Success * \retval 0 On Fail */ static int msre_op_ipmatch_param_init(msre_rule *rule, char **error_msg) { char *param = NULL; int res = 0; if (error_msg == NULL) return -1; else *error_msg = NULL; param = apr_pstrdup(rule->ruleset->mp, rule->op_param); res = ip_tree_from_param(rule->ruleset->mp, param, &rule->ip_op, error_msg); if (res) return 0; return 1; } /** * \brief Execution function to ipmatch operator * * \param msr Pointer internal modsec request structure * \param rule Pointer to the rule * \param var Pointer to variable structure * \param error_msg Pointer to error msg * * \retval -1 On Failure * \retval 1 On Match * \retval 0 On No Match */ static int msre_op_ipmatch_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { TreeRoot *rtree = NULL; int res = 0; if (error_msg == NULL) return -1; else *error_msg = NULL; if (rule == NULL || rule->ip_op == NULL) { msr_log(msr, 1, "ipMatch Internal Error: ipmatch value is null."); return 0; } rtree = rule->ip_op; res = tree_contains_ip(msr->mp, rtree, var->value, NULL, error_msg); if (res < 0) { msr_log(msr, 1, "%s", *error_msg); *error_msg = NULL; } if (res > 0) { *error_msg = apr_psprintf(msr->mp, "IPmatch: \"%s\" matched at %s.", var->value, var->name); } return res; } /** * \brief Init function to ipmatchFromFile operator * * \param rule Pointer to the rule * \param error_msg Pointer to error msg * * \retval 1 On Success * \retval 0 On Fail */ static int msre_op_ipmatchFromFile_param_init(msre_rule *rule, char **error_msg) { const char *rootpath = NULL; const char *filepath = NULL; const char *ipfile_path = NULL; char *fn = NULL; int res = 0; TreeRoot *rtree = NULL; if ((rule->op_param == NULL) || (strlen(rule->op_param) == 0)) { *error_msg = apr_psprintf(rule->ruleset->mp, "Missing parameter for " \ "operator 'ipmatchFromFile'."); return 0; } fn = apr_pstrdup(rule->ruleset->mp, rule->op_param); while ((apr_isspace(*fn) != 0) && (*fn != '\0')) { fn++; } if (*fn == '\0') { *error_msg = apr_psprintf(rule->ruleset->mp, "Empty file specification " \ "for operator ipmatchFromFile \"%s\"", fn); return 0; } filepath = fn; ipfile_path = apr_pstrndup(rule->ruleset->mp, rule->filename, strlen(rule->filename) - strlen(apr_filepath_name_get(rule->filename))); if (apr_filepath_root(&rootpath, &filepath, APR_FILEPATH_TRUENAME, rule->ruleset->mp) != APR_SUCCESS) { apr_filepath_merge(&fn, ipfile_path, fn, APR_FILEPATH_TRUENAME, rule->ruleset->mp); } res = ip_tree_from_file(&rtree, fn, rule->ruleset->mp, error_msg); if (res) { return 0; } rule->op_param_data = rtree; return 1; } /** * \brief Execution function to ipmatchFromFile operator * * \param msr Pointer internal modsec request structure * \param rule Pointer to the rule * \param var Pointer to variable structure * \param error_msg Pointer to error msg * * \retval -1 On Failure * \retval 1 On Match * \retval 0 On No Match */ static int msre_op_ipmatchFromFile_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { TreeRoot *rtree = (TreeRoot *)rule->op_param_data; int res = 0; if (error_msg == NULL) return -1; else *error_msg = NULL; if(rtree == NULL) { msr_log(msr, 1, "ipMatchFromFile Internal Error: tree value is null."); return 0; } if (msr->txcfg->debuglog_level >= 4) { msr_log(msr, 4, "IPmatchFromFile: Total tree entries: %d, ipv4 %d " \ "ipv6 %d", rtree->ipv4_tree->count+rtree->ipv6_tree->count, rtree->ipv4_tree->count, rtree->ipv6_tree->count); } res = tree_contains_ip(msr->mp, rtree, var->value, msr, error_msg); if (res < 0) msr_log(msr, 9, "%s", *error_msg); if (res > 0) *error_msg = apr_psprintf(msr->mp, "IPmatchFromFile: \"%s\" matched at " \ "%s.", var->value, var->name); return res; } /* rsub */ static char *param_remove_escape(msre_rule *rule, char *str, int len) { char *parm = apr_pcalloc(rule->ruleset->mp, len); char *ret = parm; for(;*str!='\0';str++) { if(*str != '\\') { *parm++ = *str; } else { str++; if(*str != '/') { str--; *parm++ = *str; } else { *parm++ = *str; } } } *parm = '\0'; return ret; } /** * \brief Init function to rsub operator * * \param rule Pointer to the rule * \param error_msg Pointer to error msg * * \retval 1 On Success * \retval 0 On Fail */ #if !defined(MSC_TEST) static int msre_op_rsub_param_init(msre_rule *rule, char **error_msg) { #if AP_SERVER_MAJORVERSION_NUMBER > 1 && AP_SERVER_MINORVERSION_NUMBER > 0 ap_regex_t *regex; #else regex_t *regex; #endif const char *pattern = NULL; const char *line = NULL; char *reg_pattern = NULL; char *replace = NULL; char *e_pattern = NULL; char *parsed_replace = NULL; char *flags = NULL; char *data = NULL; char delim; int ignore_case = 0; unsigned short int op_len = 0; if (error_msg == NULL) return -1; *error_msg = NULL; line = rule->op_param; if (apr_tolower(*line) != 's') { *error_msg = apr_psprintf(rule->ruleset->mp, "Error rsub operator format, must be s/ pattern"); return -1; } data = apr_pstrdup(rule->ruleset->mp, line); delim = *++data; if (delim) reg_pattern = ++data; if (reg_pattern) { if (*data != delim) { for(;*data != '\0' ;data++) { if(*data == delim) { data--; if(*data == '\\') { data++; continue; } break; } } } if (*data) { *++data = '\0'; ++data; replace = data; } } if (replace) { if (*data != delim) { for(;*data != '\0' ;data++) { if(*data == delim) { data--; if(*data == '\\') { data++; continue; } break; } } } if (*data) { *++data = '\0'; flags = ++data; } } if (!delim || !reg_pattern || !replace) { *error_msg = apr_psprintf(rule->ruleset->mp, "Error rsub operator format - must be s/regex/str/[flags]"); return -1; } op_len = strlen(replace); parsed_replace = apr_pstrdup(rule->ruleset->mp, parse_pm_content(param_remove_escape(rule, replace, strlen(replace)), op_len, rule, error_msg)); if(!parsed_replace) { *error_msg = apr_psprintf(rule->ruleset->mp, "Error rsub operator parsing input data"); return -1; } rule->sub_str = apr_pstrmemdup(rule->ruleset->mp, parsed_replace, strlen(parsed_replace)); if (flags) { while (*flags) { delim = apr_tolower(*flags); if (delim == 'i') ignore_case = 1; else if (delim == 'd') rule->escape_re = 1; else *error_msg = apr_psprintf(rule->ruleset->mp, "Regex flag not supported"); flags++; } } e_pattern = param_remove_escape(rule, reg_pattern, strlen(reg_pattern)); pattern = apr_pstrndup(rule->ruleset->mp, e_pattern, strlen(e_pattern)); if(strstr(pattern,"%{") == NULL) { #if AP_SERVER_MAJORVERSION_NUMBER > 1 && AP_SERVER_MINORVERSION_NUMBER > 0 regex = ap_pregcomp(rule->ruleset->mp, pattern, AP_REG_EXTENDED | (ignore_case ? AP_REG_ICASE : 0)); #else regex = ap_pregcomp(rule->ruleset->mp, pattern, REG_EXTENDED | (ignore_case ? REG_ICASE : 0)); #endif rule->sub_regex = regex; } else { rule->re_precomp = 1; rule->re_str = apr_pstrndup(rule->ruleset->mp, pattern, strlen(pattern)); rule->sub_regex = NULL; } return 1; /* OK */ } /** * \brief Execution function to rsub operator * * \param msr Pointer internal modsec request structure * \param rule Pointer to the rule * \param var Pointer to variable structure * \param error_msg Pointer to error msg * * \retval -1 On Failure * \retval 1 On Match * \retval 0 On No Match */ static int msre_op_rsub_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { msc_string *str = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); msc_string *re_pattern = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); char *offset = NULL; char *data = NULL, *pattern = NULL; char *data_out = NULL; unsigned int size = 0; unsigned int maxsize=0; int output_body = 0, input_body = 0, sl; #if AP_SERVER_MAJORVERSION_NUMBER > 1 && AP_SERVER_MINORVERSION_NUMBER > 0 ap_regmatch_t pmatch[AP_MAX_REG_MATCH]; #else regmatch_t pmatch[AP_MAX_REG_MATCH]; #endif if (error_msg == NULL) return -1; *error_msg = NULL; if(strcmp(var->name,"STREAM_OUTPUT_BODY") == 0 ) { output_body = 1; } else if(strcmp(var->name,"STREAM_INPUT_BODY") == 0 ) { input_body = 1; } else { msr_log(msr,9,"Operator rsub only works with STREAM_* variables"); return -1; } if(rule->re_precomp == 1) { re_pattern->value = apr_pstrndup(msr->mp, rule->re_str, strlen(rule->re_str)); re_pattern->value_len = strlen(re_pattern->value); expand_macros(msr, re_pattern, rule, msr->mp); if(strlen(re_pattern->value) > 0) { if(rule->escape_re == 1) { pattern = log_escape_re(msr->mp, re_pattern->value); if (msr->txcfg->debuglog_level >= 6) { msr_log(msr, 6, "Escaping pattern [%s]",pattern); } #if AP_SERVER_MAJORVERSION_NUMBER > 1 && AP_SERVER_MINORVERSION_NUMBER > 0 rule->sub_regex = ap_pregcomp(msr->mp, pattern, AP_REG_EXTENDED); #else rule->sub_regex = ap_pregcomp(msr->mp, pattern, REG_EXTENDED); #endif } else { #if AP_SERVER_MAJORVERSION_NUMBER > 1 && AP_SERVER_MINORVERSION_NUMBER > 0 rule->sub_regex = ap_pregcomp(msr->mp, re_pattern->value, AP_REG_EXTENDED); #else rule->sub_regex = ap_pregcomp(msr->mp, re_pattern->value, REG_EXTENDED); #endif } } else { rule->sub_regex = NULL; } } if(rule->sub_regex == NULL) { *error_msg = "Internal Error: regex data is null."; return -1; } str->value = apr_pstrndup(msr->mp, rule->sub_str, strlen(rule->sub_str)); str->value_len = strlen(str->value); if(strstr(rule->sub_str,"%{") != NULL) expand_macros(msr, str, rule, msr->mp); maxsize=var->value_len+(AP_MAX_REG_MATCH*1024)+1; nextround: data = apr_pcalloc(msr->mp, maxsize+1); if(data == NULL) { *error_msg = "Internal Error: cannot allocate memory"; return -1; } data_out=data; size=0; for (offset = (char*)var->value; !ap_regexec(rule->sub_regex, offset, AP_MAX_REG_MATCH, pmatch, 0); ) { //Copy of data before the regex match int i; int s = pmatch [0].rm_so; int p_len=pmatch [0].rm_eo - pmatch [0].rm_so; if (size+s>maxsize) { maxsize*=2; goto nextround; } memcpy(data_out,offset,s); data_out+=s; size+=s; //Copy of regex match with replacing data \1..\9 for(i=0;i<str->value_len;) { char *x = str->value+i; if (*x == '\\' && *(x + 1) > '0' && *(x + 1) <= '9') { int capture=*(x + 1) - 48; int capture_len=pmatch[capture].rm_eo-pmatch[capture].rm_so; if (size+capture_len>maxsize) { maxsize*=2; goto nextround; } memcpy(data_out,offset+pmatch[capture].rm_so,capture_len); data_out+= capture_len; size+=capture_len; i+=2; } else { if (size+1>maxsize) { maxsize*=2; goto nextround; } *data_out=*(str->value+i); data_out++; size++; i++; } } offset+=s; offset+=p_len; } //Copy of data after the last regex match sl = strlen(offset); if (size+sl>maxsize) { maxsize*=2; goto nextround; } memcpy(data_out,offset,sl); data_out+=sl; size+=sl; *data_out=0; if(msr->stream_output_data != NULL && output_body == 1) { memset(msr->stream_output_data, 0x0, msr->stream_output_length); free(msr->stream_output_data); msr->stream_output_data = NULL; msr->stream_output_length = 0; msr->stream_output_data = (char *)malloc(size+1); if(msr->stream_output_data == NULL) { return -1; } msr->stream_output_length = size; memset(msr->stream_output_data, 0x0, size+1); msr->of_stream_changed = 1; memcpy(msr->stream_output_data, data, size); msr->stream_output_data[size] = '\0'; var->value_len = size; var->value = msr->stream_output_data; } if(msr->stream_input_data != NULL && input_body == 1) { memset(msr->stream_input_data, 0x0, msr->stream_input_length); free(msr->stream_input_data); msr->stream_input_data = NULL; msr->stream_input_length = 0; msr->stream_input_data = (char *)malloc(size+1); if(msr->stream_input_data == NULL) { return -1; } msr->stream_input_length = size; memset(msr->stream_input_data, 0x0, size+1); msr->if_stream_changed = 1; memcpy(msr->stream_input_data, data, size); msr->stream_input_data[size] = '\0'; var->value_len = size; var->value = msr->stream_input_data; } if (! *error_msg) { *error_msg = apr_psprintf(msr->mp, "Operator rsub succeeded."); } return 1; } #endif /* MSC_TEST */ /** * \brief Init function to validateHash * * \param rule ModSecurity rule struct * \param error_msg Error message * * \retval 1 On success * \retval 0 On fail */ static int msre_op_validateHash_param_init(msre_rule *rule, char **error_msg) { const char *errptr = NULL; int erroffset; msc_regex_t *regex; const char *pattern = rule->op_param; #ifdef WITH_PCRE_STUDY #ifdef WITH_PCRE_JIT int rc, jit; #endif #endif if (error_msg == NULL) return -1; *error_msg = NULL; /* Compile pattern */ if(strstr(pattern,"%{") == NULL) { regex = msc_pregcomp_ex(rule->ruleset->mp, pattern, PCRE_DOTALL | PCRE_DOLLAR_ENDONLY, &errptr, &erroffset, msc_pcre_match_limit, msc_pcre_match_limit_recursion); if (regex == NULL) { *error_msg = apr_psprintf(rule->ruleset->mp, "Error compiling pattern (offset %d): %s", erroffset, errptr); return 0; } #ifdef WITH_PCRE_STUDY #ifdef WITH_PCRE_JIT rc = msc_fullinfo(regex, PCRE_INFO_JIT, &jit); if ((rc != 0) || (jit != 1)) { *error_msg = apr_psprintf(rule->ruleset->mp, "Rule %pp [id \"%s\"][file \"%s\"][line \"%d\"] - " "Execution error - " "Does not support JIT (%d)", rule,((rule->actionset != NULL)&&((rule->actionset->id != NULL)&& (rule->actionset->id != NOT_SET_P))) ? rule->actionset->id : "-", rule->filename != NULL ? rule->filename : "-", rule->line_num,rc); } #endif #endif rule->op_param_data = regex; } else { rule->re_precomp = 1; rule->re_str = apr_pstrndup(rule->ruleset->mp, pattern, strlen(pattern)); rule->op_param_data = NULL; } return 1; /* OK */ } /** * \brief Execute function to validateHash * * \param msr ModSecurity transaction resource * \param rule ModSecurity rule struct * \param var ModSecurity variable struct * \param error_msg Error message * * \retval 1 On success * \retval 0 On fail */ static int msre_op_validateHash_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { msc_regex_t *regex = (msc_regex_t *)rule->op_param_data; msc_string *re_pattern = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); const char *target; const char *errptr = NULL; int erroffset; unsigned int target_length; char *my_error_msg = NULL; int ovector[33]; int rc; const char *pattern = NULL; #ifdef WITH_PCRE_STUDY #ifdef WITH_PCRE_JIT int jit; #endif #endif if (error_msg == NULL) return -1; *error_msg = NULL; if (msr->txcfg->hash_enforcement == HASH_DISABLED || msr->txcfg->hash_is_enabled == HASH_DISABLED) return 0; if (regex == NULL) { if(rule->re_precomp == 0) { *error_msg = "Internal Error: regex data is null."; return -1; } else { if(re_pattern == NULL) { *error_msg = "Internal Error: regex variable data is null."; return -1; } re_pattern->value = apr_pstrndup(msr->mp, rule->re_str, strlen(rule->re_str)); re_pattern->value_len = strlen(re_pattern->value); expand_macros(msr, re_pattern, rule, msr->mp); pattern = log_escape_re(msr->mp, re_pattern->value); if (msr->txcfg->debuglog_level >= 6) { msr_log(msr, 6, "Escaping pattern [%s]",pattern); } regex = msc_pregcomp_ex(rule->ruleset->mp, pattern, PCRE_DOTALL | PCRE_DOLLAR_ENDONLY, &errptr, &erroffset, msc_pcre_match_limit, msc_pcre_match_limit_recursion); if (regex == NULL) { *error_msg = apr_psprintf(rule->ruleset->mp, "Error compiling pattern (offset %d): %s", erroffset, errptr); return 0; } #ifdef WITH_PCRE_STUDY #ifdef WITH_PCRE_JIT if (msr->txcfg->debuglog_level >= 4) { rc = msc_fullinfo(regex, PCRE_INFO_JIT, &jit); if ((rc != 0) || (jit != 1)) { *error_msg = apr_psprintf(rule->ruleset->mp, "Rule %pp [id \"%s\"][file \"%s\"][line \"%d\"] - " "Execution error - " "Does not support JIT (%d)", rule,((rule->actionset != NULL)&&((rule->actionset->id != NULL)&& (rule->actionset->id != NOT_SET_P))) ? rule->actionset->id : "-", rule->filename != NULL ? rule->filename : "-", rule->line_num,rc); msr_log(msr, 4, "%s.", *error_msg); } } #endif #endif } } /* If the given target is null run against an empty * string. This is a behaviour consistent with previous * releases. */ if (var->value == NULL) { target = ""; target_length = 0; } else { target = var->value; target_length = var->value_len; } /* We always use capture so that ovector can be used as working space * and no memory has to be allocated for any backreferences. */ rc = msc_regexec_capture(regex, target, target_length, ovector, 30, &my_error_msg); if ((rc == PCRE_ERROR_MATCHLIMIT) || (rc == PCRE_ERROR_RECURSIONLIMIT)) { msc_string *s = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); if (s == NULL) return -1; s->name = apr_pstrdup(msr->mp, "MSC_PCRE_LIMITS_EXCEEDED"); if (s->name == NULL) return -1; s->name_len = strlen(s->name); s->value = apr_pstrdup(msr->mp, "1"); if (s->value == NULL) return -1; s->value_len = 1; apr_table_setn(msr->tx_vars, s->name, (void *)s); *error_msg = apr_psprintf(msr->mp, "Rule %pp [id \"%s\"][file \"%s\"][line \"%d\"] - " "Execution error - " "PCRE limits exceeded (%d): %s", rule,((rule->actionset != NULL)&&(rule->actionset->id != NULL)) ? rule->actionset->id : "-", rule->filename != NULL ? rule->filename : "-", rule->line_num,rc, my_error_msg); msr_log(msr, 3, "%s.", *error_msg); return 0; /* No match. */ } else if (rc < -1) { *error_msg = apr_psprintf(msr->mp, "Regex execution failed (%d): %s", rc, my_error_msg); return -1; } if (rc != PCRE_ERROR_NOMATCH) { /* Match. */ /* We no longer escape the pattern here as it is done when logging */ char *pattern = apr_pstrdup(msr->mp, log_escape(msr->mp, regex->pattern ? regex->pattern : "<Unknown Match>")); char *hmac = NULL, *valid = NULL; char *hash_link = NULL, *nlink = NULL; if (strlen(pattern) > 252) { *error_msg = apr_psprintf(msr->mp, "Request URI matched \"%.252s ...\" at %s.", pattern, var->name); } else { *error_msg = apr_psprintf(msr->mp, "Request URI matched \"%s\" at %s.", pattern, var->name); } valid = strstr(target, msr->txcfg->crypto_param_name); if(valid == NULL) { if (msr->txcfg->debuglog_level >= 9) msr_log(msr, 9, "Request URI without hash parameter [%s]", target); if (strlen(pattern) > 252) { *error_msg = apr_psprintf(msr->mp, "Request URI matched \"%.252s ...\" at %s. No Hash parameter", pattern, var->name); } else { *error_msg = apr_psprintf(msr->mp, "Request URI matched \"%s\" at %s. No Hash parameter", pattern, var->name); } return 1; } else { if(strlen(valid) < strlen(msr->txcfg->crypto_param_name)+1) return 1; hmac = valid+strlen(msr->txcfg->crypto_param_name)+1; nlink = apr_pstrmemdup(msr->mp, target, strlen(target) - strlen(valid) - 1); msr_log(msr, 9, "Validating URI %s size %zu",nlink,strlen(nlink)); hash_link = do_hash_link(msr, (char *)nlink, HASH_ONLY); if(strcmp(hmac, hash_link) != 0) { if (strlen(pattern) > 252) { *error_msg = apr_psprintf(msr->mp, "Request URI matched \"%.252s ...\" at %s. Hash parameter hash value = [%s] Requested URI hash value = [%s]", pattern, var->name, hmac, hash_link); } else { *error_msg = apr_psprintf(msr->mp, "Request URI matched \"%s\" at %s. Hash parameter hash value = [%s] Requested URI hash value = [%s]", pattern, var->name, hmac, hash_link); } return 1; } } return 0; } return 0; } /* rx */ static int msre_op_rx_param_init(msre_rule *rule, char **error_msg) { const char *errptr = NULL; int erroffset; msc_regex_t *regex; const char *pattern = rule->op_param; #ifdef WITH_PCRE_STUDY #ifdef WITH_PCRE_JIT int rc, jit; #endif #endif if (error_msg == NULL) return -1; *error_msg = NULL; /* Compile pattern */ if(strstr(pattern,"%{") == NULL) { regex = msc_pregcomp_ex(rule->ruleset->mp, pattern, PCRE_DOTALL | PCRE_DOLLAR_ENDONLY, &errptr, &erroffset, msc_pcre_match_limit, msc_pcre_match_limit_recursion); if (regex == NULL) { *error_msg = apr_psprintf(rule->ruleset->mp, "Error compiling pattern (offset %d): %s", erroffset, errptr); return 0; } #ifdef WITH_PCRE_STUDY #ifdef WITH_PCRE_JIT rc = msc_fullinfo(regex, PCRE_INFO_JIT, &jit); if ((rc != 0) || (jit != 1)) { *error_msg = apr_psprintf(rule->ruleset->mp, "Rule %pp [id \"%s\"][file \"%s\"][line \"%d\"] - " "Execution error - " "Does not support JIT (%d)", rule,((rule->actionset != NULL)&&((rule->actionset->id != NULL)&& (rule->actionset->id != NOT_SET_P))) ? rule->actionset->id : "-", rule->filename != NULL ? rule->filename : "-", rule->line_num,rc); } #endif #endif rule->op_param_data = regex; } else { rule->re_precomp = 1; rule->re_str = apr_pstrndup(rule->ruleset->mp, pattern, strlen(pattern)); rule->op_param_data = NULL; } return 1; /* OK */ } static int msre_op_rx_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { msc_regex_t *regex = (msc_regex_t *)rule->op_param_data; msc_string *re_pattern = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); const char *target; const char *errptr = NULL; int erroffset; unsigned int target_length; char *my_error_msg = NULL; int ovector[33]; int capture = 0; int matched_bytes = 0; int matched = 0; int rc; char *qspos = NULL; const char *parm = NULL, *pattern = NULL; msc_parm *mparm = NULL; #ifdef WITH_PCRE_STUDY #ifdef WITH_PCRE_JIT int jit; #endif #endif if (error_msg == NULL) return -1; *error_msg = NULL; if (regex == NULL) { if(rule->re_precomp == 0) { *error_msg = "Internal Error: regex data is null."; return -1; } else { if(re_pattern == NULL) { *error_msg = "Internal Error: regex variable data is null."; return -1; } re_pattern->value = apr_pstrndup(msr->mp, rule->re_str, strlen(rule->re_str)); re_pattern->value_len = strlen(re_pattern->value); expand_macros(msr, re_pattern, rule, msr->mp); pattern = log_escape_re(msr->mp, re_pattern->value); if (msr->txcfg->debuglog_level >= 6) { msr_log(msr, 6, "Escaping pattern [%s]",pattern); } regex = msc_pregcomp_ex(rule->ruleset->mp, pattern, PCRE_DOTALL | PCRE_DOLLAR_ENDONLY, &errptr, &erroffset, msc_pcre_match_limit, msc_pcre_match_limit_recursion); if (regex == NULL) { *error_msg = apr_psprintf(rule->ruleset->mp, "Error compiling pattern (offset %d): %s", erroffset, errptr); return 0; } #ifdef WITH_PCRE_STUDY #ifdef WITH_PCRE_JIT if (msr->txcfg->debuglog_level >= 4) { rc = msc_fullinfo(regex, PCRE_INFO_JIT, &jit); if ((rc != 0) || (jit != 1)) { *error_msg = apr_psprintf(rule->ruleset->mp, "Rule %pp [id \"%s\"][file \"%s\"][line \"%d\"] - " "Execution error - " "Does not support JIT (%d)", rule,((rule->actionset != NULL)&&((rule->actionset->id != NULL)&& (rule->actionset->id != NOT_SET_P))) ? rule->actionset->id : "-", rule->filename != NULL ? rule->filename : "-", rule->line_num,rc); msr_log(msr, 4, "%s.", *error_msg); } } #endif #endif } } /* If the given target is null run against an empty * string. This is a behaviour consistent with previous * releases. */ if (var->value == NULL) { target = ""; target_length = 0; } else { target = var->value; target_length = var->value_len; } /* Are we supposed to capture subexpressions? */ capture = apr_table_get(rule->actionset->actions, "capture") ? 1 : 0; matched_bytes = apr_table_get(rule->actionset->actions, "sanitizeMatchedBytes") ? 1 : 0; if(!matched_bytes) matched_bytes = apr_table_get(rule->actionset->actions, "sanitiseMatchedBytes") ? 1 : 0; matched = apr_table_get(rule->actionset->actions, "sanitizeMatched") ? 1 : 0; if(!matched) matched = apr_table_get(rule->actionset->actions, "sanitiseMatched") ? 1 : 0; /* Show when the regex captures but "capture" is not set */ if (msr->txcfg->debuglog_level >= 6) { int capcount = 0; rc = msc_fullinfo(regex, PCRE_INFO_CAPTURECOUNT, &capcount); if (msr->txcfg->debuglog_level >= 6) { if ((capture == 0) && (capcount > 0)) { msr_log(msr, 6, "Ignoring regex captures since \"capture\" action is not enabled."); } } } /* We always use capture so that ovector can be used as working space * and no memory has to be allocated for any backreferences. */ rc = msc_regexec_capture(regex, target, target_length, ovector, 30, &my_error_msg); if ((rc == PCRE_ERROR_MATCHLIMIT) || (rc == PCRE_ERROR_RECURSIONLIMIT)) { msc_string *s = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); if (s == NULL) return -1; s->name = apr_pstrdup(msr->mp, "MSC_PCRE_LIMITS_EXCEEDED"); if (s->name == NULL) return -1; s->name_len = strlen(s->name); s->value = apr_pstrdup(msr->mp, "1"); if (s->value == NULL) return -1; s->value_len = 1; apr_table_setn(msr->tx_vars, s->name, (void *)s); *error_msg = apr_psprintf(msr->mp, "Rule %pp [id \"%s\"][file \"%s\"][line \"%d\"] - " "Execution error - " "PCRE limits exceeded (%d): %s", rule,((rule->actionset != NULL)&&(rule->actionset->id != NULL)) ? rule->actionset->id : "-", rule->filename != NULL ? rule->filename : "-", rule->line_num,rc, my_error_msg); msr_log(msr, 3, "%s.", *error_msg); return 0; /* No match. */ } else if (rc < -1) { *error_msg = apr_psprintf(msr->mp, "Regex execution failed (%d): %s", rc, my_error_msg); return -1; } /* Handle captured subexpressions. */ if (capture && rc > 0) { int i; /* Unset any of the previously set capture variables. */ apr_table_unset(msr->tx_vars, "0"); apr_table_unset(msr->tx_vars, "1"); apr_table_unset(msr->tx_vars, "2"); apr_table_unset(msr->tx_vars, "3"); apr_table_unset(msr->tx_vars, "4"); apr_table_unset(msr->tx_vars, "5"); apr_table_unset(msr->tx_vars, "6"); apr_table_unset(msr->tx_vars, "7"); apr_table_unset(msr->tx_vars, "8"); apr_table_unset(msr->tx_vars, "9"); /* Use the available captures. */ for(i = 0; i < rc; i++) { msc_string *s = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); if (s == NULL) return -1; s->name = apr_psprintf(msr->mp, "%d", i); if (s->name == NULL) return -1; s->name_len = strlen(s->name); s->value = apr_pstrmemdup(msr->mp, target + ovector[2 * i], ovector[2 * i + 1] - ovector[2 * i]); if (s->value == NULL) return -1; s->value_len = (ovector[2 * i + 1] - ovector[2 * i]); apr_table_addn(msr->tx_vars, s->name, (void *)s); if(((matched == 1) || (matched_bytes == 1)) && (var != NULL) && (var->name != NULL)) { qspos = apr_psprintf(msr->mp, "%s", var->name); parm = strstr(qspos, ":"); if (parm != NULL) { parm++; mparm = apr_palloc(msr->mp, sizeof(msc_parm)); if (mparm == NULL) continue; mparm->value = apr_pstrmemdup(msr->mp,s->value,s->value_len); mparm->pad_1 = rule->actionset->arg_min; mparm->pad_2 = rule->actionset->arg_max; apr_table_addn(msr->pattern_to_sanitize, parm, (void *)mparm); } else { mparm = apr_palloc(msr->mp, sizeof(msc_parm)); if (mparm == NULL) continue; mparm->value = apr_pstrmemdup(msr->mp,s->value,s->value_len); apr_table_addn(msr->pattern_to_sanitize, qspos, (void *)mparm); } } if (msr->txcfg->debuglog_level >= 9) { msr_log(msr, 9, "Added regex subexpression to TX.%d: %s", i, log_escape_nq_ex(msr->mp, s->value, s->value_len)); } } } if (rc != PCRE_ERROR_NOMATCH) { /* Match. */ /* We no longer escape the pattern here as it is done when logging */ char *pattern = apr_pstrdup(msr->mp, log_escape(msr->mp, regex->pattern ? regex->pattern : "<Unknown Match>")); /* This message will be logged. */ if (strlen(pattern) > 252) { *error_msg = apr_psprintf(msr->mp, "Pattern match \"%.252s ...\" at %s.", pattern, var->name); } else { *error_msg = apr_psprintf(msr->mp, "Pattern match \"%s\" at %s.", pattern, var->name); } return 1; } /* No match. */ return 0; } /* pm */ static int msre_op_pm_param_init(msre_rule *rule, char **error_msg) { ACMP *p; const char *phrase; const char *next; unsigned short int op_len; if ((rule->op_param == NULL)||(strlen(rule->op_param) == 0)) { *error_msg = apr_psprintf(rule->ruleset->mp, "Missing parameter for operator 'pm'."); return 0; /* ERROR */ } op_len = strlen(rule->op_param); p = acmp_create(0, rule->ruleset->mp); if (p == NULL) return 0; phrase = apr_pstrdup(rule->ruleset->mp, parse_pm_content(rule->op_param, op_len, rule, error_msg)); if(phrase == NULL) phrase = apr_pstrdup(rule->ruleset->mp, rule->op_param); /* Loop through phrases */ /* ENH: Need to allow quoted phrases w/space */ for (;;) { while((apr_isspace(*phrase) != 0) && (*phrase != '\0')) phrase++; if (*phrase == '\0') break; next = phrase; while((apr_isspace(*next) == 0) && (*next != 0)) next++; acmp_add_pattern(p, phrase, NULL, NULL, next - phrase); phrase = next; } acmp_prepare(p); rule->op_param_data = p; return 1; } /* pmFromFile */ static int msre_op_pmFromFile_param_init(msre_rule *rule, char **error_msg) { char errstr[1024]; char buf[HUGE_STRING_LEN + 1]; char *fn = NULL; char *next = NULL; char *start = NULL; char *end = NULL; const char *rulefile_path; char *processed = NULL; unsigned short int op_len; apr_status_t rc; apr_file_t *fd = NULL; ACMP *p; if ((rule->op_param == NULL)||(strlen(rule->op_param) == 0)) { *error_msg = apr_psprintf(rule->ruleset->mp, "Missing parameter for operator 'pmFromFile'."); return 0; /* ERROR */ } p = acmp_create(0, rule->ruleset->mp); if (p == NULL) return 0; fn = apr_pstrdup(rule->ruleset->mp, rule->op_param); /* Get the path of the rule filename to use as a base */ rulefile_path = apr_pstrndup(rule->ruleset->mp, rule->filename, strlen(rule->filename) - strlen(apr_filepath_name_get(rule->filename))); #ifdef DEBUG_CONF fprintf(stderr, "Rulefile path: \"%s\"\n", rulefile_path); #endif /* Loop through filenames */ /* ENH: Need to allow quoted filenames w/space */ for (;;) { const char *rootpath = NULL; const char *filepath = NULL; int line = 0; /* Trim whitespace */ while((apr_isspace(*fn) != 0) && (*fn != '\0')) fn++; if (*fn == '\0') break; next = fn; while((apr_isspace(*next) == 0) && (*next != '\0')) next++; while((apr_isspace(*next) != 0) && (*next != '\0')) *(next++) = '\0'; /* Add path of the rule filename for a relative phrase filename */ filepath = fn; if (apr_filepath_root(&rootpath, &filepath, APR_FILEPATH_TRUENAME, rule->ruleset->mp) != APR_SUCCESS) { /* We are not an absolute path. It could mean an error, but * let that pass through to the open call for a better error */ apr_filepath_merge(&fn, rulefile_path, fn, APR_FILEPATH_TRUENAME, rule->ruleset->mp); } /* Open file and read */ rc = apr_file_open(&fd, fn, APR_READ | APR_BUFFERED | APR_FILE_NOCLEANUP, 0, rule->ruleset->mp); if (rc != APR_SUCCESS) { *error_msg = apr_psprintf(rule->ruleset->mp, "Could not open phrase file \"%s\": %s", fn, apr_strerror(rc, errstr, 1024)); return 0; } #ifdef DEBUG_CONF fprintf(stderr, "Loading phrase file: \"%s\"\n", fn); #endif /* Read one pattern per line skipping empty/commented */ for(;;) { line++; rc = apr_file_gets(buf, HUGE_STRING_LEN, fd); if (rc == APR_EOF) break; if (rc != APR_SUCCESS) { *error_msg = apr_psprintf(rule->ruleset->mp, "Could not read \"%s\" line %d: %s", fn, line, apr_strerror(rc, errstr, 1024)); return 0; } op_len = strlen(buf); processed = apr_pstrdup(rule->ruleset->mp, parse_pm_content(buf, op_len, rule, error_msg)); /* Trim Whitespace */ if(processed != NULL) start = processed; else start = buf; while ((apr_isspace(*start) != 0) && (*start != '\0')) start++; if(processed != NULL) end = processed + strlen(processed); else end = buf + strlen(buf); if (end > start) end--; while ((end > start) && (apr_isspace(*end) != 0)) end--; if (end > start) { *(++end) = '\0'; } /* Ignore empty lines and comments */ if ((start == end) || (*start == '#')) continue; acmp_add_pattern(p, start, NULL, NULL, (end - start)); } fn = next; } if (fd != NULL) apr_file_close(fd); acmp_prepare(p); rule->op_param_data = p; return 1; } static int msre_op_pm_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { const char *match = NULL; apr_status_t rc = 0; int capture; ACMPT pt; /* Nothing to read */ if ((var->value == NULL) || (var->value_len == 0)) return 0; /* Are we supposed to capture subexpressions? */ capture = apr_table_get(rule->actionset->actions, "capture") ? 1 : 0; pt.parser = (ACMP *)rule->op_param_data; pt.ptr = NULL; rc = acmp_process_quick(&pt, &match, var->value, var->value_len); if (rc) { char *match_escaped = log_escape(msr->mp, match ? match : "<Unknown Match>"); /* This message will be logged. */ if (strlen(match_escaped) > 252) { *error_msg = apr_psprintf(msr->mp, "Matched phrase \"%.252s ...\" at %s.", match_escaped, var->name); } else { *error_msg = apr_psprintf(msr->mp, "Matched phrase \"%s\" at %s.", match_escaped, var->name); } /* Handle capture as tx.0=match */ if (capture) { int i; msc_string *s = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); if (s == NULL) return -1; s->name = "0"; s->name_len = strlen(s->name); s->value = apr_pstrdup(msr->mp, match); if (s->value == NULL) return -1; s->value_len = strlen(s->value); apr_table_setn(msr->tx_vars, s->name, (void *)s); if (msr->txcfg->debuglog_level >= 9) { msr_log(msr, 9, "Added phrase match to TX.0: %s", log_escape_nq_ex(msr->mp, s->value, s->value_len)); } /* Unset the remaining ones (from previous invocations). */ for(i = rc; i <= 9; i++) { char buf[2]; apr_snprintf(buf, sizeof(buf), "%d", i); apr_table_unset(msr->tx_vars, buf); } } return 1; } return rc; } /* gsbLookup */ /** * \brief Reduce /./ to / * * \param pool Pointer to the memory pool * \param domain Input data * * \retval domain On Failure * \retval url On Success */ static const char *gsb_replace_tpath(apr_pool_t *pool, const char *domain, int len) { char *pos = NULL, *data = NULL; char *url = NULL; int match = 0; url = apr_palloc(pool, len + 1); data = apr_palloc(pool, len + 1); memset(data, 0, len+1); memset(url, 0, len+1); memcpy(url, domain, len); while(( pos = strstr(url , "/./" )) != NULL) { match = 1; data[0] = '\0'; strncat(data, url, pos - url); strcat(data , "/"); strcat(data ,pos + strlen("/./")); strncpy(url , data, len); } if(match == 0) return domain; return url; } /** * \brief Reduce double dot to single dot * * \param msr ModSecurity transation resource * \param domain Input data * * \retval domain On Failure * \retval reduced On Success */ static const char *gsb_reduce_char(apr_pool_t *pool, const char *domain) { char *ptr = apr_pstrdup(pool, domain); char *data = NULL; char *reduced = NULL; int skip = 0; if(ptr == NULL) return domain; data = apr_pcalloc(pool, strlen(ptr)); if(data == NULL) return domain; reduced = data; while(*ptr != '\0') { switch(*ptr) { case '.': ptr++; if(*ptr == '.') skip = 1; ptr--; break; case '/': ptr++; if(*ptr == '/') skip = 1; ptr--; break; } if(skip == 0) { *data = *ptr; data++; } ptr++; skip = 0; } *data = '\0'; --data; if(*data == '.') *data = '\0'; else ++data; return reduced; } /** * \brief Verify function to gsbLookup operator * * \param msr ModSecurity transaction resource * \param match Pointer to input data * \param match_length Input size * * \retval -1 On Failure * \retval 1 On Match * \retval 0 On No Match */ static int verify_gsb(gsb_db *gsb, modsec_rec *msr, const char *match, unsigned int match_length) { apr_md5_ctx_t ctx; apr_status_t rc; unsigned char digest[APR_MD5_DIGESTSIZE]; const char *hash = NULL; const char *search = NULL; memset(digest, 0, sizeof(digest)); apr_md5_init(&ctx); if ((rc = apr_md5_update(&ctx, match, match_length)) != APR_SUCCESS) return -1; apr_md5_final(digest, &ctx); hash = apr_psprintf(msr->mp, "%s", bytes2hex(msr->mp, digest, 16)); if ((hash != NULL) && (gsb->gsb_table != NULL)) { search = apr_hash_get(gsb->gsb_table, hash, APR_HASH_KEY_STRING); if (search != NULL) return 1; } return 0; } /** * \brief Init function to gsbLookup operator * * \param rule ModSecurity rule struct * \param error_msg Error message * * \retval 1 On Success * \retval 0 On Fail */ static int msre_op_gsbLookup_param_init(msre_rule *rule, char **error_msg) { const char *errptr = NULL; int erroffset; msc_regex_t *regex; if (error_msg == NULL) return -1; *error_msg = NULL; /* Compile rule->op_param */ regex = msc_pregcomp_ex(rule->ruleset->mp, rule->op_param, PCRE_DOTALL | PCRE_MULTILINE, &errptr, &erroffset, msc_pcre_match_limit, msc_pcre_match_limit_recursion); if (regex == NULL) { *error_msg = apr_psprintf(rule->ruleset->mp, "Error compiling pattern (offset %d): %s", erroffset, errptr); return 0; } rule->op_param_data = regex; return 1; /* OK */ } /** * \brief Execution function to gsbLookup operator * * \param msr ModSecurity transaction resource * \param rule ModSecurity rule struct * \param var ModSecurity variable struct * \param error_msg Error message * * \retval -1 On Failure * \retval 1 On Match * \retval 0 On No Match */ static int msre_op_gsbLookup_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { msc_regex_t *regex = (msc_regex_t *)rule->op_param_data; char *my_error_msg = NULL; int ovector[33]; unsigned int offset = 0; gsb_db *gsb = msr->txcfg->gsb; const char *match = NULL; unsigned int match_length; unsigned int canon_length; int rv, i, ret, count_slash; unsigned int j = 0; unsigned int size = var->value_len; char *base = NULL, *domain = NULL, *savedptr = NULL; char *str = NULL, *canon = NULL, *dot = NULL; char *data = NULL, *ptr = NULL, *url = NULL; int capture, domain_len; int d_pos = -1; int s_pos = -1; if (error_msg == NULL) return -1; *error_msg = NULL; if(regex == NULL) { *error_msg = "Internal Error: regex is null."; return 0; } if(gsb == NULL) { msr_log(msr, 1, "GSB lookup failed without a database. Set SecGsbLookupDB."); return 0; } data = apr_pcalloc(rule->ruleset->mp, var->value_len+1); if(data == NULL) { *error_msg = "Internal Error: cannot allocate memory for data."; return -1; } capture = apr_table_get(rule->actionset->actions, "capture") ? 1 : 0; memcpy(data,var->value,var->value_len); while (offset < size && (rv = msc_regexec_ex(regex, data, size, offset, PCRE_NOTEMPTY, ovector, 30, &my_error_msg)) >= 0) { for(i = 0; i < rv; ++i) { match = apr_psprintf(rule->ruleset->mp, "%.*s", ovector[2*i+1] - ovector[2*i], data + ovector[2*i]); if (match == NULL) { *error_msg = "Internal Error: cannot allocate memory for match."; return -1; } match = remove_escape(rule->ruleset->mp, match, strlen(match)); match = gsb_replace_tpath(rule->ruleset->mp, match, strlen(match)); match = gsb_reduce_char(rule->ruleset->mp, match); match_length = strlen(match); strtolower_inplace((unsigned char *)match); if((strstr(match,"http") == NULL) && (match_length > 0) && (strchr(match,'.'))) { /* full url */ if (msr->txcfg->debuglog_level >= 4) { msr_log(msr, 4, "GSB: Successfully extracted url: %s", match); } ret = verify_gsb(gsb, msr, match, match_length); if(ret > 0) { set_match_to_tx(msr, capture, match, 0); if (! *error_msg) { *error_msg = apr_psprintf(msr->mp, "Gsb lookup for \"%s\" succeeded.", log_escape_nq(msr->mp, match)); } str = apr_pstrdup(rule->ruleset->mp,match); base = apr_strtok(str,"/",&savedptr); if(base != NULL) set_match_to_tx(msr, capture, base, 1); return 1; } /* append / in the end of full url */ if ((match[match_length -1] != '/') && (strchr(match,'?') == NULL)) { canon = apr_psprintf(rule->ruleset->mp, "%s/", match); if (canon != NULL) { canon_length = strlen(canon); ret = verify_gsb(gsb, msr, canon, canon_length); if(ret > 0) { set_match_to_tx(msr, capture, match, 0); if (! *error_msg) { *error_msg = apr_psprintf(msr->mp, "Gsb lookup for \"%s\" succeeded.", log_escape_nq(msr->mp, canon)); } str = apr_pstrdup(rule->ruleset->mp,match); base = apr_strtok(str,"/",&savedptr); if(base != NULL) set_match_to_tx(msr, capture, base, 1); return 1; } } } /* Parsing full url */ domain = apr_pstrdup(rule->ruleset->mp, match); domain_len = strlen(domain); if(*domain != '/') { if(domain[domain_len-1] == '.') domain[domain_len-1] = '\0'; if(domain[domain_len-1] == '/' && domain[domain_len-2] == '.') { domain[domain_len-2] = '/'; domain[domain_len-1] = '\0'; } dot = strchr(domain,'.'); if(dot != NULL) { canon = apr_pstrdup(rule->ruleset->mp, domain); ret = verify_gsb(gsb, msr, canon, strlen(canon)); if(ret > 0) { set_match_to_tx(msr, capture, canon, 0); if (! *error_msg) { *error_msg = apr_psprintf(msr->mp, "Gsb lookup for \"%s\" succeeded.", log_escape_nq(msr->mp, canon)); } str = apr_pstrdup(rule->ruleset->mp,match); base = apr_strtok(str,"/",&savedptr); if(base != NULL) set_match_to_tx(msr, capture, base, 1); return 1; } base = apr_strtok(canon,"?",&savedptr); if(base != NULL) { ret = verify_gsb(gsb, msr, base, strlen(base)); if(ret > 0) { set_match_to_tx(msr, capture, base, 0); if (! *error_msg) { *error_msg = apr_psprintf(msr->mp, "Gsb lookup for \"%s\" succeeded.", log_escape_nq(msr->mp, base)); } str = apr_pstrdup(rule->ruleset->mp,match); base = apr_strtok(str,"/",&savedptr); if(base != NULL) set_match_to_tx(msr, capture, base, 1); return 1; } } url = apr_palloc(rule->ruleset->mp, strlen(canon)); count_slash = 0; while(*canon != '\0') { switch (*canon) { case '/': ptr = apr_psprintf(rule->ruleset->mp,"%s/",url); ret = verify_gsb(gsb, msr, ptr, strlen(ptr)); if(ret > 0) { set_match_to_tx(msr, capture, ptr, 0); if (! *error_msg) { *error_msg = apr_psprintf(msr->mp, "Gsb lookup for \"%s\" succeeded.", log_escape_nq(msr->mp, ptr)); } str = apr_pstrdup(rule->ruleset->mp,match); base = apr_strtok(str,"/",&savedptr); if(base != NULL) set_match_to_tx(msr, capture, base, 1); return 1; } break; } url[count_slash] = *canon; count_slash++; canon++; } } } /* Do the same for subdomains */ for(j=0; j<strlen(match); j++) { if(match[j] == '/') { s_pos = j; break; } } str = apr_pstrdup(rule->ruleset->mp, match); while (*str != '\0') { switch(*str) { case '.': domain++; domain_len = strlen(domain); d_pos = strchr(domain,'.') - domain; if(s_pos >= 0 && d_pos >= 0 && d_pos > s_pos) break; if(*domain != '/') { if(domain[domain_len-1] == '.') domain[domain_len-1] = '\0'; if(domain[domain_len-1] == '/' && domain[domain_len-2] == '.') { domain[domain_len-2] = '/'; domain[domain_len-1] = '\0'; } dot = strchr(domain,'.'); if(dot != NULL) { canon = apr_pstrdup(rule->ruleset->mp, domain); ret = verify_gsb(gsb, msr, canon, strlen(canon)); if(ret > 0) { set_match_to_tx(msr, capture, canon, 0); if (! *error_msg) { *error_msg = apr_psprintf(msr->mp, "Gsb lookup for \"%s\" succeeded.", log_escape_nq(msr->mp, canon)); } str = apr_pstrdup(rule->ruleset->mp,match); base = apr_strtok(str,"/",&savedptr); if(base != NULL) set_match_to_tx(msr, capture, base, 1); return 1; } base = apr_strtok(canon,"?",&savedptr); if(base != NULL) { ret = verify_gsb(gsb, msr, base, strlen(base)); if(ret > 0) { set_match_to_tx(msr, capture, base, 0); if (! *error_msg) { *error_msg = apr_psprintf(msr->mp, "Gsb lookup for \"%s\" succeeded.", log_escape_nq(msr->mp, base)); } str = apr_pstrdup(rule->ruleset->mp,match); base = apr_strtok(str,"/",&savedptr); if(base != NULL) set_match_to_tx(msr, capture, base, 1); return 1; } } url = apr_palloc(rule->ruleset->mp, strlen(canon)); count_slash = 0; while(*canon != '\0') { switch (*canon) { case '/': ptr = apr_psprintf(rule->ruleset->mp,"%s/",url); ret = verify_gsb(gsb, msr, ptr, strlen(ptr)); if(ret > 0) { set_match_to_tx(msr, capture, ptr, 0); if (! *error_msg) { *error_msg = apr_psprintf(msr->mp, "Gsb lookup for \"%s\" succeeded.", log_escape_nq(msr->mp, ptr)); } str = apr_pstrdup(rule->ruleset->mp,match); base = apr_strtok(str,"/",&savedptr); if(base != NULL) set_match_to_tx(msr, capture, base, 1); return 1; } break; } url[count_slash] = *canon; count_slash++; canon++; } } } break; } domain = str; domain++; str++; } } } offset = ovector[1]; } return 0; } /* within */ static int msre_op_within_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { msc_string *str = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); const char *match = NULL; const char *target; unsigned int match_length; unsigned int target_length = 0; unsigned int i, i_max; str->value = (char *)rule->op_param; if (str->value == NULL) { *error_msg = "Internal Error: match string is null."; return -1; } str->value_len = strlen(str->value); if (error_msg == NULL) return -1; *error_msg = NULL; expand_macros(msr, str, rule, msr->mp); match = (const char *)str->value; match_length = str->value_len; /* If the given target is null we give up without a match */ if (var->value == NULL) { /* No match. */ return 0; } target = var->value; target_length = var->value_len; /* The empty string always matches */ if (target_length == 0) { /* Match. */ *error_msg = apr_psprintf(msr->mp, "String match within \"\" at %s.", var->name); return 1; } /* This is impossible to match */ if (target_length > match_length) { /* No match. */ return 0; } /* scan for first character, then compare from there until we * have a match or there is no room left in the target */ i_max = match_length - target_length; for (i = 0; i <= i_max; i++) { if (match[i] == target[0]) { if (memcmp((target + 1), (match + i + 1), (target_length - 1)) == 0) { /* match. */ *error_msg = apr_psprintf(msr->mp, "String match within \"%s\" at %s.", log_escape_ex(msr->mp, match, match_length), var->name); return 1; } } } /* No match. */ return 0; } /* contains */ static int msre_op_contains_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { msc_string *str = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); const char *match = NULL; const char *target; unsigned int match_length; unsigned int target_length = 0; unsigned int i, i_max; str->value = (char *)rule->op_param; if (str->value == NULL) { *error_msg = "Internal Error: match string is null."; return -1; } str->value_len = strlen(str->value); if (error_msg == NULL) return -1; *error_msg = NULL; expand_macros(msr, str, rule, msr->mp); match = (const char *)str->value; match_length = str->value_len; /* If the given target is null run against an empty * string. This is a behaviour consistent with previous * releases. */ if (var->value == NULL) { target = ""; target_length = 0; } else { target = var->value; target_length = var->value_len; } /* The empty string always matches */ if (match_length == 0) { /* Match. */ *error_msg = apr_psprintf(msr->mp, "String match \"\" at %s.", var->name); return 1; } /* This is impossible to match */ if (match_length > target_length) { /* No match. */ return 0; } /* scan for first character, then compare from there until we * have a match or there is no room left in the target */ i_max = target_length - match_length; for (i = 0; i <= i_max; i++) { /* First character matched - avoid func call */ if (target[i] == match[0]) { /* See if remaining matches */ if ( (match_length == 1) || (memcmp((match + 1), (target + i + 1), (match_length - 1)) == 0)) { /* Match. */ *error_msg = apr_psprintf(msr->mp, "String match \"%s\" at %s.", log_escape_ex(msr->mp, match, match_length), var->name); return 1; } } } /* No match. */ return 0; } /** libinjection detectSQLi * links against files in libinjection directory * See www.client9.com/libinjection for details */ static int msre_op_detectSQLi_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { char fingerprint[8]; int issqli; int capture; issqli = libinjection_sqli(var->value, var->value_len, fingerprint); capture = apr_table_get(rule->actionset->actions, "capture") ? 1 : 0; if (issqli) { set_match_to_tx(msr, capture, fingerprint, 0); *error_msg = apr_psprintf(msr->mp, "detected SQLi using libinjection with fingerprint '%s'", fingerprint); if (msr->txcfg->debuglog_level >= 9) { msr_log(msr, 9, "ISSQL: libinjection fingerprint '%s' matched input '%s'", fingerprint, log_escape_ex(msr->mp, var->value, var->value_len)); } } else { if (msr->txcfg->debuglog_level >= 9) { msr_log(msr, 9, "ISSQL: not sqli, no libinjection sqli fingerprint matched input '%s'", log_escape_ex(msr->mp, var->value, var->value_len)); } } return issqli; } /** libinjection detectXSS */ static int msre_op_detectXSS_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { int is_xss; is_xss = libinjection_xss(var->value, var->value_len); if (is_xss) { *error_msg = apr_psprintf(msr->mp, "detected XSS using libinjection."); if (msr->txcfg->debuglog_level >= 9) { msr_log(msr, 9, "IS_XSS: libinjection detected XSS."); } } else { if (msr->txcfg->debuglog_level >= 9) { msr_log(msr, 9, "IS_XSS: not XSS, libinjection was not able to find any XSS."); } } return is_xss; } /* containsWord */ static int msre_op_containsWord_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { msc_string *str = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); const char *match = NULL; const char *target; unsigned int match_length; unsigned int target_length = 0; unsigned int i, i_max; int rc = 0; str->value = (char *)rule->op_param; if (str->value == NULL) { *error_msg = "Internal Error: match string is null."; return -1; } str->value_len = strlen(str->value); if (error_msg == NULL) return -1; *error_msg = NULL; expand_macros(msr, str, rule, msr->mp); match = (const char *)str->value; match_length = str->value_len; /* If the given target is null run against an empty * string. This is a behaviour consistent with previous * releases. */ if (var->value == NULL) { target = ""; target_length = 0; } else { target = var->value; target_length = var->value_len; } /* The empty string always matches */ if (match_length == 0) { /* Match. */ *error_msg = apr_psprintf(msr->mp, "String match \"\" at %s.", var->name); return 1; } /* This is impossible to match */ if (match_length > target_length) { /* No match. */ return 0; } /* scan for first character, then compare from there until we * have a match or there is no room left in the target */ i_max = target_length - match_length; for (i = 0; i <= i_max; i++) { /* Previous char must have been a start or non-word */ if ((i > 0) && (apr_isalnum(target[i-1])||(target[i-1] == '_'))) continue; /* First character matched - avoid func call */ if (target[i] == match[0]) { /* See if remaining matches */ if ( (match_length == 1) || (memcmp((match + 1), (target + i + 1), (match_length - 1)) == 0)) { /* check boundaries */ if (i == i_max) { /* exact/end word match */ rc = 1; } else if (!(apr_isalnum(target[i + match_length])||(target[i + match_length] == '_'))) { /* start/mid word match */ rc = 1; } } } } if (rc == 1) { /* Maybe a match. */ *error_msg = apr_psprintf(msr->mp, "String match \"%s\" at %s.", log_escape_ex(msr->mp, match, match_length), var->name); return 1; } /* No match. */ *error_msg = NULL; return 0; } /* streq */ static int msre_op_streq_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { msc_string *str = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); const char *match = NULL; const char *target; unsigned int match_length; unsigned int target_length; str->value = (char *)rule->op_param; if (str->value == NULL) { *error_msg = "Internal Error: match string is null."; return -1; } str->value_len = strlen(str->value); if (error_msg == NULL) return -1; *error_msg = NULL; expand_macros(msr, str, rule, msr->mp); match = (const char *)str->value; match_length = str->value_len; /* If the given target is null run against an empty * string. This is a behaviour consistent with previous * releases. */ if (var->value == NULL) { target = ""; target_length = 0; } else { target = var->value; target_length = var->value_len; } /* These are impossible to match */ if (match_length != target_length) { /* No match. */ return 0; } if (memcmp(match, target, target_length) == 0) { /* Match. */ *error_msg = apr_psprintf(msr->mp, "String match \"%s\" at %s.", log_escape_ex(msr->mp, match, match_length), var->name); return 1; } /* No match. */ return 0; } /* beginsWith */ static int msre_op_beginsWith_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { msc_string *str = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); const char *match = NULL; const char *target; unsigned int match_length; unsigned int target_length; str->value = (char *)rule->op_param; if (str->value == NULL) { *error_msg = "Internal Error: match string is null."; return -1; } str->value_len = strlen(str->value); if (error_msg == NULL) return -1; *error_msg = NULL; expand_macros(msr, str, rule, msr->mp); match = (const char *)str->value; match_length = str->value_len; /* If the given target is null run against an empty * string. This is a behaviour consistent with previous * releases. */ if (var->value == NULL) { target = ""; target_length = 0; } else { target = var->value; target_length = var->value_len; } /* The empty string always matches */ if (match_length == 0) { /* Match. */ *error_msg = apr_psprintf(msr->mp, "String match \"\" at %s.", var->name); return 1; } /* This is impossible to match */ if (match_length > target_length) { /* No match. */ return 0; } if (memcmp(match, target, match_length) == 0) { /* Match. */ *error_msg = apr_psprintf(msr->mp, "String match \"%s\" at %s.", log_escape_ex(msr->mp, match, match_length), var->name); return 1; } /* No match. */ return 0; } /* endsWith */ static int msre_op_endsWith_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { msc_string *str = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); const char *match = NULL; const char *target; unsigned int match_length; unsigned int target_length; str->value = (char *)rule->op_param; if (str->value == NULL) { *error_msg = "Internal Error: match string is null."; return -1; } str->value_len = strlen(str->value); if (error_msg == NULL) return -1; *error_msg = NULL; expand_macros(msr, str, rule, msr->mp); match = (const char *)str->value; match_length = str->value_len; /* If the given target is null run against an empty * string. This is a behaviour consistent with previous * releases. */ if (var->value == NULL) { target = ""; target_length = 0; } else { target = var->value; target_length = var->value_len; } /* The empty string always matches */ if (match_length == 0) { /* Match. */ *error_msg = apr_psprintf(msr->mp, "String match \"\" at %s.", var->name); return 1; } /* This is impossible to match */ if (match_length > target_length) { /* No match. */ return 0; } if (memcmp(match, (target + (target_length - match_length)), match_length) == 0) { /* Match. */ *error_msg = apr_psprintf(msr->mp, "String match \"%s\" at %s.", log_escape_ex(msr->mp, match, match_length), var->name); return 1; } /* No match. */ return 0; } /* strmatch */ static int msre_op_strmatch_param_init(msre_rule *rule, char **error_msg) { const apr_strmatch_pattern *compiled_pattern; char *processed = NULL; const char *pattern = rule->op_param; unsigned short int op_len; if (error_msg == NULL) return -1; *error_msg = NULL; op_len = strlen(pattern); /* Process pattern */ processed = parse_pm_content(pattern, op_len, rule, error_msg); if (processed == NULL) { return 0; } /* Compile pattern */ compiled_pattern = apr_strmatch_precompile(rule->ruleset->mp, processed, 1); if (compiled_pattern == NULL) { *error_msg = apr_psprintf(rule->ruleset->mp, "Error compiling pattern: %s", pattern); return 0; } rule->op_param_data = (void *)compiled_pattern; return 1; /* OK */ } static int msre_op_strmatch_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { apr_strmatch_pattern *compiled_pattern = (apr_strmatch_pattern *)rule->op_param_data; const char *target; unsigned int target_length; const char *rc; if (error_msg == NULL) return -1; *error_msg = NULL; if (compiled_pattern == NULL) { *error_msg = "Internal Error: strnmatch data is null."; return -1; } /* If the given target is null run against an empty * string. This is a behaviour consistent with previous * releases. */ if (var->value == NULL) { target = ""; target_length = 0; } else { target = var->value; target_length = var->value_len; } rc = apr_strmatch(compiled_pattern, target, target_length); if (rc == NULL) { /* No match. */ return 0; } *error_msg = apr_psprintf(msr->mp, "Pattern match \"%s\" at %s.", log_escape(msr->mp, rule->op_param), var->name); /* Match. */ return 1; } /* validateDTD */ static int msre_op_validateDTD_init(msre_rule *rule, char **error_msg) { /* ENH Verify here the file actually exists. */ return 1; } static int msre_op_validateDTD_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { xmlValidCtxtPtr cvp; xmlDtdPtr dtd; if ((msr->xml == NULL)||(msr->xml->doc == NULL)) { *error_msg = apr_psprintf(msr->mp, "XML document tree could not be found for DTD validation."); return -1; } if (msr->xml->well_formed != 1) { *error_msg = apr_psprintf(msr->mp, "XML: DTD validation failed because content is not well formed."); return 1; } /* Make sure there were no other generic processing errors */ if (msr->msc_reqbody_error) { *error_msg = apr_psprintf(msr->mp, "XML: DTD validation could not proceed due to previous" " processing errors."); return 1; } dtd = xmlParseDTD(NULL, (const xmlChar *)rule->op_param); /* EHN support relative filenames */ if (dtd == NULL) { *error_msg = apr_psprintf(msr->mp, "XML: Failed to load DTD: %s", rule->op_param); return -1; } cvp = xmlNewValidCtxt(); if (cvp == NULL) { *error_msg = "XML: Failed to create a validation context."; xmlFreeDtd(dtd); return -1; } /* Send validator errors/warnings to msr_log */ /* NOTE: No xmlDtdSetValidErrors()? */ cvp->error = (xmlSchemaValidityErrorFunc)msr_log_error; cvp->warning = (xmlSchemaValidityErrorFunc)msr_log_warn; cvp->userData = msr; if (!xmlValidateDtd(cvp, msr->xml->doc, dtd)) { *error_msg = "XML: DTD validation failed."; xmlFreeValidCtxt(cvp); xmlFreeDtd(dtd); return 1; /* No match. */ } if (msr->txcfg->debuglog_level >= 4) { msr_log(msr, 4, "XML: Successfully validated payload against DTD: %s", rule->op_param); } xmlFreeValidCtxt(cvp); xmlFreeDtd(dtd); /* Match. */ return 0; } /* validateSchema */ static int msre_op_validateSchema_init(msre_rule *rule, char **error_msg) { /* ENH Verify here the file actually exists. */ return 1; } static int msre_op_validateSchema_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { xmlSchemaParserCtxtPtr parserCtx; xmlSchemaValidCtxtPtr validCtx; xmlSchemaPtr schema; int rc; if ((msr->xml == NULL)||(msr->xml->doc == NULL)) { *error_msg = apr_psprintf(msr->mp, "XML document tree could not be found for schema validation."); return -1; } if (msr->xml->well_formed != 1) { *error_msg = apr_psprintf(msr->mp, "XML: Schema validation failed because content is not well formed."); return 1; } /* Make sure there were no other generic processing errors */ if (msr->msc_reqbody_error) { *error_msg = apr_psprintf(msr->mp, "XML: Schema validation could not proceed due to previous" " processing errors."); return 1; } parserCtx = xmlSchemaNewParserCtxt(rule->op_param); /* ENH support relative filenames */ if (parserCtx == NULL) { *error_msg = apr_psprintf(msr->mp, "XML: Failed to load Schema from file: %s", rule->op_param); return -1; } /* Send parser errors/warnings to msr_log */ xmlSchemaSetParserErrors(parserCtx, (xmlSchemaValidityErrorFunc)msr_log_error, (xmlSchemaValidityWarningFunc)msr_log_warn, msr); schema = xmlSchemaParse(parserCtx); if (schema == NULL) { *error_msg = apr_psprintf(msr->mp, "XML: Failed to load Schema: %s", rule->op_param); xmlSchemaFreeParserCtxt(parserCtx); return -1; } validCtx = xmlSchemaNewValidCtxt(schema); if (validCtx == NULL) { *error_msg = "XML: Failed to create validation context."; xmlSchemaFree(schema); xmlSchemaFreeParserCtxt(parserCtx); return -1; } /* Send validator errors/warnings to msr_log */ xmlSchemaSetValidErrors(validCtx, (xmlSchemaValidityErrorFunc)msr_log_error, (xmlSchemaValidityWarningFunc)msr_log_warn, msr); rc = xmlSchemaValidateDoc(validCtx, msr->xml->doc); if (rc != 0) { *error_msg = "XML: Schema validation failed."; xmlSchemaFree(schema); xmlSchemaFreeParserCtxt(parserCtx); return 1; /* No match. */ } if (msr->txcfg->debuglog_level >= 4) { msr_log(msr, 4, "XML: Successfully validated payload against Schema: %s", rule->op_param); } xmlSchemaFree(schema); xmlSchemaFreeValidCtxt(validCtx); return 0; } /* verifyCC */ /** * Luhn Mod-10 Method (ISO 2894/ANSI 4.13) */ static int luhn_verify(const char *ccnumber, int len) { int sum[2] = { 0, 0 }; int odd = 0; int digits = 0; int i; /* Weighted lookup table which is just a precalculated (i = index): * i*2 + (( (i*2) > 9 ) ? -9 : 0) */ static const int wtable[10] = {0, 2, 4, 6, 8, 1, 3, 5, 7, 9}; /* weight lookup table */ /* Add up only digits (weighted digits via lookup table) * for both odd and even CC numbers to avoid 2 passes. */ for (i = 0; i < len; i++) { if (apr_isdigit(ccnumber[i])) { sum[0] += (!odd ? wtable[ccnumber[i] - '0'] : (ccnumber[i] - '0')); sum[1] += (odd ? wtable[ccnumber[i] - '0'] : (ccnumber[i] - '0')); odd = 1 - odd; /* alternate weights */ digits++; } } /* No digits extracted */ if (digits == 0) return 0; /* Do a mod 10 on the sum */ sum[odd] %= 10; /* If the result is a zero the card is valid. */ return sum[odd] ? 0 : 1; } static int msre_op_verifyCC_init(msre_rule *rule, char **error_msg) { const char *errptr = NULL; int erroffset; msc_regex_t *regex; if (error_msg == NULL) return -1; *error_msg = NULL; /* Compile rule->op_param */ regex = msc_pregcomp_ex(rule->ruleset->mp, rule->op_param, PCRE_DOTALL | PCRE_MULTILINE, &errptr, &erroffset, msc_pcre_match_limit, msc_pcre_match_limit_recursion); if (regex == NULL) { *error_msg = apr_psprintf(rule->ruleset->mp, "Error compiling pattern (offset %d): %s", erroffset, errptr); return 0; } rule->op_param_data = regex; return 1; /* OK */ } static int msre_op_verifyCC_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { msc_regex_t *regex = (msc_regex_t *)rule->op_param_data; const char *target; unsigned int target_length; char *my_error_msg = NULL; int ovector[33]; int rc; int is_cc = 0; int offset; int matched_bytes = 0; char *qspos = NULL; const char *parm = NULL; msc_parm *mparm = NULL; #ifdef WITH_PCRE_STUDY #ifdef WITH_PCRE_JIT int jit; #endif #endif if (error_msg == NULL) return -1; *error_msg = NULL; if (regex == NULL) { *error_msg = "Internal Error: regex data is null."; return -1; } memset(ovector, 0, sizeof(ovector)); #ifdef WITH_PCRE_STUDY #ifdef WITH_PCRE_JIT if (msr->txcfg->debuglog_level >= 4) { rc = msc_fullinfo(regex, PCRE_INFO_JIT, &jit); if ((rc != 0) || (jit != 1)) { *error_msg = apr_psprintf(rule->ruleset->mp, "Rule %pp [id \"%s\"][file \"%s\"][line \"%d\"] - " "Execution error - " "Does not support JIT (%d)", rule,((rule->actionset != NULL)&&((rule->actionset->id != NULL)&& (rule->actionset->id != NOT_SET_P))) ? rule->actionset->id : "-", rule->filename != NULL ? rule->filename : "-", rule->line_num,rc); msr_log(msr, 4, "%s.", *error_msg); } } #endif #endif /* If the given target is null run against an empty * string. This is a behaviour consistent with previous * releases. */ if (var->value == NULL) { target = ""; target_length = 0; } else { target = var->value; target_length = var->value_len; } for (offset = 0; ((unsigned int)offset < target_length) && (is_cc == 0); offset++) { if (msr->txcfg->debuglog_level >= 9) { if (offset > 0) { msr_log(msr, 9, "Continuing CC# search at target offset %d.", offset); } } rc = msc_regexec_ex(regex, target, target_length, offset, PCRE_NOTEMPTY, ovector, 30, &my_error_msg); /* If there was no match, then we are done. */ if (rc == PCRE_ERROR_NOMATCH) { break; } if (rc < -1) { *error_msg = apr_psprintf(msr->mp, "CC# regex execution failed: %s", my_error_msg); return -1; } /* Verify a match. */ if (rc > 0) { const char *match = target + ovector[0]; int length = ovector[1] - ovector[0]; int i = 0; offset = ovector[2*i]; /* Check the Luhn using the match string */ is_cc = luhn_verify(match, length); /* Not a CC number, then try another match where we left off. */ if (!is_cc) { if (msr->txcfg->debuglog_level >= 9) { msr_log(msr, 9, "CC# Luhn check failed at target offset %d: \"%.*s\"", offset, length, match); } continue; } /* We have a potential CC number and need to set any captures * and we are done. */ matched_bytes = apr_table_get(rule->actionset->actions, "sanitizeMatchedBytes") ? 1 : 0; if(!matched_bytes) matched_bytes = apr_table_get(rule->actionset->actions, "sanitiseMatchedBytes") ? 1 : 0; if (apr_table_get(rule->actionset->actions, "capture")) { for(; i < rc; i++) { msc_string *s = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); if (s == NULL) return -1; s->name = apr_psprintf(msr->mp, "%d", i); if (s->name == NULL) return -1; s->name_len = strlen(s->name); s->value = apr_pstrmemdup(msr->mp, match, length); if (s->value == NULL) return -1; s->value_len = length; apr_table_setn(msr->tx_vars, s->name, (void *)s); if (msr->txcfg->debuglog_level >= 9) { msr_log(msr, 9, "Added regex subexpression to TX.%d: %s", i, log_escape_nq_ex(msr->mp, s->value, s->value_len)); } if((matched_bytes == 1) && (var != NULL) && (var->name != NULL)) { qspos = apr_psprintf(msr->mp, "%s", var->name); parm = strstr(qspos, ":"); if (parm != NULL) { parm++; mparm = apr_palloc(msr->mp, sizeof(msc_parm)); if (mparm == NULL) continue; mparm->value = apr_pstrmemdup(msr->mp,s->value,s->value_len); mparm->pad_1 = rule->actionset->arg_min; mparm->pad_2 = rule->actionset->arg_max; apr_table_addn(msr->pattern_to_sanitize, parm, (void *)mparm); } else { mparm = apr_palloc(msr->mp, sizeof(msc_parm)); if (mparm == NULL) continue; mparm->value = apr_pstrmemdup(msr->mp,s->value,s->value_len); apr_table_addn(msr->pattern_to_sanitize, qspos, (void *)mparm); } } } } /* Unset the remaining TX vars (from previous invocations). */ for(; i <= 9; i++) { char buf[24]; apr_snprintf(buf, sizeof(buf), "%i", i); apr_table_unset(msr->tx_vars, buf); } break; } } if (is_cc) { /* Match. */ /* This message will be logged. */ *error_msg = apr_psprintf(msr->mp, "CC# match \"%s\" at %s. [offset \"%d\"]", regex->pattern, var->name, offset); return 1; } /* No match. */ return 0; } /** * \brief Check for a valid CPF * * \param cpfnumber Pointer to cpf * \param len cpf length * * \retval 0 On Invalid CPF * \retval 1 On Valid CPF */ static int cpf_verify(const char *cpfnumber, int len) { int factor, part_1, part_2, var_len = len; unsigned int sum = 0, i = 0, cpf_len = 11, c; int cpf[11]; char s_cpf[11]; char bad_cpf[11][11] = { "00000000000", "01234567890", "11111111111", "22222222222", "33333333333", "44444444444", "55555555555", "66666666666", "77777777777", "88888888888", "99999999999"}; while((*cpfnumber != '\0') && ( var_len > 0)) { if(*cpfnumber != '-' || *cpfnumber != '.') { if(i < cpf_len && isdigit(*cpfnumber)) { s_cpf[i] = *cpfnumber; cpf[i] = convert_to_int(*cpfnumber); i++; } } cpfnumber++; var_len--; } if (i != cpf_len) return 0; else { for(i = 0; i< cpf_len; i++) { if(strncmp(s_cpf,bad_cpf[i],cpf_len) == 0) { return 0; } } } part_1 = convert_to_int(s_cpf[cpf_len-2]); part_2 = convert_to_int(s_cpf[cpf_len-1]); c = cpf_len; for(i = 0; i < 9; i++) { sum += (cpf[i] * --c); } factor = (sum % cpf_len); if(factor < 2) { cpf[9] = 0; } else { cpf[9] = cpf_len-factor; } sum = 0; c = cpf_len; for(i = 0;i < 10; i++) sum += (cpf[i] * c--); factor = (sum % cpf_len); if(factor < 2) { cpf[10] = 0; } else { cpf[10] = cpf_len-factor; } if(part_1 == cpf[9] && part_2 == cpf[10]) return 1; return 0; } /** * \brief Init function to CPF operator * * \param rule ModSecurity rule struct * \param error_msg Error message * * \retval 0 On Failure * \retval 1 On Success */ static int msre_op_verifyCPF_init(msre_rule *rule, char **error_msg) { const char *errptr = NULL; int erroffset; msc_regex_t *regex; if (error_msg == NULL) return -1; *error_msg = NULL; /* Compile rule->op_param */ regex = msc_pregcomp_ex(rule->ruleset->mp, rule->op_param, PCRE_DOTALL | PCRE_MULTILINE, &errptr, &erroffset, msc_pcre_match_limit, msc_pcre_match_limit_recursion); if (regex == NULL) { *error_msg = apr_psprintf(rule->ruleset->mp, "Error compiling pattern (offset %d): %s", erroffset, errptr); return 0; } rule->op_param_data = regex; return 1; /* OK */ } /** * \brief Execution function to CPF operator * * \param msr ModSecurity transaction resource * \param rule ModSecurity rule struct * \param var ModSecurity variable struct * \param error_msg Error message * * \retval -1 On Failure * \retval 1 On Match * \retval 0 On No Match */ static int msre_op_verifyCPF_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { msc_regex_t *regex = (msc_regex_t *)rule->op_param_data; const char *target; unsigned int target_length; char *my_error_msg = NULL; int ovector[33]; int rc; int is_cpf = 0; int offset; int matched_bytes = 0; char *qspos = NULL; const char *parm = NULL; msc_parm *mparm = NULL; #ifdef WITH_PCRE_STUDY #ifdef WITH_PCRE_JIT int jit; #endif #endif if (error_msg == NULL) return -1; *error_msg = NULL; if (regex == NULL) { *error_msg = "Internal Error: regex data is null."; return -1; } memset(ovector, 0, sizeof(ovector)); #ifdef WITH_PCRE_STUDY #ifdef WITH_PCRE_JIT if (msr->txcfg->debuglog_level >= 4) { rc = msc_fullinfo(regex, PCRE_INFO_JIT, &jit); if ((rc != 0) || (jit != 1)) { *error_msg = apr_psprintf(rule->ruleset->mp, "Rule %pp [id \"%s\"][file \"%s\"][line \"%d\"] - " "Execution error - " "Does not support JIT (%d)", rule,((rule->actionset != NULL)&&((rule->actionset->id != NULL)&& (rule->actionset->id != NOT_SET_P))) ? rule->actionset->id : "-", rule->filename != NULL ? rule->filename : "-", rule->line_num,rc); msr_log(msr, 4, "%s.", *error_msg); } } #endif #endif /* If the given target is null run against an empty * string. This is a behaviour consistent with previous * releases. */ if (var->value == NULL) { target = ""; target_length = 0; } else { target = var->value; target_length = var->value_len; } for (offset = 0; ((unsigned int)offset < target_length) && (is_cpf == 0); offset++) { if (msr->txcfg->debuglog_level >= 9) { if (offset > 0) { msr_log(msr, 9, "Continuing CPF# search at target offset %d.", offset); } } rc = msc_regexec_ex(regex, target, target_length, offset, PCRE_NOTEMPTY, ovector, 30, &my_error_msg); /* If there was no match, then we are done. */ if (rc == PCRE_ERROR_NOMATCH) { break; } if (rc < -1) { *error_msg = apr_psprintf(msr->mp, "CPF# regex execution failed: %s", my_error_msg); return -1; } /* Verify a match. */ if (rc > 0) { const char *match = target + ovector[0]; int length = ovector[1] - ovector[0]; int i = 0; offset = ovector[2*i]; /* Check CPF using the match string */ is_cpf = cpf_verify(match, length); /* Not a CPF number, then try another match where we left off. */ if (!is_cpf) { if (msr->txcfg->debuglog_level >= 9) { msr_log(msr, 9, "CPF# check failed at target offset %d: \"%.*s\"", offset, length, match); } continue; } /* We have a potential CPF number and need to set any captures * and we are done. */ matched_bytes = apr_table_get(rule->actionset->actions, "sanitizeMatchedBytes") ? 1 : 0; if(!matched_bytes) matched_bytes = apr_table_get(rule->actionset->actions, "sanitiseMatchedBytes") ? 1 : 0; if (apr_table_get(rule->actionset->actions, "capture")) { for(; i < rc; i++) { msc_string *s = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); if (s == NULL) return -1; s->name = apr_psprintf(msr->mp, "%d", i); if (s->name == NULL) return -1; s->name_len = strlen(s->name); s->value = apr_pstrmemdup(msr->mp, match, length); if (s->value == NULL) return -1; s->value_len = length; apr_table_setn(msr->tx_vars, s->name, (void *)s); if (msr->txcfg->debuglog_level >= 9) { msr_log(msr, 9, "Added regex subexpression to TX.%d: %s", i, log_escape_nq_ex(msr->mp, s->value, s->value_len)); } if((matched_bytes == 1) && (var != NULL) && (var->name != NULL)) { qspos = apr_psprintf(msr->mp, "%s", var->name); parm = strstr(qspos, ":"); if (parm != NULL) { parm++; mparm = apr_palloc(msr->mp, sizeof(msc_parm)); if (mparm == NULL) continue; mparm->value = apr_pstrmemdup(msr->mp,s->value,s->value_len); mparm->pad_1 = rule->actionset->arg_min; mparm->pad_2 = rule->actionset->arg_max; apr_table_addn(msr->pattern_to_sanitize, parm, (void *)mparm); } else { mparm = apr_palloc(msr->mp, sizeof(msc_parm)); if (mparm == NULL) continue; mparm->value = apr_pstrmemdup(msr->mp,s->value,s->value_len); apr_table_addn(msr->pattern_to_sanitize, qspos, (void *)mparm); } } } } /* Unset the remaining TX vars (from previous invocations). */ for(; i <= 9; i++) { char buf[24]; apr_snprintf(buf, sizeof(buf), "%i", i); apr_table_unset(msr->tx_vars, buf); } break; } } if (is_cpf) { /* Match. */ /* This message will be logged. */ *error_msg = apr_psprintf(msr->mp, "CPF# match \"%s\" at %s. [offset \"%d\"]", regex->pattern, var->name, offset); return 1; } /* No match. */ return 0; } /** * \brief Check for a valid SSN * * \param msr ModSecurity transaction source * \param ssnumber Pointer to ssn * \param len ssn length * * \retval 0 On Invalid SSN * \retval 1 On Valid SSN */ static int ssn_verify(modsec_rec *msr, const char *ssnumber, int len) { int i; int num[9]; int digits = 0; int area, serial, grp; int sequencial = 0; int repetitions = 0; char *str_area; char *str_grp; char *str_serial; for (i = 0; i < len; i++) { if (apr_isdigit(ssnumber[i])) { if (digits < 9) num[digits] = convert_to_int(ssnumber[i]); digits++; } } /* Not a valid number */ if (digits != 9) goto invalid; for (i=0; i < 8; i++) { if (num[i] == (num[i+1]-1)) sequencial++; if (num[i] == num[i+1]) repetitions++; } /* We are blocking when all numbers were sequencial or repeated */ if (sequencial == 8) goto invalid; if (repetitions == 8) goto invalid; str_area = apr_psprintf(msr->mp,"%d%d%d",num[0],num[1],num[2]); str_grp = apr_psprintf(msr->mp,"%d%d",num[3],num[4]); str_serial = apr_psprintf(msr->mp,"%d%d%d%d",num[5],num[6],num[7],num[8]); if(str_area == NULL || str_grp == NULL || str_serial == NULL) goto invalid; area = atoi(str_area); grp = atoi(str_grp); serial = atoi(str_serial); /* Cannot has seroed fields */ if (area == 0 || serial == 0 || grp == 0) goto invalid; /* More tests */ if (area >= 740 || area == 666) goto invalid; return 1; invalid: return 0; } /** * \brief Init function to SSN operator * * \param rule ModSecurity rule struct * \param error_msg Error message * * \retval 0 On Failure * \retval 1 On Success */ static int msre_op_verifySSN_init(msre_rule *rule, char **error_msg) { const char *errptr = NULL; int erroffset; msc_regex_t *regex; if (error_msg == NULL) return -1; *error_msg = NULL; /* Compile rule->op_param */ regex = msc_pregcomp_ex(rule->ruleset->mp, rule->op_param, PCRE_DOTALL | PCRE_MULTILINE, &errptr, &erroffset, msc_pcre_match_limit, msc_pcre_match_limit_recursion); if (regex == NULL) { *error_msg = apr_psprintf(rule->ruleset->mp, "Error compiling pattern (offset %d): %s", erroffset, errptr); return 0; } rule->op_param_data = regex; return 1; /* OK */ } /** * \brief Execution function to SSN operator * * \param msr ModSecurity transaction resource * \param rule ModSecurity rule struct * \param var ModSecurity variable struct * \param error_msg Error message * * \retval -1 On Failure * \retval 1 On Match * \retval 0 On No Match */ static int msre_op_verifySSN_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { msc_regex_t *regex = (msc_regex_t *)rule->op_param_data; const char *target; unsigned int target_length; char *my_error_msg = NULL; int ovector[33]; int rc; int is_ssn = 0; int offset; int matched_bytes = 0; char *qspos = NULL; const char *parm = NULL; msc_parm *mparm = NULL; #ifdef WITH_PCRE_STUDY #ifdef WITH_PCRE_JIT int jit; #endif #endif if (error_msg == NULL) return -1; *error_msg = NULL; if (regex == NULL) { *error_msg = "Internal Error: regex data is null."; return -1; } memset(ovector, 0, sizeof(ovector)); #ifdef WITH_PCRE_STUDY #ifdef WITH_PCRE_JIT if (msr->txcfg->debuglog_level >= 4) { rc = msc_fullinfo(regex, PCRE_INFO_JIT, &jit); if ((rc != 0) || (jit != 1)) { *error_msg = apr_psprintf(rule->ruleset->mp, "Rule %pp [id \"%s\"][file \"%s\"][line \"%d\"] - " "Execution error - " "Does not support JIT (%d)", rule,((rule->actionset != NULL)&&((rule->actionset->id != NULL)&& (rule->actionset->id != NOT_SET_P))) ? rule->actionset->id : "-", rule->filename != NULL ? rule->filename : "-", rule->line_num,rc); msr_log(msr, 4, "%s.", *error_msg); } } #endif #endif /* If the given target is null run against an empty * string. This is a behaviour consistent with previous * releases. */ if (var->value == NULL) { target = ""; target_length = 0; } else { target = var->value; target_length = var->value_len; } for (offset = 0; ((unsigned int)offset < target_length) && (is_ssn == 0); offset++) { if (msr->txcfg->debuglog_level >= 9) { if (offset > 0) { msr_log(msr, 9, "Continuing SSN# search at target offset %d.", offset); } } rc = msc_regexec_ex(regex, target, target_length, offset, PCRE_NOTEMPTY, ovector, 30, &my_error_msg); /* If there was no match, then we are done. */ if (rc == PCRE_ERROR_NOMATCH) { break; } if (rc < -1) { *error_msg = apr_psprintf(msr->mp, "SSN# regex execution failed: %s", my_error_msg); return -1; } /* Verify a match. */ if (rc > 0) { const char *match = target + ovector[0]; int length = ovector[1] - ovector[0]; int i = 0; offset = ovector[2*i]; /* Check SSN using the match string */ is_ssn = ssn_verify(msr, match, length); /* Not a SSN number, then try another match where we left off. */ if (!is_ssn) { if (msr->txcfg->debuglog_level >= 9) { msr_log(msr, 9, "SSN# check failed at target offset %d: \"%.*s\"", offset, length, match); } continue; } /* We have a potential SSN number and need to set any captures * and we are done. */ matched_bytes = apr_table_get(rule->actionset->actions, "sanitizeMatchedBytes") ? 1 : 0; if(!matched_bytes) matched_bytes = apr_table_get(rule->actionset->actions, "sanitiseMatchedBytes") ? 1 : 0; if (apr_table_get(rule->actionset->actions, "capture")) { for(; i < rc; i++) { msc_string *s = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); if (s == NULL) return -1; s->name = apr_psprintf(msr->mp, "%d", i); if (s->name == NULL) return -1; s->name_len = strlen(s->name); s->value = apr_pstrmemdup(msr->mp, match, length); if (s->value == NULL) return -1; s->value_len = length; apr_table_setn(msr->tx_vars, s->name, (void *)s); if (msr->txcfg->debuglog_level >= 9) { msr_log(msr, 9, "Added regex subexpression to TX.%d: %s", i, log_escape_nq_ex(msr->mp, s->value, s->value_len)); } if((matched_bytes == 1) && (var != NULL) && (var->name != NULL)) { qspos = apr_psprintf(msr->mp, "%s", var->name); parm = strstr(qspos, ":"); if (parm != NULL) { parm++; mparm = apr_palloc(msr->mp, sizeof(msc_parm)); if (mparm == NULL) continue; mparm->value = apr_pstrmemdup(msr->mp,s->value,s->value_len); mparm->pad_1 = rule->actionset->arg_min; mparm->pad_2 = rule->actionset->arg_max; apr_table_addn(msr->pattern_to_sanitize, parm, (void *)mparm); } else { mparm = apr_palloc(msr->mp, sizeof(msc_parm)); if (mparm == NULL) continue; mparm->value = apr_pstrmemdup(msr->mp,s->value,s->value_len); apr_table_addn(msr->pattern_to_sanitize, qspos, (void *)mparm); } } } } /* Unset the remaining TX vars (from previous invocations). */ for(; i <= 9; i++) { char buf[24]; apr_snprintf(buf, sizeof(buf), "%i", i); apr_table_unset(msr->tx_vars, buf); } break; } } if (is_ssn) { /* Match. */ /* This message will be logged. */ *error_msg = apr_psprintf(msr->mp, "SSN# match \"%s\" at %s. [offset \"%d\"]", regex->pattern, var->name, offset); return 1; } /* No match. */ return 0; } /** * Perform geograpical lookups on an IP/Host. */ static int msre_op_geoLookup_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { geo_rec rec; geo_db *geo = msr->txcfg->geo; const char *geo_host = var->value; msc_string *s = NULL; int rc; *error_msg = NULL; if (geo == NULL) { msr_log(msr, 1, "Geo lookup for \"%s\" attempted without a database. Set SecGeoLookupDB.", log_escape(msr->mp, geo_host)); return 0; } rc = geo_lookup(msr, &rec, geo_host, error_msg); if (rc <= 0) { if (! *error_msg) { *error_msg = apr_psprintf(msr->mp, "Geo lookup for \"%s\" failed at %s.", log_escape_nq(msr->mp, geo_host), var->name); } apr_table_clear(msr->geo_vars); return rc; } if (! *error_msg) { *error_msg = apr_psprintf(msr->mp, "Geo lookup for \"%s\" succeeded at %s.", log_escape_nq(msr->mp, geo_host), var->name); } if (msr->txcfg->debuglog_level >= 9) { msr_log(msr, 9, "GEO: %s={country_code=%s, country_code3=%s, country_name=%s, country_continent=%s, region=%s, city=%s, postal_code=%s, latitude=%f, longitude=%f, dma_code=%d, area_code=%d}", geo_host, rec.country_code, rec.country_code3, rec.country_name, rec.country_continent, rec.region, rec.city, rec.postal_code, rec.latitude, rec.longitude, rec.dma_code, rec.area_code); } s = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); s->name = apr_pstrdup(msr->mp, "COUNTRY_CODE"); s->name_len = strlen(s->name); s->value = apr_pstrdup(msr->mp, rec.country_code ? rec.country_code : ""); s->value_len = strlen(s->value); apr_table_setn(msr->geo_vars, s->name, (void *)s); s = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); s->name = apr_pstrdup(msr->mp, "COUNTRY_CODE3"); s->name_len = strlen(s->name); s->value = apr_pstrdup(msr->mp, rec.country_code3 ? rec.country_code3 : ""); s->value_len = strlen(s->value); apr_table_setn(msr->geo_vars, s->name, (void *)s); s = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); s->name = apr_pstrdup(msr->mp, "COUNTRY_NAME"); s->name_len = strlen(s->name); s->value = apr_pstrdup(msr->mp, rec.country_name ? rec.country_name : ""); s->value_len = strlen(s->value); apr_table_setn(msr->geo_vars, s->name, (void *)s); s = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); s->name = apr_pstrdup(msr->mp, "COUNTRY_CONTINENT"); s->name_len = strlen(s->name); s->value = apr_pstrdup(msr->mp, rec.country_continent ? rec.country_continent : ""); s->value_len = strlen(s->value); apr_table_setn(msr->geo_vars, s->name, (void *)s); s = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); s->name = apr_pstrdup(msr->mp, "REGION"); s->name_len = strlen(s->name); s->value = apr_pstrdup(msr->mp, rec.region ? rec.region : ""); s->value_len = strlen(s->value); apr_table_setn(msr->geo_vars, s->name, (void *)s); s = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); s->name = apr_pstrdup(msr->mp, "CITY"); s->name_len = strlen(s->name); s->value = apr_pstrdup(msr->mp, rec.city ? rec.city : ""); s->value_len = strlen(s->value); apr_table_setn(msr->geo_vars, s->name, (void *)s); s = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); s->name = apr_pstrdup(msr->mp, "POSTAL_CODE"); s->name_len = strlen(s->name); s->value = apr_pstrdup(msr->mp, rec.postal_code ? rec.postal_code : ""); s->value_len = strlen(s->value); apr_table_setn(msr->geo_vars, s->name, (void *)s); s = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); s->name = apr_pstrdup(msr->mp, "LATITUDE"); s->name_len = strlen(s->name); s->value = apr_psprintf(msr->mp, "%f", rec.latitude); s->value_len = strlen(s->value); apr_table_setn(msr->geo_vars, s->name, (void *)s); s = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); s->name = apr_pstrdup(msr->mp, "LONGITUDE"); s->name_len = strlen(s->name); s->value = apr_psprintf(msr->mp, "%f", rec.longitude); s->value_len = strlen(s->value); apr_table_setn(msr->geo_vars, s->name, (void *)s); s = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); s->name = apr_pstrdup(msr->mp, "DMA_CODE"); s->name_len = strlen(s->name); s->value = apr_psprintf(msr->mp, "%d", rec.dma_code); s->value_len = strlen(s->value); apr_table_setn(msr->geo_vars, s->name, (void *)s); s = (msc_string *)apr_pcalloc(msr->mp, sizeof(msc_string)); s->name = apr_pstrdup(msr->mp, "AREA_CODE"); s->name_len = strlen(s->name); s->value = apr_psprintf(msr->mp, "%d", rec.area_code); s->value_len = strlen(s->value); apr_table_setn(msr->geo_vars, s->name, (void *)s); return 1; } /* rbl */ static int msre_op_rbl_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { unsigned int h0, h1, h2, h3; unsigned int high8bits = 0; char *name_to_check = NULL; char *target = NULL; apr_sockaddr_t *sa = NULL; apr_status_t rc; int capture = 0; if (error_msg == NULL) return -1; *error_msg = NULL; capture = apr_table_get(rule->actionset->actions, "capture") ? 1 : 0; /* ENH Add IPv6 support. */ target = apr_pstrmemdup(msr->mp, var->value, var->value_len); if (target == NULL) return -1; /* Construct the host name we want to resolve. */ if (sscanf(target, "%d.%d.%d.%d", &h0, &h1, &h2, &h3) == 4) { /* IPv4 address */ /* If we're using the httpBl blocklist, we need to add the key */ if(strstr(rule->op_param,"httpbl.org")) { if (msr->txcfg->httpBlkey == NULL) { if (msr->txcfg->debuglog_level >= 4) { msr_log(msr, 4, "RBL httpBl called but no key defined: set SecHttpBlKey"); } *error_msg = "RBL httpBl called but no key defined: set SecHttpBlKey"; } else { name_to_check = apr_psprintf(msr->mp, "%s.%d.%d.%d.%d.%s", msr->txcfg->httpBlkey, h3, h2, h1, h0, rule->op_param); } } else { /* regular IPv4 RBLs */ name_to_check = apr_psprintf(msr->mp, "%d.%d.%d.%d.%s", h3, h2, h1, h0, rule->op_param); } } else { /* Assume the input is a domain name. */ name_to_check = apr_psprintf(msr->mp, "%s.%s", target, rule->op_param); } if (name_to_check == NULL) return -1; rc = apr_sockaddr_info_get(&sa, name_to_check, APR_UNSPEC/*msr->r->connection->remote_addr->family*/, 0, 0, msr->mp); if (rc == APR_SUCCESS) { high8bits = sa->sa.sin.sin_addr.s_addr >> 24; /* multi.uribl.com */ if(strstr(rule->op_param,"uribl.com")) { switch(high8bits) { case 2: *error_msg = apr_psprintf(msr->r->pool, "RBL lookup of %s succeeded at %s (BLACK).", log_escape_nq(msr->mp, name_to_check), var->name); break; case 4: *error_msg = apr_psprintf(msr->r->pool, "RBL lookup of %s succeeded at %s (GREY).", log_escape_nq(msr->mp, name_to_check), var->name); break; case 8: *error_msg = apr_psprintf(msr->r->pool, "RBL lookup of %s succeeded at %s (RED).", log_escape_nq(msr->mp, name_to_check), var->name); break; case 14: *error_msg = apr_psprintf(msr->r->pool, "RBL lookup of %s succeeded at %s (BLACK,GREY,RED).", log_escape_nq(msr->mp, name_to_check), var->name); break; case 255: *error_msg = apr_psprintf(msr->r->pool, "RBL lookup of %s succeeded at %s (DNS IS BLOCKED).", log_escape_nq(msr->mp, name_to_check), var->name); break; default: *error_msg = apr_psprintf(msr->r->pool, "RBL lookup of %s succeeded at %s (WHITE).", log_escape_nq(msr->mp, name_to_check), var->name); break; } set_match_to_tx(msr, capture, *error_msg, 0); } else if(strstr(rule->op_param,"spamhaus.org")) { switch(high8bits) { case 2: case 3: *error_msg = apr_psprintf(msr->r->pool, "RBL lookup of %s succeeded at %s (Static UBE sources).", log_escape_nq(msr->mp, name_to_check), var->name); break; case 4: case 5: case 6: case 7: *error_msg = apr_psprintf(msr->r->pool, "RBL lookup of %s succeeded at %s (Illegal 3rd party exploits).", log_escape_nq(msr->mp, name_to_check), var->name); break; case 10: case 11: *error_msg = apr_psprintf(msr->r->pool, "RBL lookup of %s succeeded at %s (Delivering unauthenticated SMTP email).", log_escape_nq(msr->mp, name_to_check), var->name); break; default: *error_msg = apr_psprintf(msr->r->pool, "RBL lookup of %s succeeded at %s.", log_escape_nq(msr->mp, name_to_check), var->name); break; } set_match_to_tx(msr, capture, *error_msg, 0); } else if(strstr(rule->op_param,"httpbl.org")) { char *respBl; int first, days, score, type; respBl = inet_ntoa(sa->sa.sin.sin_addr); if (sscanf(respBl, "%d.%d.%d.%d", &first, &days, &score, &type) != 4) { *error_msg = apr_psprintf(msr->r->pool, "RBL lookup of %s failed: bad response", log_escape_nq(msr->mp, name_to_check)); } else { if (first != 127) { *error_msg = apr_psprintf(msr->r->pool, "RBL lookup of %s failed: bad response", log_escape_nq(msr->mp, name_to_check)); } else { char *ptype; switch(type) { case 0: ptype = "Search Engine"; break; case 1: ptype = "Suspicious IP"; break; case 2: ptype = "Harvester IP"; break; case 3: ptype = "Suspicious harvester IP"; break; case 4: ptype = "Comment spammer IP"; break; case 5: ptype = "Suspicious comment spammer IP"; break; case 6: ptype = "Harvester and comment spammer IP"; break; case 7: ptype = "Suspicious harvester comment spammer IP"; break; default: ptype = " "; } *error_msg = apr_psprintf(msr->r->pool, "RBL lookup of %s succeeded at %s. %s: %d days since last activity, threat score %d", log_escape_nq(msr->mp, name_to_check), var->name, ptype, days, score); } } set_match_to_tx(msr, capture, *error_msg, 0); /* end of httpBl code */ } else { *error_msg = apr_psprintf(msr->r->pool, "RBL lookup of %s succeeded at %s.", log_escape_nq(msr->mp, name_to_check), var->name); set_match_to_tx(msr, capture, *error_msg, 0); } return 1; /* Match. */ } if (msr->txcfg->debuglog_level >= 5) { msr_log(msr, 5, "RBL lookup of %s failed at %s.", log_escape_nq(msr->mp, name_to_check), var->name); } /* No match. */ return 0; } /* inspectFile */ static int msre_op_inspectFile_init(msre_rule *rule, char **error_msg) { char *filename = (char *)rule->op_param; if (error_msg == NULL) return -1; *error_msg = NULL; if ((filename == NULL)||(is_empty_string(filename))) { *error_msg = apr_psprintf(rule->ruleset->mp, "Operator @inspectFile requires parameter."); return -1; } filename = resolve_relative_path(rule->ruleset->mp, rule->filename, filename); #if defined(WITH_LUA) /* ENH Write & use string_ends(s, e). */ if (strlen(rule->op_param) > 4) { char *p = filename + strlen(filename) - 4; if ((p[0] == '.')&&(p[1] == 'l')&&(p[2] == 'u')&&(p[3] == 'a')) { msc_script *script = NULL; /* Compile script. */ *error_msg = lua_compile(&script, filename, rule->ruleset->mp); if (*error_msg != NULL) return -1; rule->op_param_data = script; } } #endif if (rule->op_param_data == NULL) { /* ENH Verify the script exists and that we have * the rights to execute it. */ } return 1; } static int msre_op_inspectFile_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { if (error_msg == NULL) return -1; *error_msg = NULL; if (rule->op_param_data == NULL) { /* Execute externally, as native binary/shell script. */ char *script_output = NULL; char const *argv[5]; const char *approver_script = rule->op_param; const char *target_file = apr_pstrmemdup(msr->mp, var->value, var->value_len); if (msr->txcfg->debuglog_level >= 4) { msr_log(msr, 4, "Executing %s to inspect %s.", approver_script, target_file); } argv[0] = approver_script; argv[1] = target_file; argv[2] = NULL; if (apache2_exec(msr, approver_script, (const char **)argv, &script_output) <= 0) { *error_msg = apr_psprintf(msr->mp, "Execution of the approver script \"%s\" failed (invocation failed).", log_escape(msr->mp, approver_script)); return -1; } if (script_output == NULL) { *error_msg = apr_psprintf(msr->mp, "Execution of the approver script \"%s\" failed (no output).", log_escape(msr->mp, approver_script)); return -1; } if (script_output[0] != '1') { *error_msg = apr_psprintf(msr->mp, "File \"%s\" rejected by the approver script \"%s\": %s", log_escape(msr->mp, target_file), log_escape(msr->mp, approver_script), log_escape_nq(msr->mp, script_output)); return 1; /* Match. */ } } #if defined(WITH_LUA) else { /* Execute internally, as Lua script. */ char *target = apr_pstrmemdup(msr->mp, var->value, var->value_len); msc_script *script = (msc_script *)rule->op_param_data; int rc; rc = lua_execute(script, target, msr, rule, error_msg); if (rc < 0) { /* Error. */ return -1; } return rc; } #endif /* No match. */ return 0; } /* validateByteRange */ static int msre_op_validateByteRange_init(msre_rule *rule, char **error_msg) { char *p = NULL, *saveptr = NULL; char *table = NULL, *data = NULL; if (error_msg == NULL) return -1; *error_msg = NULL; if (rule->op_param == NULL) { *error_msg = apr_psprintf(rule->ruleset->mp, "Missing parameter for validateByteRange."); return -1; } /* Initialise. */ data = apr_pstrdup(rule->ruleset->mp, rule->op_param); rule->op_param_data = apr_pcalloc(rule->ruleset->mp, 32); if ((data == NULL)||(rule->op_param_data == NULL)) return -1; table = rule->op_param_data; /* Extract parameters and update table. */ p = apr_strtok(data, ",", &saveptr); while(p != NULL) { char *s = strstr(p, "-"); if (s == NULL) { /* Single value. */ int x = atoi(p); if ((x < 0)||(x > 255)) { *error_msg = apr_psprintf(rule->ruleset->mp, "Invalid range value: %d", x); return 0; } table[x>>3] = (table[x>>3] | (1 << (x & 0x7))); } else { /* Range. */ int start = atoi(p); int end = atoi(s + 1); if ((start < 0)||(start > 255)) { *error_msg = apr_psprintf(rule->ruleset->mp, "Invalid range start value: %d", start); return 0; } if ((end < 0)||(end > 255)) { *error_msg = apr_psprintf(rule->ruleset->mp, "Invalid range end value: %d", end); return 0; } if (start > end) { *error_msg = apr_psprintf(rule->ruleset->mp, "Invalid range: %d-%d", start, end); return 0; } while(start <= end) { table[start >> 3] = (table[start >> 3] | (1 << (start & 0x7))); start++; } } p = apr_strtok(NULL, ",", &saveptr); } return 1; } static int msre_op_validateByteRange_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { char *table = rule->op_param_data; unsigned int i, count; if (error_msg == NULL) return -1; *error_msg = NULL; if (table == NULL) { *error_msg = apr_psprintf(msr->mp, "Internal Error: validateByteRange table not " "initialised."); return -1; } /* Check every byte of the target to detect characters that are not allowed. */ count = 0; for(i = 0; i < var->value_len; i++) { int x = ((unsigned char *)var->value)[i]; if (!(table[x >> 3] & (1 << (x & 0x7)))) { if (msr->txcfg->debuglog_level >= 9) { msr_log(msr, 9, "Value %d in %s outside range: %s", x, var->name, rule->op_param); } count++; } } if (count == 0) return 0; /* Valid - no match. */ *error_msg = apr_psprintf(msr->mp, "Found %d byte(s) in %s outside range: %s.", count, var->name, rule->op_param); return 1; /* Invalid - match.*/ } /* validateUrlEncoding */ static int validate_url_encoding(const char *input, long int input_length) { int i; if ((input == NULL)||(input_length < 0)) return -1; i = 0; while (i < input_length) { if (input[i] == '%') { if (i + 2 >= input_length) { /* Not enough bytes. */ return -3; } else { /* Here we only decode a %xx combination if it is valid, * leaving it as is otherwise. */ char c1 = input[i + 1]; char c2 = input[i + 2]; if ( (((c1 >= '0')&&(c1 <= '9')) || ((c1 >= 'a')&&(c1 <= 'f')) || ((c1 >= 'A')&&(c1 <= 'F'))) && (((c2 >= '0')&&(c2 <= '9')) || ((c2 >= 'a')&&(c2 <= 'f')) || ((c2 >= 'A')&&(c2 <= 'F'))) ) { i += 3; } else { /* Non-hexadecimal characters used in encoding. */ return -2; } } } else { i++; } } return 1; } static int msre_op_validateUrlEncoding_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { int rc = validate_url_encoding(var->value, var->value_len); switch(rc) { case 1 : /* Encoding is valid */ *error_msg = apr_psprintf(msr->mp, "Valid URL Encoding at %s.", var->name); break; case -2 : *error_msg = apr_psprintf(msr->mp, "Invalid URL Encoding: Non-hexadecimal " "digits used at %s.", var->name); return 1; /* Invalid match. */ break; case -3 : *error_msg = apr_psprintf(msr->mp, "Invalid URL Encoding: Not enough characters " "at the end of input at %s.", var->name); return 1; /* Invalid match. */ break; case -1 : default : *error_msg = apr_psprintf(msr->mp, "Invalid URL Encoding: Internal Error (rc = %d) at %s", rc, var->name); return -1; break; } /* No match. */ return 0; } /* validateUtf8Encoding */ /* NOTE: This is over-commented for ease of verification */ static int detect_utf8_character(const unsigned char *p_read, unsigned int length) { int unicode_len = 0; unsigned int d = 0; unsigned char c; if (p_read == NULL) return UNICODE_ERROR_DECODING_ERROR; c = *p_read; /* If first byte begins with binary 0 it is single byte encoding */ if ((c & 0x80) == 0) { /* single byte unicode (7 bit ASCII equivilent) has no validation */ return 1; } /* If first byte begins with binary 110 it is two byte encoding*/ else if ((c & 0xE0) == 0xC0) { /* check we have at least two bytes */ if (length < 2) unicode_len = UNICODE_ERROR_CHARACTERS_MISSING; /* check second byte starts with binary 10 */ else if (((*(p_read + 1)) & 0xC0) != 0x80) unicode_len = UNICODE_ERROR_INVALID_ENCODING; else { unicode_len = 2; /* compute character number */ d = ((c & 0x1F) << 6) | (*(p_read + 1) & 0x3F); } } /* If first byte begins with binary 1110 it is three byte encoding */ else if ((c & 0xF0) == 0xE0) { /* check we have at least three bytes */ if (length < 3) unicode_len = UNICODE_ERROR_CHARACTERS_MISSING; /* check second byte starts with binary 10 */ else if (((*(p_read + 1)) & 0xC0) != 0x80) unicode_len = UNICODE_ERROR_INVALID_ENCODING; /* check third byte starts with binary 10 */ else if (((*(p_read + 2)) & 0xC0) != 0x80) unicode_len = UNICODE_ERROR_INVALID_ENCODING; else { unicode_len = 3; /* compute character number */ d = ((c & 0x0F) << 12) | ((*(p_read + 1) & 0x3F) << 6) | (*(p_read + 2) & 0x3F); } } /* If first byte begins with binary 11110 it is four byte encoding */ else if ((c & 0xF8) == 0xF0) { /* restrict characters to UTF-8 range (U+0000 - U+10FFFF)*/ if (c >= 0xF5) { return UNICODE_ERROR_RESTRICTED_CHARACTER; } /* check we have at least four bytes */ if (length < 4) unicode_len = UNICODE_ERROR_CHARACTERS_MISSING; /* check second byte starts with binary 10 */ else if (((*(p_read + 1)) & 0xC0) != 0x80) unicode_len = UNICODE_ERROR_INVALID_ENCODING; /* check third byte starts with binary 10 */ else if (((*(p_read + 2)) & 0xC0) != 0x80) unicode_len = UNICODE_ERROR_INVALID_ENCODING; /* check forth byte starts with binary 10 */ else if (((*(p_read + 3)) & 0xC0) != 0x80) unicode_len = UNICODE_ERROR_INVALID_ENCODING; else { unicode_len = 4; /* compute character number */ d = ((c & 0x07) << 18) | ((*(p_read + 1) & 0x3F) << 12) | ((*(p_read + 2) & 0x3F) < 6) | (*(p_read + 3) & 0x3F); } } /* any other first byte is invalid (RFC 3629) */ else { return UNICODE_ERROR_INVALID_ENCODING; } /* invalid UTF-8 character number range (RFC 3629) */ if ((d >= 0xD800) && (d <= 0xDFFF)) { return UNICODE_ERROR_RESTRICTED_CHARACTER; } /* check for overlong */ if ((unicode_len == 4) && (d < 0x010000)) { /* four byte could be represented with less bytes */ return UNICODE_ERROR_OVERLONG_CHARACTER; } else if ((unicode_len == 3) && (d < 0x0800)) { /* three byte could be represented with less bytes */ return UNICODE_ERROR_OVERLONG_CHARACTER; } else if ((unicode_len == 2) && (d < 0x80)) { /* two byte could be represented with less bytes */ return UNICODE_ERROR_OVERLONG_CHARACTER; } return unicode_len; } static int msre_op_validateUtf8Encoding_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { unsigned int i, bytes_left; bytes_left = var->value_len; for(i = 0; i < var->value_len;) { int rc = detect_utf8_character((unsigned char *)&var->value[i], bytes_left); switch(rc) { case UNICODE_ERROR_CHARACTERS_MISSING : *error_msg = apr_psprintf(msr->mp, "Invalid UTF-8 encoding: " "not enough bytes in character " "at %s. [offset \"%d\"]", var->name, i); return 1; break; case UNICODE_ERROR_INVALID_ENCODING : *error_msg = apr_psprintf(msr->mp, "Invalid UTF-8 encoding: " "invalid byte value in character " "at %s. [offset \"%d\"]", var->name, i); return 1; break; case UNICODE_ERROR_OVERLONG_CHARACTER : *error_msg = apr_psprintf(msr->mp, "Invalid UTF-8 encoding: " "overlong character detected " "at %s. [offset \"%d\"]", var->name, i); return 1; break; case UNICODE_ERROR_RESTRICTED_CHARACTER : *error_msg = apr_psprintf(msr->mp, "Invalid UTF-8 encoding: " "use of restricted character " "at %s. [offset \"%d\"]", var->name, i); return 1; break; case UNICODE_ERROR_DECODING_ERROR : *error_msg = apr_psprintf(msr->mp, "Error validating UTF-8 decoding " "at %s. [offset \"%d\"]", var->name, i); return 1; break; } if (rc <= 0) { *error_msg = apr_psprintf(msr->mp, "Internal error during UTF-8 validation " "at %s.", var->name); return 1; } i += rc; bytes_left -= rc; } return 0; } /* eq */ static int msre_op_eq_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { msc_string str; int left, right; char *target = NULL; if (error_msg == NULL) return -1; *error_msg = NULL; if ((var->value == NULL)||(rule->op_param == NULL)) { /* NULL values do not match anything. */ return 0; } str.value = (char *)rule->op_param; str.value_len = strlen(str.value); expand_macros(msr, &str, rule, msr->mp); target = apr_pstrmemdup(msr->mp, var->value, var->value_len); if (target == NULL) return -1; left = atoi(target); right = atoi(str.value); if (left != right) { /* No match. */ return 0; } else { *error_msg = apr_psprintf(msr->mp, "Operator EQ matched %d at %s.", right, var->name); /* Match. */ return 1; } } /* gt */ static int msre_op_gt_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { msc_string str; int left, right; char *target = NULL; if ((var->value == NULL)||(rule->op_param == NULL)) { /* NULL values do not match anything. */ return 0; } if (error_msg == NULL) return -1; *error_msg = NULL; if ((var->value == NULL)||(rule->op_param == NULL)) { /* NULL values do not match anything. */ return 0; } str.value = (char *)rule->op_param; str.value_len = strlen(str.value); expand_macros(msr, &str, rule, msr->mp); target = apr_pstrmemdup(msr->mp, var->value, var->value_len); if (target == NULL) return -1; left = atoi(target); right = atoi(str.value); if (left <= right) { /* No match. */ return 0; } else { *error_msg = apr_psprintf(msr->mp, "Operator GT matched %d at %s.", right, var->name); /* Match. */ return 1; } } /* lt */ static int msre_op_lt_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { msc_string str; int left, right; char *target = NULL; if ((var->value == NULL)||(rule->op_param == NULL)) { /* NULL values do not match anything. */ return 0; } if (error_msg == NULL) return -1; *error_msg = NULL; if ((var->value == NULL)||(rule->op_param == NULL)) { /* NULL values do not match anything. */ return 0; } str.value = (char *)rule->op_param; str.value_len = strlen(str.value); expand_macros(msr, &str, rule, msr->mp); target = apr_pstrmemdup(msr->mp, var->value, var->value_len); if (target == NULL) return -1; left = atoi(target); right = atoi(str.value); if (left >= right) { /* No match. */ return 0; } else { *error_msg = apr_psprintf(msr->mp, "Operator LT matched %d at %s.", right, var->name); /* Match. */ return 1; } } /* ge */ static int msre_op_ge_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { msc_string str; int left, right; char *target = NULL; if ((var->value == NULL)||(rule->op_param == NULL)) { /* NULL values do not match anything. */ return 0; } if (error_msg == NULL) return -1; *error_msg = NULL; if ((var->value == NULL)||(rule->op_param == NULL)) { /* NULL values do not match anything. */ return 0; } str.value = (char *)rule->op_param; str.value_len = strlen(str.value); expand_macros(msr, &str, rule, msr->mp); target = apr_pstrmemdup(msr->mp, var->value, var->value_len); if (target == NULL) return -1; left = atoi(target); right = atoi(str.value); if (left < right) { /* No match. */ return 0; } else { *error_msg = apr_psprintf(msr->mp, "Operator GE matched %d at %s.", right, var->name); /* Match. */ return 1; } } /* le */ static int msre_op_le_execute(modsec_rec *msr, msre_rule *rule, msre_var *var, char **error_msg) { msc_string str; int left, right; char *target = NULL; if ((var->value == NULL)||(rule->op_param == NULL)) { /* NULL values do not match anything. */ return 0; } if (error_msg == NULL) return -1; *error_msg = NULL; if ((var->value == NULL)||(rule->op_param == NULL)) { /* NULL values do not match anything. */ return 0; } str.value = (char *)rule->op_param; str.value_len = strlen(str.value); expand_macros(msr, &str, rule, msr->mp); target = apr_pstrmemdup(msr->mp, var->value, var->value_len); if (target == NULL) return -1; left = atoi(target); right = atoi(str.value); if (left > right) { /* No match. */ return 0; } else { *error_msg = apr_psprintf(msr->mp, "Operator LE matched %d at %s.", right, var->name); /* Match. */ return 1; } } /* -------------------------------------------------------------------------- */ /** * */ void msre_engine_register_default_operators(msre_engine *engine) { /* unconditionalMatch */ msre_engine_op_register(engine, "unconditionalMatch", NULL, msre_op_unconditionalmatch_execute ); /* noMatch */ msre_engine_op_register(engine, "noMatch", NULL, msre_op_nomatch_execute ); /* ipmatch */ msre_engine_op_register(engine, "ipmatch", msre_op_ipmatch_param_init, msre_op_ipmatch_execute ); /* ipmatchFromFile */ msre_engine_op_register(engine, "ipmatchFromFile", msre_op_ipmatchFromFile_param_init, msre_op_ipmatchFromFile_execute ); /* ipmatchf */ msre_engine_op_register(engine, "ipmatchf", msre_op_ipmatchFromFile_param_init, msre_op_ipmatchFromFile_execute ); /* rsub */ #if !defined(MSC_TEST) msre_engine_op_register(engine, "rsub", msre_op_rsub_param_init, msre_op_rsub_execute ); #endif /* MSC_TEST */ /* rx */ msre_engine_op_register(engine, "rx", msre_op_rx_param_init, msre_op_rx_execute ); /* validateEncyption */ msre_engine_op_register(engine, "validateHash", msre_op_validateHash_param_init, msre_op_validateHash_execute ); /* pm */ msre_engine_op_register(engine, "pm", msre_op_pm_param_init, msre_op_pm_execute ); /* pmFromFile */ msre_engine_op_register(engine, "pmFromFile", msre_op_pmFromFile_param_init, msre_op_pm_execute ); /* pmf */ msre_engine_op_register(engine, "pmf", msre_op_pmFromFile_param_init, msre_op_pm_execute ); /* within */ msre_engine_op_register(engine, "within", NULL, /* ENH init function to flag var substitution */ msre_op_within_execute ); /* contains */ msre_engine_op_register(engine, "contains", NULL, /* ENH init function to flag var substitution */ msre_op_contains_execute ); /* containsWord */ msre_engine_op_register(engine, "containsWord", NULL, /* ENH init function to flag var substitution */ msre_op_containsWord_execute ); /* detectSQLi */ msre_engine_op_register(engine, "detectSQLi", NULL, msre_op_detectSQLi_execute ); /* detectXSS */ msre_engine_op_register(engine, "detectXSS", NULL, msre_op_detectXSS_execute ); /* streq */ msre_engine_op_register(engine, "streq", NULL, /* ENH init function to flag var substitution */ msre_op_streq_execute ); /* beginsWith */ msre_engine_op_register(engine, "beginsWith", NULL, /* ENH init function to flag var substitution */ msre_op_beginsWith_execute ); /* endsWith */ msre_engine_op_register(engine, "endsWith", NULL, /* ENH init function to flag var substitution */ msre_op_endsWith_execute ); /* strmatch */ msre_engine_op_register(engine, "strmatch", msre_op_strmatch_param_init, msre_op_strmatch_execute ); /* validateDTD */ msre_engine_op_register(engine, "validateDTD", msre_op_validateDTD_init, msre_op_validateDTD_execute ); /* validateSchema */ msre_engine_op_register(engine, "validateSchema", msre_op_validateSchema_init, msre_op_validateSchema_execute ); /* verifyCC */ msre_engine_op_register(engine, "verifyCC", msre_op_verifyCC_init, msre_op_verifyCC_execute ); /* verifyCPF */ msre_engine_op_register(engine, "verifyCPF", msre_op_verifyCPF_init, msre_op_verifyCPF_execute ); /* verifySSN */ msre_engine_op_register(engine, "verifySSN", msre_op_verifySSN_init, msre_op_verifySSN_execute ); /* geoLookup */ msre_engine_op_register(engine, "geoLookup", NULL, msre_op_geoLookup_execute ); /* gsbLookup */ msre_engine_op_register(engine, "gsbLookup", msre_op_gsbLookup_param_init, msre_op_gsbLookup_execute ); /* rbl */ msre_engine_op_register(engine, "rbl", NULL, /* ENH init function to validate DNS server */ msre_op_rbl_execute ); /* inspectFile */ msre_engine_op_register(engine, "inspectFile", msre_op_inspectFile_init, msre_op_inspectFile_execute ); /* validateByteRange */ msre_engine_op_register(engine, "validateByteRange", msre_op_validateByteRange_init, msre_op_validateByteRange_execute ); /* validateUrlEncoding */ msre_engine_op_register(engine, "validateUrlEncoding", NULL, msre_op_validateUrlEncoding_execute ); /* validateUtf8Encoding */ msre_engine_op_register(engine, "validateUtf8Encoding", NULL, msre_op_validateUtf8Encoding_execute ); /* eq */ msre_engine_op_register(engine, "eq", NULL, msre_op_eq_execute ); /* gt */ msre_engine_op_register(engine, "gt", NULL, msre_op_gt_execute ); /* lt */ msre_engine_op_register(engine, "lt", NULL, msre_op_lt_execute ); /* le */ msre_engine_op_register(engine, "le", NULL, msre_op_le_execute ); /* ge */ msre_engine_op_register(engine, "ge", NULL, msre_op_ge_execute ); }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #ifndef Common_hpp #define Common_hpp #include "BuildXLSandboxShared.hpp" #define REPORT_QUEUE_SUCCESS 0x1000 #define REPORT_QUEUE_CONNECTION_ERROR 0x1001 #define REPORT_QUEUE_DEQUEUE_ERROR 0x1002 typedef enum { Kext, EndpointSecurity } ConnectionType; extern "C" { void SetLogger(os_log_t newLogger); /*! * Normalized path is stored in 'buffer'. That buffer must be 'bufferSize' bytes long. * * @param path Path to normalize and hash. * @param buffer Buffer where the normalized path is stored. * @param bufferSize The size of 'buffer' in bytes. * @result Hash of the normalized path. */ int NormalizePathAndReturnHash(const char *path, char *buffer, int bufferSize); typedef void (__cdecl *AccessReportCallback)(AccessReport, int); bool SendPipStarted(const pid_t processId, pipid_t pipId, const char *const famBytes, int famBytesLength, ConnectionType type, void *connection); bool SendPipProcessTerminated(pipid_t pipId, pid_t processId, ConnectionType type, void *connection); }; #endif /* Common_hpp */
#include "LBDefinitions.h" #include "computeCellValues.h" #include <stdio.h> #include <omp.h> void computeDensity(const float *const currentCell, float *density){ /* * Computes the macroscopic density within currentCell * rho(x,t) = sum(f_i, i=0:Q-1) */ int i; *density = 0; for (i=0; i<Q; i++) { *density += currentCell[i]; } } void computeVelocity(const float * const currentCell, const float * const density, float *velocity){ /* * Computes the velocity within currentCell * u(x,t) = sum(f[i] * c[i] for i in [0:Q-1]) / rho */ int i; float density_inv = 1 / (*density); velocity[0] = 0; velocity[1] = 0; velocity[2] = 0; for (i=0; i<Q; i++) { velocity[0] += LATTICEVELOCITIES[i][0] * currentCell[i]; velocity[1] += LATTICEVELOCITIES[i][1] * currentCell[i]; velocity[2] += LATTICEVELOCITIES[i][2] * currentCell[i]; } velocity[0] *= density_inv; velocity[1] *= density_inv; velocity[2] *= density_inv; } void computeFeq(const float * const density, const float * const velocity, float * const feq){ /* * feq[i] = w[i] * rho * (1 + c_i*u / (c_s^2) + ... */ int i; float ci_dot_u_cs2[Q]; float ci0[Q], ci1[Q], ci2[Q], a1[Q], a2[Q], a3[Q]; const float u0 = velocity[0]; const float u1 = velocity[1]; const float u2 = velocity[2]; const float u_dot_u_cs2 = (u0*u0 + u1*u1 + u2*u2) * 0.5 * C_S2_inv; #pragma GCC ivdep for (i=0; i<Q/2 + 1; i++) { ci0[i] = LATTICEVELOCITIES[i][0]; ci1[i] = LATTICEVELOCITIES[i][1]; ci2[i] = LATTICEVELOCITIES[i][2]; } #pragma GCC ivdep for (i=0; i<Q/2 + 1; i++) { a1[i] = ci0[i]*u0; a2[i] = ci1[i]*u1; a3[i] = ci2[i]*u2; ci_dot_u_cs2[i] = (a1[i] + a2[i] + a3[i]) * C_S2_inv; feq[i] = (1 + ci_dot_u_cs2[i] + (ci_dot_u_cs2[i] * ci_dot_u_cs2[i]) * 0.5 - u_dot_u_cs2) * (*density)* LATTICEWEIGHTS[i]; } #pragma GCC ivdep for (i = 0; i < Q / 2; i++) { feq[Q - i - 1] = feq[i] - 2 * ci_dot_u_cs2[i] * (*density) * LATTICEWEIGHTS[i]; } }
/* * This file is part of the KDE libraries * Copyright (C) 1999-2001 <NAME> (<EMAIL>) * Copyright (C) 2001 <NAME> (<EMAIL>) * Copyright (C) 2003, 2004, 2005, 2007 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #ifndef KJS_VALUE_H #define KJS_VALUE_H #include "JSImmediate.h" #include "ustring.h" #include "collector.h" #include <wtf/Noncopyable.h> #include <stddef.h> // for size_t #ifndef NDEBUG // protection against problems if committing with KJS_VERBOSE on // Uncomment this to enable very verbose output from KJS //#define KJS_VERBOSE // Uncomment this to debug memory allocation and garbage collection //#define KJS_DEBUG_MEM #endif namespace KJS { struct ClassInfo; class ExecState; class JSObject; class JSCell; /** * JSValue is the base type for all primitives (Undefined, Null, Boolean, * String, Number) and objects in ECMAScript. * * Note: you should never inherit from JSValue as it is for primitive types * only (all of which are provided internally by KJS). Instead, inherit from * JSObject. */ class KJS_EXPORT JSValue : Noncopyable { friend class JSCell; // so it can derive from this class friend class Collector; // so it can call asCell() private: JSValue(); virtual ~JSValue(); public: // Querying the type. JSType type() const; bool isUndefined() const; bool isNull() const; bool isUndefinedOrNull() const; bool isBoolean() const; bool isNumber() const; bool isString() const; bool isObject() const; bool isObject(const ClassInfo *) const; // Extracting the value. bool getBoolean(bool &) const; bool getBoolean() const; // false if not a boolean bool getNumber(double &) const; double getNumber() const; // NaN if not a number bool getString(UString &) const; UString getString() const; // null string if not a string JSObject *getObject(); // NULL if not an object const JSObject *getObject() const; // NULL if not an object // Extracting integer values. bool getUInt32(uint32_t &) const; bool getTruncatedInt32(int32_t &) const; bool getTruncatedUInt32(uint32_t &) const; JSValue *getByIndex(ExecState *exec, unsigned propertyName) const; // Basic conversions. JSValue *toPrimitive(ExecState *exec, JSType preferredType = UnspecifiedType) const; bool getPrimitiveNumber(ExecState *exec, double &number, JSValue *&value); bool toBoolean(ExecState *exec) const; double toNumber(ExecState *exec) const; JSValue *toJSNumber(ExecState *) const; // Fast path for when you expect that the value is an immediate number. UString toString(ExecState *exec) const; JSObject *toObject(ExecState *exec) const; // Integer conversions. double toInteger(ExecState *) const; double toIntegerPreserveNaN(ExecState *) const; int32_t toInt32(ExecState *) const; int32_t toInt32(ExecState *, bool &ok) const; uint32_t toUInt32(ExecState *) const; uint32_t toUInt32(ExecState *, bool &ok) const; uint16_t toUInt16(ExecState *exec) const; // These are identical logic to above, and faster than jsNumber(number)->toInt32(exec) static int32_t toInt32(double); static int32_t toUInt32(double); // Floating point conversions. float toFloat(ExecState *) const; // Object-level properties... /** * Whether or not the value implements the call() method. If it does, this also * implies this is an object, and hence it can be cast to a JSObject * and the call method can be invoked * * @return true if this is an object implementing the call() method, otherwise * false */ bool implementsCall() const; // Garbage collection. void mark(); bool marked() const; static int32_t toInt32SlowCase(double, bool &ok); static uint32_t toUInt32SlowCase(double, bool &ok); private: int32_t toInt32SlowCase(ExecState *, bool &ok) const; uint32_t toUInt32SlowCase(ExecState *, bool &ok) const; // Implementation details. JSCell *asCell(); const JSCell *asCell() const; // emulate Q_DISABLE_COPY to avoid msvc linker errors #if !defined(_MSC_VER) || !defined(MAKE_KJS_LIB) // Give a compile time error if we try to copy one of these. JSValue(const JSValue &); JSValue &operator=(const JSValue &); #endif }; class KJS_EXPORT JSCell : public JSValue { friend class Collector; friend class NumberImp; friend class StringImp; friend class JSObject; friend class GetterSetterImp; private: explicit JSCell(); virtual ~JSCell(); public: // Querying the type. virtual JSType type() const = 0; bool isNumber() const; bool isString() const; bool isObject() const; bool isObject(const ClassInfo *) const; // Extracting the value. bool getNumber(double &) const; double getNumber() const; // NaN if not a number bool getString(UString &) const; UString getString() const; // null string if not a string JSObject *getObject(); // NULL if not an object const JSObject *getObject() const; // NULL if not an object // Extracting integer values. virtual bool getUInt32(uint32_t &) const; virtual bool getTruncatedInt32(int32_t &) const; virtual bool getTruncatedUInt32(uint32_t &) const; // Basic conversions. virtual JSValue *toPrimitive(ExecState *exec, JSType preferredType = UnspecifiedType) const = 0; virtual bool getPrimitiveNumber(ExecState *exec, double &number, JSValue *&value) = 0; virtual bool toBoolean(ExecState *exec) const = 0; virtual double toNumber(ExecState *exec) const = 0; virtual UString toString(ExecState *exec) const = 0; virtual JSObject *toObject(ExecState *exec) const = 0; // Higher-level (object-like) properties: virtual bool implementsCall() const; // Garbage collection. void *operator new(size_t); virtual void mark(); bool marked() const; }; KJS_EXPORT JSValue *jsNumberCell(double); KJS_EXPORT JSCell *jsString(); // returns empty string KJS_EXPORT JSCell *jsString(const UString &); // returns empty string if passed null string KJS_EXPORT JSCell *jsString(const char * = ""); // returns empty string if passed 0 KJS_EXPORT JSCell *jsString(const char *s, int len); // should be used for strings that are owned by an object that will // likely outlive the JSValue this makes, such as the parse tree or a // DOM object that contains a UString JSCell *jsOwnedString(const UString &); inline JSValue *jsUndefined() { return JSImmediate::undefinedImmediate(); } inline JSValue *jsNull() { return JSImmediate::nullImmediate(); } inline JSValue *jsNaN() { static const union { uint64_t bits; double d; } nan = { 0x7ff80000ULL << 32 }; return jsNumberCell(nan.d); } inline JSValue *jsBoolean(bool b) { return b ? JSImmediate::trueImmediate() : JSImmediate::falseImmediate(); } ALWAYS_INLINE JSValue *jsNumber(double d) { JSValue *v = JSImmediate::from(d); return v ? v : jsNumberCell(d); } ALWAYS_INLINE JSValue *jsNumber(int i) { JSValue *v = JSImmediate::from(i); return v ? v : jsNumberCell(i); } ALWAYS_INLINE JSValue *jsNumber(unsigned i) { JSValue *v = JSImmediate::from(i); return v ? v : jsNumberCell(i); } ALWAYS_INLINE JSValue *jsNumber(long i) { JSValue *v = JSImmediate::from(i); return v ? v : jsNumberCell(i); } ALWAYS_INLINE JSValue *jsNumber(unsigned long i) { JSValue *v = JSImmediate::from(i); return v ? v : jsNumberCell(i); } ALWAYS_INLINE JSValue *jsNumber(long long i) { JSValue *v = JSImmediate::from(i); return v ? v : jsNumberCell(static_cast<double>(i)); } ALWAYS_INLINE JSValue *jsNumber(unsigned long long i) { JSValue *v = JSImmediate::from(i); return v ? v : jsNumberCell(static_cast<double>(i)); } ALWAYS_INLINE JSValue *jsNumberFromAnd(ExecState *exec, JSValue *v1, JSValue *v2) { if (JSImmediate::areBothImmediateNumbers(v1, v2)) { return JSImmediate::andImmediateNumbers(v1, v2); } return jsNumber(v1->toInt32(exec) & v2->toInt32(exec)); } inline JSValue::JSValue() { } inline JSValue::~JSValue() { } inline JSCell::JSCell() { } inline JSCell::~JSCell() { } inline bool JSCell::isNumber() const { return type() == NumberType; } inline bool JSCell::isString() const { return type() == StringType; } inline bool JSCell::isObject() const { return type() == ObjectType; } inline bool JSCell::marked() const { return Collector::isCellMarked(this); } inline void JSCell::mark() { return Collector::markCell(this); } ALWAYS_INLINE JSCell *JSValue::asCell() { ASSERT(!JSImmediate::isImmediate(this)); return static_cast<JSCell *>(this); } ALWAYS_INLINE const JSCell *JSValue::asCell() const { ASSERT(!JSImmediate::isImmediate(this)); return static_cast<const JSCell *>(this); } inline bool JSValue::isUndefined() const { return this == jsUndefined(); } inline bool JSValue::isNull() const { return this == jsNull(); } inline bool JSValue::isUndefinedOrNull() const { return JSImmediate::isUndefinedOrNull(this); } inline bool JSValue::isBoolean() const { return JSImmediate::isBoolean(this); } inline bool JSValue::isNumber() const { return JSImmediate::isNumber(this) || (!JSImmediate::isImmediate(this) && asCell()->isNumber()); } inline bool JSValue::isString() const { return !JSImmediate::isImmediate(this) && asCell()->isString(); } inline bool JSValue::isObject() const { return !JSImmediate::isImmediate(this) && asCell()->isObject(); } inline bool JSValue::getBoolean(bool &v) const { if (JSImmediate::isBoolean(this)) { v = JSImmediate::toBoolean(this); return true; } return false; } inline bool JSValue::getBoolean() const { return JSImmediate::isBoolean(this) ? JSImmediate::toBoolean(this) : false; } inline bool JSValue::getNumber(double &v) const { if (JSImmediate::isImmediate(this)) { return JSImmediate::getNumber(this, v); } return asCell()->getNumber(v); } inline double JSValue::getNumber() const { return JSImmediate::isImmediate(this) ? JSImmediate::getNumber(this) : asCell()->getNumber(); } inline bool JSValue::getString(UString &s) const { return !JSImmediate::isImmediate(this) && asCell()->getString(s); } inline UString JSValue::getString() const { return JSImmediate::isImmediate(this) ? UString() : asCell()->getString(); } inline JSObject *JSValue::getObject() { return JSImmediate::isImmediate(this) ? nullptr : asCell()->getObject(); } inline const JSObject *JSValue::getObject() const { return JSImmediate::isImmediate(this) ? nullptr : asCell()->getObject(); } ALWAYS_INLINE bool JSValue::getUInt32(uint32_t &v) const { return JSImmediate::isImmediate(this) ? JSImmediate::getUInt32(this, v) : asCell()->getUInt32(v); } ALWAYS_INLINE bool JSValue::getTruncatedInt32(int32_t &v) const { return JSImmediate::isImmediate(this) ? JSImmediate::getTruncatedInt32(this, v) : asCell()->getTruncatedInt32(v); } inline bool JSValue::getTruncatedUInt32(uint32_t &v) const { return JSImmediate::isImmediate(this) ? JSImmediate::getTruncatedUInt32(this, v) : asCell()->getTruncatedUInt32(v); } inline void JSValue::mark() { ASSERT(!JSImmediate::isImmediate(this)); // callers should check !marked() before calling mark() asCell()->mark(); } inline bool JSValue::marked() const { return JSImmediate::isImmediate(this) || asCell()->marked(); } inline JSType JSValue::type() const { return JSImmediate::isImmediate(this) ? JSImmediate::type(this) : asCell()->type(); } inline JSValue *JSValue::toPrimitive(ExecState *exec, JSType preferredType) const { return JSImmediate::isImmediate(this) ? const_cast<JSValue *>(this) : asCell()->toPrimitive(exec, preferredType); } inline bool JSValue::getPrimitiveNumber(ExecState *exec, double &number, JSValue *&value) { if (JSImmediate::isImmediate(this)) { number = JSImmediate::toDouble(this); value = this; return true; } return asCell()->getPrimitiveNumber(exec, number, value); } inline bool JSValue::toBoolean(ExecState *exec) const { return JSImmediate::isImmediate(this) ? JSImmediate::toBoolean(this) : asCell()->toBoolean(exec); } ALWAYS_INLINE double JSValue::toNumber(ExecState *exec) const { return JSImmediate::isImmediate(this) ? JSImmediate::toDouble(this) : asCell()->toNumber(exec); } ALWAYS_INLINE JSValue *JSValue::toJSNumber(ExecState *exec) const { return JSImmediate::isNumber(this) ? const_cast<JSValue *>(this) : jsNumber(this->toNumber(exec)); } inline UString JSValue::toString(ExecState *exec) const { return JSImmediate::isImmediate(this) ? JSImmediate::toString(this) : asCell()->toString(exec); } inline JSObject *JSValue::toObject(ExecState *exec) const { return JSImmediate::isImmediate(this) ? JSImmediate::toObject(this, exec) : asCell()->toObject(exec); } ALWAYS_INLINE int32_t JSValue::toInt32(ExecState *exec) const { int32_t i; if (getTruncatedInt32(i)) { return i; } bool ok; return toInt32SlowCase(exec, ok); } inline uint32_t JSValue::toUInt32(ExecState *exec) const { uint32_t i; if (getTruncatedUInt32(i)) { return i; } bool ok; return toUInt32SlowCase(exec, ok); } inline int32_t JSValue::toInt32(double val) { if (!(val >= -2147483648.0 && val < 2147483648.0)) { bool ignored; return toInt32SlowCase(val, ignored); } return static_cast<int32_t>(val); } inline int32_t JSValue::toUInt32(double val) { if (!(val >= 0.0 && val < 4294967296.0)) { bool ignored; return toUInt32SlowCase(val, ignored); } return static_cast<uint32_t>(val); } inline int32_t JSValue::toInt32(ExecState *exec, bool &ok) const { int32_t i; if (getTruncatedInt32(i)) { ok = true; return i; } return toInt32SlowCase(exec, ok); } inline uint32_t JSValue::toUInt32(ExecState *exec, bool &ok) const { uint32_t i; if (getTruncatedUInt32(i)) { ok = true; return i; } return toUInt32SlowCase(exec, ok); } inline bool JSValue::implementsCall() const { if (JSImmediate::isImmediate(this)) { return false; // immediate values are never calleable. } else { return asCell()->implementsCall(); } } } // namespace #endif // KJS_VALUE_H
<reponame>so61pi/examples #ifndef CMATH_FACTORY_H #define CMATH_FACTORY_H #include <atomic> #include <Windows.h> #include <comdef.h> #include "CMath.h" #include "Global.h" // // // class CMathFactory : public IClassFactory { public: // IUnknown virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) override; virtual ULONG STDMETHODCALLTYPE AddRef(void) override; virtual ULONG STDMETHODCALLTYPE Release(void) override; // IClassFactory virtual HRESULT STDMETHODCALLTYPE CreateInstance(_In_opt_ IUnknown *pUnkOuter, _In_ REFIID riid, _COM_Outptr_ void **ppvObject) override; virtual HRESULT STDMETHODCALLTYPE LockServer(BOOL fLock) override; }; #endif // CMATH_FACTORY_H
#pragma once #include <SFML/Graphics.hpp> class Platform { sf::Texture texture; sf::Sprite sprite; public: Platform() { this->texture.loadFromFile("platform.png"); this->sprite.setTexture(texture); }; void show() { RectangleShape rectangle(Vector2f(70.f, 100.f)); rectangle.move(165, 150); rectangle.setFillColor(Color(175, 180, 240)); } ~Platform(){} };
<reponame>Ravf95/12h<gh_stars>1-10 /* The MIT License (MIT) Copyright (c) 2017 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Author: Rodrigo <Ravf> Villalba */ #if !defined _H_F_GAME_ #define _H_F_GAME_ #include "f_fichas.h" // @SUB-RUTINA : f_game_get_turno() // @UTILIDAD : obtiene el turno actual. // @PARAMETROS : ninguno. // @RETORNO : el turno. guint8 f_game_get_turno(void); // @SUB-RUTINA : f_game_get_jugadas() // @UTILIDAD : obtiene el número de jugadas en el tablero. // @PARAMETROS : ninguno. // @RETORNO : ninguno. guint16 f_game_get_jugadas(void); // @SUB-RUTINA : f_game_set_turno() // @UTILIDAD : asigna el turno actual. // @PARAMETROS : i > el turno. // @RETORNO : ninguno. void f_game_set_turno(guint16 i); // @SUB-RUTINA : f_game_next_turno() // @UTILIDAD : asigna el siguiente turno. // @PARAMETROS : ninguno. // @RETORNO : ninguno. void f_game_next_turno(void); // @SUB-RUTINA : f_game_count_jugadas() // @UTILIDAD : cuenta la cantidad de jugadas en el tablero. // @PARAMETROS : ninguno. // @RETORNO : ninguno. void f_game_count_jugadas(void); // @SUB-RUTINA : f_game_get_adv() // @UTILIDAD : obtiene el adversario a partir del turno actual. // @PARAMETROS : ninguno. // @RETORNO : el adversario. guint8 f_game_get_adv(void); // @SUB-RUTINA : f_game_terminar_turno() // @UTILIDAD : llamar a subrutinas que son necesarias // para finalizar correctamente el turno // de un jugador. // @PARAMETROS : ninguno. // @RETORNO : ninguno. void f_game_terminar_turno(void); // @SUB-RUTINA : f_game_get_config() // @UTILIDAD : verifica si existe una // configuración de juego. // @PARAMETROS : ninguno. // @RETORNO : TRUE > no existe una configuracíon. // FALSE > existe una configuración. gboolean f_game_get_config(void); // @SUB-RUTINA : f_game_set_config() // @UTILIDAD : establer o no, que existe una configuración // de juego. // @PARAMETROS : status > estado de la configuración del juego. // @RETORNO : ninguno. void f_game_set_config(gboolean status); // @SUB-RUTINA : f_game_over(guint8 ) // @UTILIDAD : establecer el fin de juego. // @PARAMETROS : r > razón de fin de juego. // winner > el jugador ganador. // loser > el jugador perdedor. // @RETORNO : ninguno. void f_game_over(guint8 winner, guint8 loser, guint8 r); // todavía quedan fichas a mover de // los tablero verticales. #define GAME_VTABLE_NOT_EMPTY (f_game_get_jugadas() < (F_FICHAS_N * 2)) #endif // _H_F_GAME_
// // PEViewController.h // ParserExample // // Created by <NAME> on 9/6/14. // Copyright (c) 2014 RCPD. All rights reserved. // #import <UIKit/UIKit.h> @import MapKit; #import "GSNParser.h" @interface PEViewController : UIViewController <GSNParserDelegate, MKMapViewDelegate> @end
#ifndef QINSTALL_H #define QINSTALL_H #include <QMainWindow> namespace Ui { class QInstall; } class QInstall : public QMainWindow { Q_OBJECT public: explicit QInstall(QWidget *parent = 0); ~QInstall(); private slots: void on_installbtn_clicked(); void on_btnRemove_clicked(); void on_btnAdd_clicked(); void on_btnCreate_clicked(); void on_btnOpen_clicked(); void on_btnDecompress_clicked(); void on_btnBrowse_clicked(); void on_btnInstall_clicked(); // int getExecutablePath(char* szBuff, unsigned long ulBufferLen); // int linuxextract(QString file); private: Ui::QInstall *ui; }; #endif // QINSTALL_H
<filename>freebsd5/sys/dev/sio/sio_ebus.c /*- * Copyright (c) 2001 by <NAME> <<EMAIL>>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: src/sys/dev/sio/sio_ebus.c,v 1.4 2003/08/23 00:11:16 imp Exp $"); #include <sys/param.h> #include <sys/systm.h> #include <sys/bus.h> #include <sys/kernel.h> #include <sys/timepps.h> #include <sys/tty.h> #include <machine/bus.h> #include <dev/sio/siovar.h> #include <dev/ofw/openfirm.h> #include <sparc64/ebus/ebusvar.h> int sio_ofw_inlist(char *name, char *list[]); static int sio_ebus_attach(device_t dev); static int sio_ebus_probe(device_t dev); static device_method_t sio_ebus_methods[] = { /* Device interface */ DEVMETHOD(device_probe, sio_ebus_probe), DEVMETHOD(device_attach, sio_ebus_attach), { 0, 0 } }; static driver_t sio_ebus_driver = { sio_driver_name, sio_ebus_methods, 0, }; DRIVER_MODULE(sio, ebus, sio_ebus_driver, sio_devclass, 0, 0); /* Needed for EBus attach and sparc64 console support */ char *sio_ofw_names[] = { "serial", "su", "su_pnp", NULL }; char *sio_ofw_compat[] = { "su", "su16550", NULL }; int sio_ofw_inlist(name, list) char *name; char *list[]; { int i; if (name == NULL) return (0); for (i = 0; list[i] != NULL; i++) { if (strcmp(name, list[i]) == 0) return (1); } return (0); } static int sio_ebus_probe(dev) device_t dev; { char *n; n = ebus_get_name(dev); if (!sio_ofw_inlist(n, sio_ofw_names) && (strcmp(n, "serial") != 0 || !sio_ofw_inlist(ebus_get_compat(dev), sio_ofw_compat))) return (ENXIO); /* Do not probe IRQ - isa_irq_pending() does not work for ebus. */ return (sioprobe(dev, 0, 0UL, 1)); } static int sio_ebus_attach(dev) device_t dev; { return (sioattach(dev, 0, 0UL)); }
<reponame>hamiltonjr/ABookOnC /** * Exercise 06. */ #include <stdio.h> int main() { double x, y = 0; // x = inf. x = 1 / y; printf("\tx = %f\n", x); return 0; }
<gh_stars>1-10 /* object.c - writes RT-11 compatible .OBJ files. Ref: RT-11 Software Support Manual, File Formats. */ /* Copyright (c) 2001, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: o Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. o 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. o Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include "rad50.h" #include "object.h" #include "macro11.h" /* writerec writes "formatted binary records." Each is preceeded by any number of 0 bytes, begins with a 1,0 pair, followed by 2 byte length, followed by data, followed by 1 byte negative checksum. */ static int writerec(FILE *fp, char *data, int len) { int chksum; /* Checksum is negative sum of all bytes including header and length */ int i; unsigned hdrlen = len + 4; if(fp == NULL) return 1; /* Silently ignore this attempt to write. */ chksum = 0; if(fputc(FBR_LEAD1, fp) == EOF) /* All recs begin with 1,0 */ return 0; chksum -= FBR_LEAD1; if(fputc(FBR_LEAD2, fp) == EOF) return 0; chksum -= FBR_LEAD2; i = hdrlen & 0xff; /* length, lsb */ chksum -= i; if(fputc(i, fp) == EOF) return 0; i = (hdrlen >> 8) & 0xff; /* length, msb */ chksum -= i; if(fputc(i, fp) == EOF) return 0; i = fwrite(data, 1, len, fp); if(i < len) return 0; while(len > 0) /* All the data bytes */ { chksum -= *data++ & 0xff; len--; } chksum &= 0xff; fputc(chksum, fp); /* Followed by the checksum byte */ return 1; /* Worked okay. */ } /* gsd_init - prepare a GSD prior to writing GSD records */ void gsd_init(GSD *gsd, FILE *fp) { gsd->fp = fp; gsd->buf[0] = OBJ_GSD; /* GSD records start with 1,0 */ gsd->buf[1] = 0; gsd->offset = 2; /* Offset for further additions */ } /* gsd_flush - write buffered GSD records */ int gsd_flush(GSD *gsd) { if(gsd->offset > 2) { if(!writerec(gsd->fp, gsd->buf, gsd->offset)) return 0; gsd_init(gsd, gsd->fp); } return 1; } /* gsd_write - buffers a GSD record */ /* All GSD entries have the following 8 byte format: */ /* 4 bytes RAD50 name */ /* 1 byte flags */ /* 1 byte type */ /* 2 bytes value */ static int gsd_write(GSD *gsd, char *name, int flags, int type, int value) { char *cp; unsigned radtbl[2]; if(gsd->offset > sizeof(gsd->buf) - 8) { if(!gsd_flush(gsd)) return 0; } rad50x2(name, radtbl); cp = gsd->buf + gsd->offset; *cp++ = radtbl[0] & 0xff; *cp++ = (radtbl[0] >> 8) & 0xff; *cp++ = radtbl[1] & 0xff; *cp++ = (radtbl[1] >> 8) & 0xff; *cp++ = flags; *cp++ = type; *cp++ = value & 0xff; *cp = (value >> 8) & 0xff; gsd->offset += 8; return 1; } /* gsd_mod - Write module name to GSD */ int gsd_mod(GSD *gsd, char *modname) { return gsd_write(gsd, modname, 0, GSD_MODNAME, 0); } /* gsd_csect - Write a control section name & size to the GSD */ int gsd_csect(GSD *gsd, char *sectname, int size) { return gsd_write(gsd, sectname, 0, GSD_CSECT, size); } /* gsd_intname - Write an internal symbol (ignored by RT-11 linker) */ int gsd_intname(GSD *gsd, char *name, unsigned value) { return gsd_write(gsd, name, 0, GSD_ISN, value); } /* gsd_xfer - Write a program transfer address to GSD */ int gsd_xfer(GSD *gsd, char *name, unsigned value) { return gsd_write(gsd, name, 010, GSD_XFER, value); } /* gsd_global - Write a global definition or reference to GSD */ /* Caller must be aware of the proper flags. */ int gsd_global(GSD *gsd, char *name, int flags, unsigned value) { return gsd_write(gsd, name, flags, GSD_GLOBAL, value); } /* Write a program section to the GSD */ /* Caller must be aware of the proper flags. */ int gsd_psect(GSD *gsd, char *name, int flags, int size) { return gsd_write(gsd, name, flags, GSD_PSECT, size); } /* Write program ident to GSD */ int gsd_ident(GSD *gsd, char *name) { return gsd_write(gsd, name, 0, GSD_IDENT, 0); } /* Write virtual array declaration to GSD */ int gsd_virt(GSD *gsd, char *name, int size) { return gsd_write(gsd, name, 0, GSD_VSECT, size); } /* Write ENDGSD record */ int gsd_end(GSD *gsd) { gsd->buf[0] = OBJ_ENDGSD; gsd->buf[1] = 0; return writerec(gsd->fp, gsd->buf, 2); } /* TEXT and RLD record handling */ /* TEXT records contain the plain binary of the program. An RLD record refers to the prior TEXT record, giving relocation information. */ /* text_init prepares a TEXT_RLD prior to writing */ void text_init(TEXT_RLD *tr, FILE *fp, unsigned addr) { tr->fp = fp; tr->text[0] = OBJ_TEXT; /* text records begin with 3, 0 */ tr->text[1] = 0; tr->text[2] = addr & 0xff; /* and are followed by load address */ tr->text[3] = (addr >> 8) & 0xff; tr->txt_offset = 4; /* Here's where recording new text will begin */ tr->rld[0] = OBJ_RLD; /* RLD records begin with 4, 0 */ tr->rld[1] = 0; tr->txt_addr = addr; tr->rld_offset = 2; /* And are followed by RLD entries */ } /* text_flush - flushes buffer TEXT and RLD records. */ int text_flush(TEXT_RLD *tr) { if(tr->txt_offset > 4) { if(!writerec(tr->fp, tr->text, tr->txt_offset)) return 0; } if(tr->rld_offset > 2) { if(!writerec(tr->fp, tr->rld, tr->rld_offset)) return 0; } return 1; } /* Used to ensure that TEXT and RLD information will be in adjacent records. If not enough space exists in either buffer, both are flushed. */ static int text_fit(TEXT_RLD *tr, unsigned addr, int txtsize, int rldsize) { if(tr->txt_offset + txtsize <= sizeof(tr->text) && tr->rld_offset + rldsize <= sizeof(tr->rld) && (txtsize == 0 || tr->txt_addr + tr->txt_offset - 4 == addr)) return 1; /* All's well. */ if(!text_flush(tr)) return 0; text_init(tr, tr->fp, addr); return 1; } /* text_word_i - internal text_word. Used when buffer space is already assured. */ static void text_word_i(TEXT_RLD *tr, unsigned w, int size) { tr->text[tr->txt_offset++] = w & 0xff; if(size > 1) tr->text[tr->txt_offset++] = (w >> 8) & 0xff; } /* text_word - write constant word to text */ int text_word(TEXT_RLD *tr, unsigned *addr, int size, unsigned word) { if(!text_fit(tr, *addr, size, 0)) return 0; text_word_i(tr, word, size); *addr += size; /* Update the caller's DOT */ return 1; /* say "ok". */ } /* rld_word - adds a word to the RLD information. */ static void rld_word(TEXT_RLD *tr, unsigned wd) { tr->rld[tr->rld_offset++] = wd & 0xff; tr->rld[tr->rld_offset++] = (wd >> 8) & 0xff; } /* rld_byte - adds a byte to rld information. */ static void rld_byte(TEXT_RLD *tr, unsigned byte) { tr->rld[tr->rld_offset++] = byte & 0xff; } /* rld_code - write the typical RLD first-word code. Encodes the given address as the offset into the prior TEXT record. */ static void rld_code(TEXT_RLD *tr, unsigned code, unsigned addr, int size) { unsigned offset = addr - tr->txt_addr + 4; rld_word(tr, code | offset << 8 | (size == 1 ? 0200 : 0)); } /* rld_code_naddr - typical RLD entries refer to a text address. This one is used when the RLD code does not. */ static void rld_code_naddr(TEXT_RLD *tr, unsigned code, int size) { rld_word(tr, code | (size == 1 ? 0200 : 0)); } /* write a word with a psect-relative value */ int text_internal_word(TEXT_RLD *tr, unsigned *addr, int size, unsigned word) { if(!text_fit(tr, *addr, size, 4)) return 0; text_word_i(tr, word, size); rld_code(tr, RLD_INT, *addr, size); rld_word(tr, word); *addr += size; return 1; } /* write a word which is an absolute reference to a global symbol */ int text_global_word(TEXT_RLD *tr, unsigned *addr, int size, unsigned word, char *global) { unsigned radtbl[2]; if(!text_fit(tr, *addr, size, 6)) return 0; text_word_i(tr, word, size); rld_code(tr, RLD_GLOBAL, *addr, size); rad50x2(global, radtbl); rld_word(tr, radtbl[0]); rld_word(tr, radtbl[1]); *addr += size; return 1; } /* Write a word which is a PC-relative reference to an absolute address */ int text_displaced_word(TEXT_RLD *tr, unsigned *addr, int size, unsigned word) { if(!text_fit(tr, *addr, size, 4)) return 0; text_word_i(tr, word, size); rld_code(tr, RLD_INT_DISP, *addr, size); rld_word(tr, word); *addr += size; return 1; } /* write a word which is a PC-relative reference to a global symbol */ int text_global_displaced_word(TEXT_RLD *tr, unsigned *addr, int size, unsigned word, char *global) { unsigned radtbl[2]; if(!text_fit(tr, *addr, size, 6)) return 0; text_word_i(tr, word, size); rld_code(tr, RLD_GLOBAL_DISP, *addr, size); rad50x2(global, radtbl); rld_word(tr, radtbl[0]); rld_word(tr, radtbl[1]); *addr += size; return 1; } /* write a word which is an absolute reference to a global symbol plus an offset */ /* Optimizes to text_global_word when the offset is zero. */ int text_global_offset_word(TEXT_RLD *tr, unsigned *addr, int size, unsigned word, char *global) { unsigned radtbl[2]; if(word == 0) return text_global_word(tr, addr, size, word, global); if(!text_fit(tr, *addr, size, 8)) return 0; text_word_i(tr, word, size); rld_code(tr, RLD_GLOBAL_OFFSET, *addr, size); rad50x2(global, radtbl); rld_word(tr, radtbl[0]); rld_word(tr, radtbl[1]); rld_word(tr, word); *addr += size; return 1; } /* write a word which is a PC-relative reference to a global symbol plus an offset */ /* Optimizes to text_global_displaced_word when the offset is zero. */ int text_global_displaced_offset_word(TEXT_RLD *tr, unsigned *addr, int size, unsigned word, char *global) { unsigned radtbl[2]; if(word == 0) return text_global_displaced_word(tr, addr, size, word, global); if(!text_fit(tr, *addr, size, 8)) return 0; text_word_i(tr, word, size); rld_code(tr, RLD_GLOBAL_OFFSET_DISP, *addr, size); rad50x2(global, radtbl); rld_word(tr, radtbl[0]); rld_word(tr, radtbl[1]); rld_word(tr, word); *addr += size; return 1; } /* Define current program counter, plus PSECT */ /* Different because it must be the last RLD entry in a block. That's because TEXT records themselves contain the current text address. */ int text_define_location(TEXT_RLD *tr, char *name, unsigned *addr) { unsigned radtbl[2]; if(!text_fit(tr, *addr, 0, 8)) /* No text space used */ return 0; rld_code_naddr(tr, RLD_LOCDEF, 2); /* RLD code for "location counter def" with no offset */ rad50x2(name, radtbl); rld_word(tr, radtbl[0]); /* Set current section name */ rld_word(tr, radtbl[1]); rld_word(tr, *addr); /* Set current location addr */ if(!text_flush(tr)) /* Flush that block out. */ return 0; text_init(tr, tr->fp, *addr); /* Set new text address */ return 1; } /* Modify current program counter, assuming current PSECT */ /* Location counter modification is similarly weird */ /* (I wonder - why is this RLD code even here? TEXT records contain thair own start address.) */ int text_modify_location(TEXT_RLD *tr, unsigned *addr) { if(!text_fit(tr, *addr, 0, 4)) /* No text space used */ return 0; rld_code_naddr(tr, RLD_LOCMOD, 2); /* RLD code for "location counter mod" with no offset */ rld_word(tr, *addr); /* Set current location addr */ if(!text_flush(tr)) /* Flush that block out. */ return 0; text_init(tr, tr->fp, *addr); /* Set new text address */ return 1; } /* write two words containing program limits (the .LIMIT directive) */ int text_limits(TEXT_RLD *tr, unsigned *addr) { if(!text_fit(tr, *addr, 4, 2)) return 0; text_word_i(tr, 0, 2); text_word_i(tr, 0, 2); rld_code(tr, RLD_LIMITS, *addr, 2); *addr += 4; return 1; } /* write a word which is the start address of a different PSECT */ int text_psect_word(TEXT_RLD *tr, unsigned *addr, int size, unsigned word, char *name) { unsigned radtbl[2]; if(!text_fit(tr, *addr, size, 6)) return 0; text_word_i(tr, word, size); rld_code(tr, RLD_PSECT, *addr, size); rad50x2(name, radtbl); rld_word(tr, radtbl[0]); rld_word(tr, radtbl[1]); *addr += size; return 1; } /* write a word which is an offset from the start of a different PSECT */ /* Optimizes to text_psect_word when offset is zero */ int text_psect_offset_word(TEXT_RLD *tr, unsigned *addr, int size, unsigned word, char *name) { unsigned radtbl[2]; if(word == 0) return text_psect_word(tr, addr, size, word, name); if(!text_fit(tr, *addr, size, 8)) return 0; text_word_i(tr, word, size); rld_code(tr, RLD_PSECT_OFFSET, *addr, size); rad50x2(name, radtbl); rld_word(tr, radtbl[0]); rld_word(tr, radtbl[1]); rld_word(tr, word); *addr += size; return 1; } /* write a word which is the address of a different PSECT, PC-relative */ int text_psect_displaced_word(TEXT_RLD *tr, unsigned *addr, int size, unsigned word, char *name) { unsigned radtbl[2]; if(!text_fit(tr, *addr, size, 6)) return 0; text_word_i(tr, word, size); rld_code(tr, RLD_PSECT_DISP, *addr, size); rad50x2(name, radtbl); rld_word(tr, radtbl[0]); rld_word(tr, radtbl[1]); *addr += size; return 1; } /* write a word which is an offset from the address of a different PSECT, PC-relative */ /* Optimizes to text_psect_displaced_word when offset is zero */ int text_psect_displaced_offset_word(TEXT_RLD *tr, unsigned *addr, int size, unsigned word, char *name) { unsigned radtbl[2]; if(word == 0) return text_psect_displaced_word(tr, addr, size, word, name); if(!text_fit(tr, *addr, size, 8)) return 0; text_word_i(tr, word, size); rld_code(tr, RLD_PSECT_OFFSET_DISP, *addr, size); rad50x2(name, radtbl); rld_word(tr, radtbl[0]); rld_word(tr, radtbl[1]); rld_word(tr, word); *addr += size; return 1; } /* complex relocation! */ /* A complex relocation expression is where a piece of code is fed to the linker asking it to do some math for you, and store the result in a program word. The code is a stack-based language. */ /* complex_begin initializes a TEXT_COMPLEX */ void text_complex_begin(TEXT_COMPLEX *tx) { tx->len = 0; } /* text_complex_fit checks if a complex expression will fit and returns a pointer to it's location */ static char *text_complex_fit(TEXT_COMPLEX *tx, int size) { int len; if(tx->len + size > sizeof(tx->accum)) return NULL; /* Expression has grown too complex. */ len = tx->len; tx->len += size; return tx->accum + len; } /* text_complex_byte stores a single byte. */ static int text_complex_byte(TEXT_COMPLEX *tx, unsigned byte) { char *cp = text_complex_fit(tx, 1); if(!cp) return 0; *cp = byte; return 1; } /* text_complex_add - add top two stack elements */ int text_complex_add(TEXT_COMPLEX *tx) { return text_complex_byte(tx, CPLX_ADD); } /* text_complex_sub - subtract top two stack elements. */ /* You know, I think these function labels are self-explanatory... */ int text_complex_sub(TEXT_COMPLEX *tx) { return text_complex_byte(tx, CPLX_SUB); } int text_complex_mul(TEXT_COMPLEX *tx) { return text_complex_byte(tx, CPLX_MUL); } int text_complex_div(TEXT_COMPLEX *tx) { return text_complex_byte(tx, CPLX_DIV); } int text_complex_and(TEXT_COMPLEX *tx) { return text_complex_byte(tx, CPLX_AND); } int text_complex_or(TEXT_COMPLEX *tx) { return text_complex_byte(tx, CPLX_OR); } int text_complex_xor(TEXT_COMPLEX *tx) { return text_complex_byte(tx, CPLX_XOR); } int text_complex_com(TEXT_COMPLEX *tx) { return text_complex_byte(tx, CPLX_COM); } int text_complex_neg(TEXT_COMPLEX *tx) { return text_complex_byte(tx, CPLX_NEG); } /* text_complex_lit pushes a literal value to the stack. */ int text_complex_lit(TEXT_COMPLEX *tx, unsigned word) { char *cp = text_complex_fit(tx, 3); if(!cp) return 0; *cp++ = CPLX_CONST; *cp++ = word & 0xff; *cp = (word >> 8) & 0xff; return 1; } /* text_complex_global pushes the value of a global variable to the stack */ int text_complex_global(TEXT_COMPLEX *tx, char *name) { unsigned radtbl[2]; char *cp = text_complex_fit(tx, 5); if(!cp) return 0; rad50x2(name, radtbl); *cp++ = CPLX_GLOBAL; *cp++ = radtbl[0] & 0xff; *cp++ = (radtbl[0] >> 8) & 0xff; *cp++ = radtbl[1] & 0xff; *cp = (radtbl[1] >> 8) & 0xff; return 1; } /* text_complex_psect pushes the value of an offset into a PSECT to the stack. */ /* What was not documented in the Software Support manual is that PSECT "sect" numbers are assigned in the order they appear in the source program, and the order they appear in the GSD. i.e. the first PSECT GSD is assigned sector 0 (which is always the default absolute section so that's a bad example), the next sector 1, etc. */ int text_complex_psect(TEXT_COMPLEX *tx, unsigned sect, unsigned offset) { char *cp = text_complex_fit(tx, 4); if(!cp) return 0; *cp++ = CPLX_REL; *cp++ = sect & 0xff; *cp++ = offset & 0xff; *cp = (offset >> 8) & 0xff; return 1; } /* text_complex_commit - store the result of the complex expression and end the RLD code. */ int text_complex_commit(TEXT_RLD *tr, unsigned *addr, int size, TEXT_COMPLEX *tx, unsigned word) { int i; text_complex_byte(tx, CPLX_STORE); if(!text_fit(tr, *addr, size, tx->len + 2)) return 0; rld_code(tr, RLD_COMPLEX, *addr, size); for(i = 0; i < tx->len; i++) rld_byte(tr, tx->accum[i]); text_word_i(tr, word, size); *addr += size; return 1; } /* text_complex_commit_displaced - store the result of the complex expression, relative to the current PC, and end the RLD code */ int text_complex_commit_displaced(TEXT_RLD *tr, unsigned *addr, int size, TEXT_COMPLEX *tx, unsigned word) { int i; text_complex_byte(tx, CPLX_STORE_DISP); if(!text_fit(tr, *addr, size, tx->len + 2)) return 0; rld_code(tr, RLD_COMPLEX, *addr, size); for(i = 0; i < tx->len; i++) rld_byte(tr, tx->accum[i]); text_word_i(tr, word, size); *addr += size; return 1; } /* Write end-of-object-module to file. */ int write_endmod(FILE *fp) { char endmod[2] = { OBJ_ENDMOD, 0 }; return writerec(fp, endmod, 2); }
/* * A polygon outline typeface file contains a sequence of * character descriptions. Each character description * starts with a 2 byte word with CHAR (defined below) * in the upper 4 bits and a character number in the bottom * 12 bits. Following the character number is a sequence of * boundaries. Each boundary begins with a word containing * BOUNDARY in the upper 4 bits and the number of vertices * in the boundary in the bottom 12 bits. Following that are * pairs of words giving the (integer) x,y coordinates of the * points on the boundary. Words are two bytes, stored low byte * first. * * The interior of a character is to the right of its boundaries. * That is, clockwise boundaries surround pieces of the character * and counterclockwise boundaries surround holes. * * Character numbers usually follow the Mergenthaler scheme: * x= 0 1 2 3 4 5 6 7 8 9 * --- ---------------------------- * 0x| a b c d e f g h i * 1x| j k l m n o p q r s * 2x| t u v w x y z A B C * 3x| D E F G H I J K L M * 4x| N O P Q R S T U V W * 5x| X Y Z & 1 2 3 4 5 6 * 6x| 7 8 9 0 . , : ; ? ! * 7x| ( ) hy ' ` em en $ ce % * 8x| / di st bu [ ] * sc dg dd * 9x| sv ac gr ci .. ti ic cu cd hh * 10x| fl fr dl dr pm oe OE iq ie sf * 11x| ld rd bd ss ae AE oa OA o/ O/ * 12x| fi fl * Abbreviations: * .. umlaut, diaresis AE AE ligature * O/ slashed O OA circle A * ac acute accent ae ae ligature * bd baseline double quote bu bullet * cd cedilla ce cent sign * ci circumflex accent cu cup (high accent) * dd double dagger dg dagger * di diagonal em em dash * en en dash gr grave accent * hh high horizontal hy hyphen * ic inverted circumflex ie inverted exclamation mark * iq inverted question mark ld left double quote * o/ slashed o oa circle a * rd right double quote sc section * sf script f st pound sterling * sv short vertical ti tilde (high, Spanish accent) * pm per mil */ #define CMD 0xf000 #define CHRNO 0x0fff #define CHR 0x1000 #define BOUNDARY 0x2000 #define NCHR (CHRNO+1) #define NAMES " a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z & 1 2 3 4 5 6 7 8 9 0 . , : ; ? ! ( ) hy' ` emen$ ce% / distbu[ ] * scdgddsvacgrci..tiiccucdhhflfrdldrpmoeOEiqiesfldrdbdssaeAEoaOAo/O/fifl" /* * Incore font outline structures. * A Typeface points to an array called glyph of nglyph Glyphs. * A Glyph points to an array called boundary of nboundary Boundarys. * A Boundary points to an array called pt of npt Points. */ typedef struct Typeface Typeface; typedef struct Glyph Glyph; typedef struct Boundary Boundary; struct Typeface{ int nglyph; Glyph *glyph; }; struct Glyph{ int nboundary; Boundary *boundary; }; struct Boundary{ int npt; Point *pt; };
/* SPDX-License-Identifier: MIT */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <sys/stat.h> #include "pe.h" #define ALIGN_UP(val, align) ((val + align - 1) & ~(align - 1)) const size_t ALIGN = 0x1000; const size_t STRSIZE = 1024; unsigned long long offset; unsigned int address_of_entry_point; unsigned int size_of_code; unsigned int base_of_code; unsigned int size_of_image; unsigned int text_size; unsigned int text_addr; unsigned int rodata_size; unsigned int rodata_addr; unsigned int data_size; unsigned int data_addr; unsigned int bss_size; unsigned int bss_addr; static void parse_symbol_table(const char *sym_name) { FILE *sym_fp = fopen(sym_name, "r"); if (!sym_fp) { fprintf(stderr, "Could not open file %s\n", sym_name); return; } const char *HEADER = "_hdr"; const char *ENTRY = "_entry"; const char *TEXT = "_text"; const char *ETEXT = "_etext"; const char *RODATA = "_rodata"; const char *ECTORS = "_ectors"; const char *DATA = "_data"; const char *EDATA = "_edata"; const char *BSS = "__bss_start"; const char *END = "_end"; unsigned int text; unsigned int etext; unsigned int rodata; unsigned int ectors; unsigned int data; unsigned int edata; unsigned int bss; unsigned int end; unsigned long long addr; char c; char sym[STRSIZE]; while (fscanf(sym_fp, "%llx %c %s", &addr, &c, sym) != EOF) { if (!strncmp(sym, HEADER, STRSIZE)) { offset = addr; } else if (!strncmp(sym, ENTRY, STRSIZE)) { address_of_entry_point = addr - offset; } else if (!strncmp(sym, TEXT, STRSIZE)) { text = addr - offset; } else if (!strncmp(sym, ETEXT, STRSIZE)) { etext = addr - offset; } else if (!strncmp(sym, RODATA, STRSIZE)) { rodata = addr - offset; } else if (!strncmp(sym, ECTORS, STRSIZE)) { ectors = addr - offset; } else if (!strncmp(sym, DATA, STRSIZE)) { data = addr - offset; } else if (!strncmp(sym, EDATA, STRSIZE)) { edata = addr - offset; } else if (!strncmp(sym, BSS, STRSIZE)) { bss = addr - offset; } else if (!strncmp(sym, END, STRSIZE)) { end = addr - offset; } } base_of_code = text; size_of_code = etext - text; size_of_image = end; text_size = ALIGN_UP(size_of_code, ALIGN); text_addr = text; rodata_size = ALIGN_UP(ectors - rodata, ALIGN); rodata_addr = rodata; data_size = ALIGN_UP(edata - data, ALIGN); data_addr = data; bss_size = ALIGN_UP(end - bss, ALIGN); bss_addr = bss; fclose(sym_fp); } int main(int argc, char *argv[]) { if (argc < 4) { fprintf(stderr, "Usage: %s SymbolTable INPUT OUTPUT\n", argv[0]); return 1; } parse_symbol_table(argv[1]); char bin_name[STRSIZE]; strncpy(bin_name, argv[2], STRSIZE); int bin_fd = open(bin_name, O_RDONLY); if (bin_fd == -1) { fprintf(stderr, "Could not open file %s\n", bin_name); goto fail; } FILE *bin_fp = fdopen(bin_fd, "rb"); if (!bin_fp) { fprintf(stderr, "Could not open file %s\n", bin_name); goto fail; } struct stat bin_st; if (fstat(bin_fd, &bin_st) == -1) { fprintf(stderr, "fstat failed\n"); goto fail; } size_t bin_size = bin_st.st_size; void *bin_buf = malloc(bin_size); if (!bin_buf) { fprintf(stderr, "Could not allocate memory\n"); goto fail; } if (fread(bin_buf, 1, bin_size, bin_fp) != bin_size) { fprintf(stderr, "Cound not read file\n"); goto fail; } IMAGE_DOS_HEADER *doshdr = (IMAGE_DOS_HEADER *)bin_buf; if (doshdr->e_magic != MAGIC_MZ) { fprintf(stderr, "DOS header magic not found\n"); goto fail; } IMAGE_NT_HEADERS *nthdr \ = (IMAGE_NT_HEADERS *)((void *)doshdr + doshdr->e_lfanew); if (nthdr->Signature != MAGIC_PE) { fprintf(stderr, "PE header signature not found\n"); goto fail; } IMAGE_FILE_HEADER *fhdr = &nthdr->FileHeader; IMAGE_OPTIONAL_HEADER *opthdr = &nthdr->OptionalHeader; opthdr->AddressOfEntryPoint = address_of_entry_point; opthdr->SizeOfCode = size_of_code; opthdr->BaseOfCode = base_of_code; opthdr->SizeOfImage = size_of_image; const char *TEXT = ".text"; const char *RODATA = ".rodata"; const char *DATA = ".data"; const char *BSS = ".bss"; for (int i = 0; i < fhdr->NumberOfSections; i++) { IMAGE_SECTION_HEADER *sechdr \ = ((void *)nthdr + sizeof(IMAGE_NT_HEADERS) + sizeof(IMAGE_SECTION_HEADER) * i); if (!strncmp(sechdr->Name, TEXT, IMAGE_SIZEOF_SHORT_NAME)) { sechdr->Misc.VirtualSize = text_size; sechdr->VirtualAddress = text_addr; sechdr->SizeOfRawData = text_size; sechdr->PointerToRawData = text_addr; } else if (!strncmp(sechdr->Name, RODATA, IMAGE_SIZEOF_SHORT_NAME)) { sechdr->Misc.VirtualSize = rodata_size; sechdr->VirtualAddress = rodata_addr; sechdr->SizeOfRawData = rodata_size; sechdr->PointerToRawData = rodata_addr; } else if (!strncmp(sechdr->Name, DATA, IMAGE_SIZEOF_SHORT_NAME)) { sechdr->Misc.VirtualSize = data_size; sechdr->VirtualAddress = data_addr; sechdr->SizeOfRawData = data_size; sechdr->PointerToRawData = data_addr; } else if (!strncmp(sechdr->Name, BSS, IMAGE_SIZEOF_SHORT_NAME)) { sechdr->Misc.VirtualSize = bss_size; sechdr->VirtualAddress = bss_addr; sechdr->SizeOfRawData = bss_size; sechdr->PointerToRawData = bss_addr; } } void *wbuf = malloc(size_of_image); memset(wbuf, 0, size_of_image); memcpy(wbuf, bin_buf, size_of_image); FILE *wfp = fopen(argv[3], "wb"); fwrite(wbuf, size_of_image, 1, wfp); fclose(wfp); return 0; fail: if (bin_buf) free(bin_buf); if (bin_fp) fclose(bin_fp); if (bin_fd != -1) close(bin_fd); return 1; }
/* SPDX-License-Identifier: GPL-2.0 */ #ifndef __ASM_SMP_H #define __ASM_SMP_H #include <linux/cpumask.h> #define raw_smp_processor_id() (current_thread_info()->cpu) enum ipi_msg_type { IPI_CALL_FUNC, IPI_RESCHEDULE, }; extern void arch_send_call_function_single_ipi(int cpu); extern void arch_send_call_function_ipi_mask(const struct cpumask *mask); asmlinkage void secondary_start_kernel(void); extern void secondary_startup(void); #ifdef CONFIG_HOTPLUG_CPU extern void __cpu_die(unsigned int cpu); extern int __cpu_disable(void); extern void cpu_die(void); #endif extern void smp_init_cpus(void); #endif /* __ASM_SMP_H */
<gh_stars>1-10 // // Created by haru on 2017. 10. 26.. // Copyright © 2017 Hyperconnect. All rights reserved. // #import <GPUImage/GPUImage.h> @interface GPUImageCrossHatch2Filter : GPUImageFilter { GLint uCrossHatchSpacing; GLint uLineWidth; } @property (nonatomic, assign) CGFloat crossHatchSpacing; @property (nonatomic, assign) CGFloat lineWidth; - (id)initWithCrossHatchSpacing:(CGFloat)crossHatchSpacing lineWidth:(CGFloat)lineWidth fragmentShaderFromString:(NSString *)fragmentShaderString; @end
// // CHDatePickerView.h // CHDatePicker-Demo // // Created by 张晨晖 on 2019/2/18. // Copyright © 2019 张晨晖. All rights reserved. // /// 注: /// 1.年份从1-10000 /// 2.月份从1-12 /// 3.日从1-31(如果月份没有31(2月之类的)选中之后自动滚动到最近的一个日,仿苹果UIDatePicker效果) /// 4.时0-23 /// 5.分0-59 /// 6.秒0-59 #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN typedef NS_ENUM(NSUInteger, CHDatePickerViewDateComponent) { /// 年 CHDatePickerViewDateComponentY, /// 月 CHDatePickerViewDateComponentM, /// 日 CHDatePickerViewDateComponentD, /// 时 CHDatePickerViewDateComponentH, /// 分 CHDatePickerViewDateComponentm, /// 秒 CHDatePickerViewDateComponents, /// 时(12小时制) CHDatePickerViewDateComponentHShort, /// AM/PM CHDatePickerViewDateComponentAMPMS, }; typedef NS_ENUM(NSUInteger, CHDatePickerViewDateStyle) { /// 年月日时分秒 CHDatePickerViewDateStyleYMDHms, /// 年月日时分 CHDatePickerViewDateStyleYMDHm, /// 年月日时 CHDatePickerViewDateStyleYMDH, /// 年月日 CHDatePickerViewDateStyleYMD, /// 年月 CHDatePickerViewDateStyleYM, /// 年 CHDatePickerViewDateStyleY, /// 月日时分秒 CHDatePickerViewDateStyleMDHms, /// 月日时分 CHDatePickerViewDateStyleMDHm, /// 月日时分 CHDatePickerViewDateStyleMDH, /// 月日 CHDatePickerViewDateStyleMD, /// 月 CHDatePickerViewDateStyleM, /// 日时分秒 CHDatePickerViewDateStyleDHms, /// 日时分 CHDatePickerViewDateStyleDHm, /// 日时 CHDatePickerViewDateStyleDH, /// 日 CHDatePickerViewDateStyleD, /// 时分秒 CHDatePickerViewDateStyleHms, /// 时分 CHDatePickerViewDateStyleHm, /// 时 CHDatePickerViewDateStyleH, /// 分秒 CHDatePickerViewDateStylems, /// 分 CHDatePickerViewDateStylem, /// 秒 CHDatePickerViewDateStyles, }; typedef NS_ENUM(NSUInteger, CHDatePickerViewDateTextShowType) { /// 单行显示 CHDatePickerViewDateTextShowTypeSingleRow, /// 不显示 CHDatePickerViewDateTextShowTypeNone, /// 每行都显示 CHDatePickerViewDateTextShowTypeAllRow, }; typedef void(^CHDatePickerViewDidSelectDateBlock)(NSDate *date ,NSDateComponents *dateComponents); @protocol CHDatePickerViewDelegate <NSObject> @optional - (void)datePickerViewDidSelectDate:(NSDate *)date dateComponents:(NSDateComponents *)dateComponents; @end @interface CHDatePickerView : UIView /// 手动设置排列方式 @property (nonatomic ,strong) NSArray *dateComponents; /// 快速设置排列方式(内置年月日) @property (nonatomic ,assign) CHDatePickerViewDateStyle dateStyle; /// 年月日显示方式 @property (nonatomic ,assign) CHDatePickerViewDateTextShowType dateTextShowType; @property (nonatomic ,weak) id <CHDatePickerViewDelegate> delegate; @property (nonatomic ,copy) CHDatePickerViewDidSelectDateBlock didSelectDateBlock; /// 按钮背景板 @property (nonatomic ,strong) UIView *viewButtonBackground; /// 按钮背景板底部线 default color is nil @property (nonatomic ,strong) UIView *viewButtonBackgroundBottomLine; /// 确认按钮 @property (nonatomic ,strong) UIButton *buttonConfirm; /// 取消按钮 @property (nonatomic ,strong) UIButton *buttonCancel; /// 中间标题 @property (nonatomic ,strong) UILabel *labelTitle; /// MARK:row的字体 /// 字体大小 @property (nonatomic ,strong) UIFont *textFont UI_APPEARANCE_SELECTOR; /// 文字颜色 @property (nonatomic ,strong) UIColor *textColor UI_APPEARANCE_SELECTOR; // MARK:SingleRow的字体 @property (nonatomic ,strong) UIFont *singleRowTextFont UI_APPEARANCE_SELECTOR; /// SingleRow文字颜色 @property (nonatomic ,strong) UIColor *singleRowTextColor UI_APPEARANCE_SELECTOR; // 默认的选中时间.默认为当前时间[NSDate date] @property (nonatomic, strong) NSDate *date; /// 允许选中的最小时间 @property (nullable, nonatomic, strong) NSDate *minimumDate; // default is nil /// 允许选中的最大时间 @property (nullable, nonatomic, strong) NSDate *maximumDate; // default is nil /// 是否datePickerView显示分割线 @property (nonatomic ,assign) BOOL pickerViewSeparatorHidden; /// datePickerView分割线颜色.可以通过CHPickerView的来设置全局的分割线颜色 @property (nonatomic ,strong) UIColor *pickerViewSeparatorColor; /// 允许tap手势使pickerView隐藏 @property (nonatomic ,assign) BOOL allowTapToDissmiss; - (void)show; - (void)dismiss; - (void)setDate:(NSDate *)date animated:(BOOL)animated; @end NS_ASSUME_NONNULL_END
#include "indirect_link_hashtable.h" #include "module_observer.h" #include "execution_monitor.h" #include "crowd_safe_trace.h" #include "crowd_safe_util.h" /**** hashtablex.h interface elements ****/ static void *tag_xref_mutex; /**** Multimap Template ****/ // cross-reference table of tag to adjacent bb_tag_pairing_t instances // entries may be stale, if the other side gets removed #define MULTIMAP_NAME_KEY xref_multimap #define MULTIMAP_KEY_TYPE app_pc #define MULTIMAP_VALUE_TYPE bb_tag_pairing_t #define MULTIMAP_ENTRY_INLINE 1 #include "../drcontainers/drmultimap.h" #define MULTIMAP_NAME_KEY xref_multimap #define MULTIMAP_KEY_TYPE app_pc #define MULTIMAP_VALUE_TYPE bb_tag_pairing_t #define MULTIMAP_ENTRY_INLINE 1 #include "../drcontainers/drmultimapx.h" static xref_multimap_t *xref_multimap; // synchronized under TAG_XREF_LOCK // Locking note: if necessary to hold the xref lock and the table lock at the same time, // acquire the xref lock first, then the table lock. This occurs in the xref removal callback. #define TAG_XREF_LOCK dr_mutex_lock(tag_xref_mutex); #define TAG_XREF_UNLOCK dr_mutex_unlock(tag_xref_mutex); #define ASSERT_TAG_XREF_LOCK ASSERT(dr_mutex_self_owns(tag_xref_mutex)); #ifdef MONITOR_UNEXPECTED_IBP typedef struct unexpected_ibp_t unexpected_ibp_t; struct unexpected_ibp_t { app_pc from; app_pc to; uint edge_index; uint flags; uint execution_count; report_mask_t report_mask; }; # define UIBP_FROM_EXPECTED 1 # define UIBP_TO_EXPECTED 2 # define UIBP_CROSS_MODULE 4 # define UIBP_ADMITTED 8 # define UIBP_REPORT_PENDING 0x10 # define HASHTABLE_NAME_KEY uibp_hashtable # define HASHTABLE_KEY_TYPE bb_tag_pairing_t # include "../drcontainers/drhashtable.h" # define HASHTABLE_NAME_KEY uibp_hashtable # define HASHTABLE_KEY_TYPE bb_tag_pairing_t # include "../drcontainers/drhashtablex.h" static uibp_hashtable_t *uibp_table; static bool *final_uibp_report_written; typedef struct uibp_interval_t uibp_interval_t; struct uibp_interval_t { const uint interval; const byte id; // log_10 of `interval` const uint index; const char *label; }; static const uibp_interval_t uibp_intervals[UIBP_INTERVAL_COUNT] = { { 1000, 3, 0, "micro" }, { 10000, 4, 1, "short" }, { 100000, 5, 2, "long" }, { 1000000, 6, 3, "macro" }, }; typedef struct global_uibp_t global_uibp_t; struct global_uibp_t { uint pending_report_count; report_mask_t pending_report_mask; clock_type_t last_report; uint observed_interval_count[UIBP_INTERVAL_COUNT]; uint observed_admitted_interval_count[UIBP_INTERVAL_COUNT]; uint observed_suspicious_interval_count[UIBP_INTERVAL_COUNT]; uint max_consecutive_intervals[UIBP_INTERVAL_COUNT]; uint max_consecutive_admitted_intervals[UIBP_INTERVAL_COUNT]; uint max_consecutive_suspicious_intervals[UIBP_INTERVAL_COUNT]; report_mask_t report_masks[UIBP_INTERVAL_COUNT]; } *global_uibp; static drvector_t *pending_uibp_list; # define MIN_UIBP_REPORT_MASK 0xff # define MAX_UIBP_REPORT_MASK 0xfffffff #endif /**** Private Prototypes ****/ static bb_tag_pairing_t hash_ibp(app_pc from, app_pc to); static void xref_value_removed(bb_tag_pairing_t pairing); #ifdef MONITOR_UNEXPECTED_IBP static void increment_pending_uib_count(dcontext_t *dcontext); static void write_uibp_interval_report(); static void write_pending_uibp_reports(dcontext_t *dcontext); static void uibp_removed(void *p); #endif static void hashtable_entry_free_nop(void *); static void report_uibp(dcontext_t *dcontext, crowd_safe_thread_local_t *cstl, bool is_admitted, app_pc from, app_pc to, module_location_t *from_module, module_location_t *to_module, uint edge_index); /**** Public Functions ****/ void ibp_hash_global_init(dcontext_t *dcontext) { xref_multimap = (xref_multimap_t *)CS_ALLOC(sizeof(xref_multimap_t)); xref_multimap_init(xref_multimap, xref_value_removed, "ibp xref"); tag_xref_mutex = dr_mutex_create(); CS_TRACK(tag_xref_mutex, sizeof(mutex_t)); #ifdef MONITOR_UNEXPECTED_IBP { uint j; uibp_table = (uibp_hashtable_t *)CS_ALLOC(sizeof(uibp_hashtable_t)); uibp_hashtable_init_ex( uibp_table, 9, HASH_INTPTR, false, false, uibp_removed, NULL, /* no custom hashing */ NULL); global_uibp = CS_ALLOC(sizeof(global_uibp_t)); global_uibp->pending_report_count = 0; init_report_mask(&global_uibp->pending_report_mask, MIN_UIBP_REPORT_MASK, MAX_UIBP_REPORT_MASK); global_uibp->last_report = quick_system_time_millis(); for (j = 0; j < UIBP_INTERVAL_COUNT; j++) { global_uibp->observed_interval_count[j] = 0; global_uibp->observed_admitted_interval_count[j] = 0; global_uibp->observed_suspicious_interval_count[j] = 0; global_uibp->max_consecutive_intervals[j] = 0; global_uibp->max_consecutive_admitted_intervals[j] = 0; global_uibp->max_consecutive_suspicious_intervals[j] = 0; init_report_mask(&global_uibp->report_masks[j], 0xf, 0xffff); } pending_uibp_list = CS_ALLOC(sizeof(drvector_t)); drvector_init(pending_uibp_list, 0x40, false, NULL); final_uibp_report_written = CS_ALLOC(sizeof(bool)); *final_uibp_report_written = false; } #endif } bb_tag_pairing_t ibp_hash_lookup(dcontext_t *dcontext, app_pc from, app_pc to) { bb_tag_pairing_t key; CROWD_SAFE_DEBUG_HOOK(__FUNCTION__, (bb_tag_pairing_t)0x0); key = hash_ibp(from, to); return dr_ibp_lookup(dcontext, key); } bool ibp_hash_add(dcontext_t *dcontext, app_pc from, app_pc to) { bb_tag_pairing_t key; bool added = false; CROWD_SAFE_DEBUG_HOOK(__FUNCTION__, (bb_tag_pairing_t)0x0); // generate the ibp hash id for the from/to pair key = hash_ibp(from, to); if (dr_ibp_add_new(dcontext, key)) { CS_DET("xref (%s): from "PX" to "PX" on thread 0x%x\n", __FUNCTION__, from, to, current_thread_id()); TAG_XREF_LOCK xref_multimap_add(xref_multimap, from, key); xref_multimap_add(xref_multimap, to, key); TAG_XREF_UNLOCK added = true; } DODEBUG({ if (!added) { if (!ibp_has_incoming_edges(to)) CS_ERR("IBP table hit on "PX" - "PX" for key 0x%llx, but xref has no incoming edges for 'to'\n", from, to, key); ASSERT(ibp_has_incoming_edges(to)); } }); return added; } uint get_ibp_edge_count(app_pc tag) { uint count; xref_multimap_entry_t *entry; CROWD_SAFE_DEBUG_HOOK(__FUNCTION__, 0U); TAG_XREF_LOCK entry = xref_multimap_lookup(xref_multimap, tag); if (entry == NULL) count = 0; else count = xref_multimap_item_count(entry); TAG_XREF_UNLOCK return count; } bool ibp_has_incoming_edges(app_pc tag) { bool has_edges = false; xref_multimap_entry_t *entry; CROWD_SAFE_DEBUG_HOOK(__FUNCTION__, 0U); TAG_XREF_LOCK entry = xref_multimap_lookup(xref_multimap, tag); if (entry != NULL) { uint i, count = xref_multimap_item_count(entry); bb_hash_t key; for (i = 0; i < count; i++) { key = xref_multimap_entry_get_item(entry, i); if ((uint)(key >> 0x20) == p2int(tag)) { has_edges = true; break; } } } TAG_XREF_UNLOCK return has_edges; } void ibp_tag_remove(dcontext_t *dcontext, app_pc tag) { CROWD_SAFE_DEBUG_HOOK_VOID(__FUNCTION__); CS_DET("xref (%s): tag "PX"\n", __FUNCTION__, tag); TAG_XREF_LOCK // calls xref_value_removed() on each removed entry xref_multimap_remove_entry(xref_multimap, tag); TAG_XREF_UNLOCK } void ibp_clear(dcontext_t *dcontext) { dr_ibp_clear(dcontext); TAG_XREF_LOCK xref_multimap->notify_value_removed = NULL; xref_multimap_clear(xref_multimap); xref_multimap->notify_value_removed = xref_value_removed; TAG_XREF_UNLOCK } #ifdef MONITOR_UNEXPECTED_IBP void install_unexpected_ibp(dcontext_t *dcontext, app_pc from, app_pc to, module_location_t *from_module, module_location_t *to_module, bool is_from_expected, bool is_to_expected, uint edge_index, bool is_admitted, bool is_return) { crowd_safe_thread_local_t *cstl = GET_CSTL(dcontext); uint flags = 0; bb_tag_pairing_t key = hash_ibp(from, to); // cs-todo: check for duplicate first? unexpected_ibp_t *uibp = (unexpected_ibp_t *)CS_ALLOC(sizeof(unexpected_ibp_t)); assert_hashcode_lock(); uibp->from = from; uibp->to = to; uibp->edge_index = edge_index; if (is_from_expected) flags |= UIBP_FROM_EXPECTED; if (is_to_expected) flags |= UIBP_TO_EXPECTED; uibp->flags = flags; uibp->execution_count = 1; uibp->flags |= ((from_module != to_module) * UIBP_CROSS_MODULE); uibp->flags |= (is_admitted * UIBP_ADMITTED); init_report_mask(&uibp->report_mask, 0xf, 0xffffffff); TAG_XREF_LOCK if (is_return) { NOTIFY_UNIT_PREDICATE_EVENT(dcontext, instance_predicates, ur); NOTIFY_UNIT_PREDICATE_EVENT(dcontext, invocation_predicates, ur); } else if (is_admitted) { NOTIFY_UNIT_PREDICATE_EVENT(dcontext, instance_predicates, uib); NOTIFY_UNIT_PREDICATE_EVENT(dcontext, invocation_predicates, uib); } else { NOTIFY_UNIT_PREDICATE_EVENT(dcontext, instance_predicates, suib); NOTIFY_UNIT_PREDICATE_EVENT(dcontext, invocation_predicates, suib); } CS_DET("%s| %s("PX") -%c-> %s("PX")\n", is_admitted ? "UIB" : "SUIB", from_module->module_name, MODULAR_PC(from_module, from), is_return ? 'R' : '-', to_module->module_name, MODULAR_PC(to_module, to)); { unexpected_ibp_t *existing_uibp = uibp_hashtable_lookup(uibp_table, key); if (existing_uibp != NULL) CS_ERR("Installing over the top of an existing UIBP!\n"); } uibp_hashtable_add(uibp_table, key, uibp); xref_multimap_add(xref_multimap, from, key); xref_multimap_add(xref_multimap, to, key); report_uibp(dcontext, cstl, is_admitted, from, to, from_module, to_module, edge_index); increment_pending_uib_count(dcontext); TAG_XREF_UNLOCK } bool notify_possibly_unexpected_ibp(dcontext_t *dcontext, crowd_safe_thread_local_t *cstl, app_pc from, app_pc to, bool is_unexpected_return) { bb_tag_pairing_t key; unexpected_ibp_t *uibp; module_location_t *from_module, *to_module; if (!CROWD_SAFE_MONITOR()) return false; key = hash_ibp(from, to); TAG_XREF_LOCK uibp = uibp_hashtable_lookup(uibp_table, key); TAG_XREF_UNLOCK if (uibp == NULL) return false; from_module = get_module_for_address(from); to_module = get_module_for_address(to); TAG_XREF_LOCK if (is_unexpected_return) NOTIFY_UNIT_PREDICATE_EVENT(dcontext, invocation_predicates, ur); else if (uibp->flags & UIBP_ADMITTED) NOTIFY_UNIT_PREDICATE_EVENT(dcontext, invocation_predicates, uib); else NOTIFY_UNIT_PREDICATE_EVENT(dcontext, invocation_predicates, suib); CS_DET("%s+| %s("PX") -> %s("PX")\n", (uibp->flags & UIBP_ADMITTED) ? "UIB" : "SUIB", from_module->module_name, MODULAR_PC(from_module, from), to_module->module_name, MODULAR_PC(to_module, to)); uibp->execution_count++; if ((uibp->flags & UIBP_REPORT_PENDING) == 0) { uibp->flags |= UIBP_REPORT_PENDING; drvector_append(pending_uibp_list, uibp); } report_uibp(dcontext, cstl, uibp->flags & UIBP_ADMITTED, from, to, from_module, to_module, uibp->edge_index); increment_pending_uib_count(dcontext); TAG_XREF_UNLOCK #ifdef MONITOR_UIBP_ONLINE { char *label; clock_type_t now = quick_system_time_millis(); bool reported = false; cstl->thread_uibp.total++; switch (uibp->flags & (UIBP_FROM_EXPECTED | UIBP_TO_EXPECTED)) { case 0: cstl->thread_uibp.within_unexpected++; label = "U->U"; break; case UIBP_FROM_EXPECTED: cstl->thread_uibp.from_expected++; label = "E->U"; break; case UIBP_TO_EXPECTED: cstl->thread_uibp.to_expected++; label = "U->E"; break; default: cstl->thread_uibp.within_expected++; label = "E->E"; } if (is_report_threshold(&uibp->report_mask, uibp->execution_count)) if (from_module == to_module) CS_LOG("UIBP| %d executions of %s ibp %s("PX"->"PX")\n", uibp->execution_count, label, from_module->module_name, MODULAR_PC(from_module, from), MODULAR_PC(to_module, to)); else CS_LOG("UIBP| %d executions of %s ibp %s("PX")->%s("PX")\n", uibp->execution_count, label, from_module->module_name, MODULAR_PC(from_module, from), to_module->module_name, MODULAR_PC(to_module, to)); if (is_report_threshold(&cstl->thread_uibp.report_mask, cstl->thread_uibp.total)) CS_LOG("UIBP| %d ibp executions on thread 0x%x: %d E->E, %d U->E, %d E->U, %d U->U\n", cstl->thread_uibp.total, current_thread_id(), cstl->thread_uibp.within_expected, cstl->thread_uibp.to_expected, cstl->thread_uibp.from_expected, cstl->thread_uibp.within_unexpected); if (uibp->flags & UIBP_ADMITTED) { from_module->unexpected_ibt.admitted_target_invocations++; if ((from_module->unexpected_ibt.last_admitted_target_invocation > 0ULL) && ((now - from_module->unexpected_ibt.last_admitted_target_invocation) > BUFFER_FLUSH_INTERVAL)) { report_unexpected_ibt(from_module); reported = true; } from_module->unexpected_ibt.last_admitted_target_invocation = now; if (from_module->unexpected_ibt.first_admitted_target_invocation == 0ULL) { from_module->unexpected_ibt.first_admitted_target_invocation = from_module->unexpected_ibt.last_admitted_target_invocation; } } else { from_module->unexpected_ibt.suspicious_target_invocations++; if ((from_module->unexpected_ibt.last_suspicious_target_invocation > 0ULL) && ((now - from_module->unexpected_ibt.last_suspicious_target_invocation) > BUFFER_FLUSH_INTERVAL)) { report_unexpected_ibt(from_module); reported = true; } from_module->unexpected_ibt.last_suspicious_target_invocation = now; if (from_module->unexpected_ibt.first_suspicious_target_invocation == 0ULL) { from_module->unexpected_ibt.first_suspicious_target_invocation = from_module->unexpected_ibt.last_suspicious_target_invocation; } } if (!reported) report_unexpected_ibt_at_interval(from_module); } #endif return true; } void write_stale_uibp_reports(dcontext_t *dcontext, clock_type_t now) { // unsafe reads--slop is ok if ((now - global_uibp->last_report) > UIBP_REPORT_INTERVAL) { if (global_uibp->pending_report_count > 0) { TAG_XREF_LOCK output_lock_acquire(); write_pending_uibp_reports(dcontext); write_meta_timepoint(); init_report_mask(&global_uibp->pending_report_mask, MIN_UIBP_REPORT_MASK, MAX_UIBP_REPORT_MASK); output_lock_release(); TAG_XREF_UNLOCK } else if (CROWD_SAFE_META_ON_CLOCK()) { // write meta at ~60 second interval output_lock_acquire(); write_meta_timepoint(); global_uibp->last_report = now; output_lock_release(); } } } static void write_pending_uibp_reports(dcontext_t *dcontext) { uint i; unexpected_ibp_t *uibp; ASSERT_TAG_XREF_LOCK assert_output_lock(); if (global_uibp->pending_report_count == 0) return; for (i = 0; i < pending_uibp_list->entries; i++) { uibp = pending_uibp_list->array[i]; write_meta_uib(uibp->from, uibp->to, uibp->edge_index, uibp->flags & UIBP_CROSS_MODULE, uibp->flags & UIBP_ADMITTED, uibp->execution_count); if (CROWD_SAFE_META_ON_CLOCK()) { bb_tag_pairing_t key = hash_ibp(uibp->from, uibp->to); uibp_hashtable_remove(uibp_table, key); dr_ibp_add(dcontext, key); xref_multimap_add(xref_multimap, uibp->from, key); xref_multimap_add(xref_multimap, uibp->to, key); } else { uibp->flags &= ~UIBP_REPORT_PENDING; } } drvector_clear(pending_uibp_list); global_uibp->pending_report_count = 0; global_uibp->last_report = quick_system_time_millis(); write_uibp_interval_report(); } #endif #ifdef MONITOR_UNEXPECTED_IBP void write_final_uibp_report() { bool repeat; if (tag_xref_mutex == NULL) return; TAG_XREF_LOCK repeat = *final_uibp_report_written; TAG_XREF_UNLOCK if (repeat) return; CS_LOG("Writing final UIBP report\n"); TAG_XREF_LOCK output_lock_acquire(); write_uibp_interval_report(); uibp_hashtable_clear(uibp_table); // prompts an exit report per UIBP output_lock_release(); *final_uibp_report_written = true; TAG_XREF_UNLOCK finalize_metadata(); } #endif void ibp_hash_global_destroy() { #ifdef MONITOR_UNEXPECTED_IBP hashcode_lock_acquire(); write_final_uibp_report(); hashcode_lock_release(); #endif TAG_XREF_LOCK xref_multimap->notify_value_removed = NULL; xref_multimap_delete(xref_multimap); dr_global_free(xref_multimap, sizeof(xref_multimap_t)); TAG_XREF_UNLOCK dr_mutex_destroy(tag_xref_mutex); tag_xref_mutex = NULL; #ifdef MONITOR_UNEXPECTED_IBP output_lock_acquire(); uibp_hashtable_delete(uibp_table); output_lock_release(); dr_global_free(uibp_table, sizeof(uibp_hashtable_t)); dr_global_free(global_uibp, sizeof(global_uibp_t)); dr_global_free(final_uibp_report_written, sizeof(bool)); #endif } /**** Private Functions ****/ // hash is <to, (from <<o 1) ^ to> static inline bb_tag_pairing_t hash_ibp(app_pc from, app_pc to) { #ifdef X64 ptr_uint_t left, right, rotated_bit; left = p2int(to) << 0x20; right = p2int(from); rotated_bit = ((right & 0x80000000UL) > 0) ? 1 : 0; right = ((right << 1) | rotated_bit); right = (right ^ p2int(to)) & ALL_LOWER_BITS; return (bb_tag_pairing_t)(left | right); #else ptr_uint_t right, rotated_bit; bb_tag_pairing_t hash; hash = p2int(to); hash = hash << 0x20; right = p2int(from); rotated_bit = ((right & 0x80000000UL) > 0) ? 1 : 0; right = ((right << 1) | rotated_bit); right = right ^ p2int(to); return (bb_tag_pairing_t)(hash | right); #endif } static void xref_value_removed(bb_tag_pairing_t pairing) { bool removed; ASSERT_TAG_XREF_LOCK removed = dr_ibp_remove(pairing); #ifdef MONITOR_UNEXPECTED_IBP if (removed) uibp_hashtable_remove(uibp_table, pairing); #endif } #ifdef MONITOR_UNEXPECTED_IBP static inline void increment_pending_uib_count(dcontext_t *dcontext) { global_uibp->pending_report_count++; if (!CROWD_SAFE_META_ON_CLOCK() && is_report_threshold(&global_uibp->pending_report_mask, global_uibp->pending_report_count)) { output_lock_acquire(); write_pending_uibp_reports(dcontext); write_meta_timepoint(); output_lock_release(); } } static inline void write_uibp_interval_report() { uint i; assert_output_lock(); for (i = 0; i < UIBP_INTERVAL_COUNT; i++) { write_meta_uib_interval(uibp_intervals[i].id, 0, global_uibp->observed_interval_count[i], (ushort)global_uibp->max_consecutive_intervals[i]); write_meta_uib_interval(uibp_intervals[i].id, 1, global_uibp->observed_admitted_interval_count[i], (ushort)global_uibp->max_consecutive_admitted_intervals[i]); write_meta_uib_interval(uibp_intervals[i].id, 2, global_uibp->observed_suspicious_interval_count[i], (ushort)global_uibp->max_consecutive_suspicious_intervals[i]); } } static void uibp_removed(void *p) { unexpected_ibp_t *uibp = (unexpected_ibp_t*)p; assert_output_lock(); if (*final_uibp_report_written) return; if (uibp != NULL) { # ifdef MONITOR_UIBP_ONLINE char *label; switch (uibp->flags & (UIBP_FROM_EXPECTED | UIBP_TO_EXPECTED)) { case 0: label = "U->U"; break; case UIBP_FROM_EXPECTED: label = "E->U"; break; case UIBP_TO_EXPECTED: label = "U->E"; break; default: label = "E->E"; } CS_LOG("UIBP| %d executions of %s ibp "PX" -> "PX" (final--removing ibp)\n", uibp->execution_count, label, uibp->from, uibp->to); # endif write_meta_uib(uibp->from, uibp->to, uibp->edge_index, uibp->flags & UIBP_CROSS_MODULE, uibp->flags & UIBP_ADMITTED, uibp->execution_count); dr_global_free(uibp, sizeof(unexpected_ibp_t)); } } #endif #ifdef MONITOR_UNEXPECTED_IBP static void report_uibp(dcontext_t *dcontext, crowd_safe_thread_local_t *cstl, bool is_admitted, app_pc from, app_pc to, module_location_t *from_module, module_location_t *to_module, uint edge_index) { uint i; local_security_audit_state_t *csd = GET_CS_DATA(dcontext); clock_type_t interval, uibp_interval, suibp_interval; app_pc xsp = dcontext_get_app_stack_pointer(dcontext); ASSERT_TAG_XREF_LOCK if (csd->stack_spy_mark == 0UL) { CS_DET("SPY| Activating stack suspicion for %s("PX") -> %s("PX") at XSP="PX"\n", from_module->module_name, MODULAR_PC(from_module, from), to_module->module_name, MODULAR_PC(to_module, to), xsp); csd->stack_spy_mark = p2int(xsp); cstl->stack_suspicion.uib_count = (is_admitted > 0); cstl->stack_suspicion.suib_count = !is_admitted; if (from_module == to_module) { cstl->stack_suspicion.raising_edge_is_cross_module = false; cstl->stack_suspicion.raising_edge_index = edge_index; } else { cstl->stack_suspicion.raising_edge_is_cross_module = true; cstl->stack_suspicion.raising_edge_index = edge_index; } } else { if (is_admitted) { if (cstl->stack_suspicion.uib_count < 0xffff) cstl->stack_suspicion.uib_count++; } else { if (cstl->stack_suspicion.suib_count < 0xffff) cstl->stack_suspicion.suib_count++; } } uibp_interval = (cstl->thread_clock.clock - cstl->thread_clock.last_uibp_timestamp); suibp_interval = (cstl->thread_clock.clock - cstl->thread_clock.last_suibp_timestamp); if (uibp_interval < suibp_interval) interval = uibp_interval; else interval = suibp_interval; for (i = 0; i < UIBP_INTERVAL_COUNT; i++) { if (interval < uibp_intervals[i].interval) { if (global_uibp->observed_interval_count[i] < 0xffffffffUL) { global_uibp->observed_interval_count[i]++; // cs-todo: duplicate counters for intervals NOTIFY_INTERVAL_PREDICATE_EVENT(dcontext, uib_intervals, i); # ifdef MONITOR_UIBP_ONLINE if (is_report_threshold(&global_uibp->report_masks[i], global_uibp->observed_interval_count[i])) CS_LOG("UIBP| %d %s intervals (%d cycles each)\n", global_uibp->observed_interval_count[i], uibp_intervals[i].label, uibp_intervals[i].interval); # endif if (cstl->thread_clock.consecutive_interval_count[i] < 0xffffffffUL) { cstl->thread_clock.consecutive_interval_count[i]++; if (cstl->thread_clock.consecutive_interval_count[i] > global_uibp->max_consecutive_intervals[i]) { global_uibp->max_consecutive_intervals[i] = cstl->thread_clock.consecutive_interval_count[i]; # ifdef MONITOR_UIBP_ONLINE CS_LOG("UIBP| %d consecutive %s intervals (%d cycles each)\n", cstl->thread_clock.consecutive_interval_count[i], uibp_intervals[i].label, uibp_intervals[i].interval); # endif } } } } else { cstl->thread_clock.consecutive_interval_count[i] = 0; } if (is_admitted) { if (uibp_interval < uibp_intervals[i].interval) { if (global_uibp->observed_admitted_interval_count[i] < 0xffffffffUL) { global_uibp->observed_admitted_interval_count[i]++; if (cstl->thread_clock.last_uibp_is_admitted) { if (cstl->thread_clock.consecutive_admitted_interval_count[i] < 0xffffffffUL) { cstl->thread_clock.consecutive_admitted_interval_count[i]++; if (cstl->thread_clock.consecutive_admitted_interval_count[i] > global_uibp->max_consecutive_admitted_intervals[i]) global_uibp->max_consecutive_admitted_intervals[i] = cstl->thread_clock.consecutive_admitted_interval_count[i]; } } else { cstl->thread_clock.consecutive_admitted_interval_count[i] = 0; } } } else { cstl->thread_clock.consecutive_admitted_interval_count[i] = 0; } } if (!is_admitted) { if (suibp_interval < uibp_intervals[i].interval) { if (global_uibp->observed_suspicious_interval_count[i] < 0xffffffffUL) { global_uibp->observed_suspicious_interval_count[i]++; NOTIFY_INTERVAL_PREDICATE_EVENT(dcontext, suib_intervals, i); if (!cstl->thread_clock.last_uibp_is_admitted) { if (cstl->thread_clock.consecutive_suspicious_interval_count[i] < 0xffffffffUL) { cstl->thread_clock.consecutive_suspicious_interval_count[i]++; if (cstl->thread_clock.consecutive_suspicious_interval_count[i] > global_uibp->max_consecutive_suspicious_intervals[i]) global_uibp->max_consecutive_suspicious_intervals[i] = cstl->thread_clock.consecutive_suspicious_interval_count[i]; } } else { cstl->thread_clock.consecutive_suspicious_interval_count[i] = 0; } } } else { cstl->thread_clock.consecutive_suspicious_interval_count[i] = 0; } } } # ifdef MONITOR_UIBP_ONLINE if (interval < uibp_intervals[0].interval) { if (from_module == to_module) CS_LOG("UIBP| micro interval %d: %s("PX" -> "PX") %s -> %s, %d consecutive\n", (uint)interval, from_module->module_name, MODULAR_PC(from_module, from), MODULAR_PC(to_module, to), cstl->thread_clock.last_uibp_is_admitted ? "Adm" : "Susp", is_admitted ? "Adm" : "Susp", cstl->thread_clock.consecutive_interval_count[0]); else CS_LOG("UIBP| micro interval %d: %s("PX") -> %s("PX") %s -> %s, %d consecutive\n", (uint)interval, from_module->module_name, MODULAR_PC(from_module, from), to_module->module_name, MODULAR_PC(to_module, to), cstl->thread_clock.last_uibp_is_admitted ? "Adm" : "Susp", is_admitted ? "Adm" : "Susp", cstl->thread_clock.consecutive_interval_count[0]); } # endif if (!is_admitted) cstl->thread_clock.last_suibp_timestamp = cstl->thread_clock.clock; cstl->thread_clock.last_uibp_timestamp = cstl->thread_clock.clock; cstl->thread_clock.last_uibp_is_admitted = is_admitted; } #endif
<filename>Verification/SeckenApiSDK/AppDelegate.h // // AppDelegate.h // SeckenApiSDK // // Created by Secken_ck on 15/9/20. // Copyright © 2015年 Secken_ck. All rights reserved. // #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @property (nonatomic, retain) NSString * strDevice; //通过改字符串可以证书推送 @property (nonatomic, retain) NSString * userName; //授权SDK的用户名 @property (nonatomic, retain) NSString * userToken; //授权SDK返回的Token +(AppDelegate *)app; @end
#pragma once #include <linux/ioctl.h> #define KMESSAGED_IOC_MAGIC 0x6b #define KMESSAGED_IOC_S_REGUID _IOW(KMESSAGED_IOC_MAGIC, 0, char *) #define KMESSAGED_IOC_S_RDMOD _IOW(KMESSAGED_IOC_MAGIC, 1, int) #define KMESSAGED_IOC_RDMOD _IO(KMESSAGED_IOC_MAGIC, 2) #define KMESSAGED_IOC_S_MSGLMT _IOW(KMESSAGED_IOC_MAGIC, 3, int) #define KMESSAGED_IOC_MSGLMT _IO(KMESSAGED_IOC_MAGIC, 4) #define KMESSAGED_IOC_RMMSG _IOW(KMESSAGED_IOC_MAGIC, 5, char *) #define KMESSAGED_IOC_MAXNR 5 #define KMESSAGED_EXPORT #define KMESSAGED_MAX_USERNAME_LEN 20 #define KMESSAGED_MAX_MESSAGE_LEN 20 #define KMESSAGED_DEFAULT_MESSAGE_LIMIT 20 #define KMESSAGED_DEFAULT_TOTAL_MESSAGE_LIMIT 300 #define KMESSAGED_MAIN_QUEUE_NAME "org.chatatata.kmessaged" #define KMESSAGED_MAX_QUEUE_NAME_LEN 20 #define KMESSAGED_DEFAULT_DEV_MAJOR 0 #define KMESSAGED_DEFAULT_DEV_MINOR 0 #define KMESSAGED_DV_NAME "kmessaged"
/* * File: AtomicLock.h * Author: <NAME> * * Created on 2013_10_1 10:32 */ #ifndef ATOMICLOCK_H_ #define ATOMICLOCK_H_ #if defined( WIN32 ) || defined( _WIN32 ) || defined( __WIN32__ ) ////////////////////////////////////////////////////////////////////////// #include <intrin.h> ////////////////////////////////////////////////////////////////////////// extern "C" __declspec(dllimport) void __stdcall Sleep( unsigned long ms ); ////////////////////////////////////////////////////////////////////////// extern "C" long __cdecl _InterlockedExchange( long volatile *, long ); extern "C" long __cdecl _InterlockedExchangeAdd( long volatile *, long ); extern "C" long __cdecl _InterlockedIncrement( long volatile * ); extern "C" long __cdecl _InterlockedDecrement( long volatile * ); extern "C" long __cdecl _InterlockedCompareExchange( long volatile *, long, long ); extern "C" short __cdecl _InterlockedExchange16( short volatile *, short ); extern "C" short __cdecl _InterlockedExchangeAdd16( short volatile *, short ); extern "C" short __cdecl _InterlockedIncrement16( short volatile * ); extern "C" short __cdecl _InterlockedDecrement16( short volatile * ); extern "C" short __cdecl _InterlockedCompareExchange16( short volatile *, short, short ); extern "C" char __cdecl _InterlockedExchange8(char volatile *, char); extern "C" char __cdecl _InterlockedExchangeAdd8( char volatile *, char ); extern "C" char __cdecl _InterlockedCompareExchange8(char volatile *, char, char); # if defined(_M_IA64) || defined(_M_AMD64) || defined(__x86_64__) || defined(__x86_64) extern "C" void* __cdecl _InterlockedExchangePointer( void* volatile *, void* ); #endif extern "C" __int64 __cdecl _InterlockedCompareExchange64(__int64 volatile *, __int64, __int64); ////////////////////////////////////////////////////////////////////////// #define atomic_xchg(P, V) _InterlockedExchange((long volatile *)(P), (long)(V)) #define atomic_xadd(P, V) _InterlockedExchangeAdd((long volatile *)(P), (long)(V)) #define atomic_cmpxchg(P, N, O) _InterlockedCompareExchange((long volatile *)(P), (long)(N), (long)(O)) #define atomic_inc(P) _InterlockedIncrement((long volatile *)(P)) #define atomic_dec(P) _InterlockedDecrement((long volatile *)(P)) #define atomic_xchg16(P, V) _InterlockedExchange16((short volatile *)(P), (short)(V)) #define atomic_xadd16(P, V) _InterlockedExchangeAdd16((short volatile *)(P), (short)(V)) #define atomic_cmpxchg16(P, N, O) _InterlockedCompareExchange16((short volatile *)(P), (short)(N), (short)(O)) #define atomic_inc16(P) _InterlockedIncrement16((short volatile *)(P)) #define atomic_dec16(P) _InterlockedDecrement16((short volatile *)(P)) #define atomic_xchg8(P, V) _InterlockedExchange8((char volatile *)(P), (char)(V)) #define atomic_xadd8(P, V) _InterlockedExchangeAdd8((char volatile *)(P), (char)(V)) #define atomic_cmpxchg8(P, N, O) _InterlockedCompareExchange8((char volatile *)(P), (char)(N), (char)(O)) #define atomic_inc8(P) _InterlockedExchangeAdd8((char volatile *)(P), 1) #define atomic_dec8(P) _InterlockedExchangeAdd8((char volatile *)(P), -1) #if defined(_M_IA64) || defined(_M_AMD64) || defined(__x86_64__) || defined(__x86_64) #define atomic_xchgptr(P, V) _InterlockedExchangePointer((void* volatile *)(P), (void*) (V)) #else #define atomic_xchgptr(P, V) _InterlockedExchange((long volatile *)(P), (long)(V)) #endif #define atomic_cmpxchg64(P, N, O) _InterlockedCompareExchange64((long long volatile *)(P), (long long)(N), (long long)(O)) static __forceinline __int64 InterlockedIncre64( __int64 volatile *Addend) { __int64 Old; do { Old = *Addend; } while (_InterlockedCompareExchange64(Addend, Old + 1, Old) != Old); return Old + 1; } #define atomic_inc64(P) InterlockedIncre64((__int64 volatile *)(P)) static __forceinline __int64 InterlockedXChg64(__int64 volatile *Target, __int64 Value) { __int64 Old; do { Old = *Target; } while (_InterlockedCompareExchange64(Target, Value, Old) != Old); return Old; } #define atomic_xchg64(P, V) InterlockedXChg64((__int64 volatile *)(P), (__int64)(V)) static __forceinline long atomic_or_fetch (volatile long *lock, long value) { long old, newvalue; do { old = *lock; newvalue = old | value; } while (_InterlockedCompareExchange(lock, newvalue, old) != old); return newvalue; } static __forceinline long atomic_and_fetch (volatile long *lock, long value) { long old, newvalue; do { old = *lock; newvalue = old & value; } while (_InterlockedCompareExchange(lock, newvalue, old) != old); return newvalue; } ////////////////////////////////////////////////////////////////////////// #if defined( _MSC_VER ) && _MSC_VER >= 1310 extern "C" void _ReadWriteBarrier(); #pragma intrinsic( _ReadWriteBarrier ) #define memory_barrier() _ReadWriteBarrier() #endif #define smt_pause() __asm { rep nop } inline void cpu_relax( unsigned k ) { if( k < 4 ) { } else if( k < 16) { smt_pause(); } else if( k < 32 ) { Sleep( 0 ); } else { Sleep( 1 ); } } #elif defined(__GNUC__) #if defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__) # define ARM_BARRIER "dmb" #elif defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) # define ARM_BARRIER "mcr p15, 0, r0, c7, c10, 5" #else # define ARM_BARRIER "" #endif #define memory_barrier() __asm__ __volatile__( ARM_BARRIER : : : "memory" ) #define atomic_xchg __sync_lock_test_and_set #define atomic_xadd __sync_fetch_and_add #define atomic_cmpxchg(P, N, O) (__sync_val_compare_and_swap((P), (O), (N))) #define atomic_inc(P) __sync_add_and_fetch((P), 1) #define atomic_dec(P) __sync_sub_and_fetch((P), 1) #define atomic_xchg16 __sync_lock_test_and_set #define atomic_xadd16 __sync_fetch_and_add #define atomic_cmpxchg16(P, N, O) (__sync_val_compare_and_swap((P), (O), (N))) #define atomic_inc16(P) __sync_add_and_fetch((P), 1) #define atomic_dec16(P) __sync_sub_and_fetch((P), 1) #define atomic_xchg8 __sync_lock_test_and_set #define atomic_xadd8 __sync_fetch_and_add #define atomic_cmpxchg8(P, N, O) (__sync_val_compare_and_swap((P), (O), (N))) #define atomic_inc8(P) __sync_add_and_fetch((P), 1) #define atomic_dec8(P) __sync_sub_and_fetch((P), 1) #define atomic_xchgptr __sync_lock_test_and_set #define atomic_inc64(P) __sync_add_and_fetch((P), 1) #define atomic_xchg64 __sync_lock_test_and_set #define atomic_cmpxchg64(P, N, O) (__sync_val_compare_and_swap((P), (O), (N))) #define atomic_or_fetch __sync_or_and_fetch #define atomic_and_fetch __sync_and_and_fetch #define atomic_sub_fetch __sync_sub_and_fetch #define atomic_fetch_xor __sync_fetch_and_xor #if defined( __APPLE__ ) || defined( __ANDROID__ ) || defined( ANDROID ) #define smt_pause() __asm__ __volatile__( "nop" : : : "memory" ) #else #define smt_pause() __asm__ __volatile__( "rep; nop" : : : "memory" ) #endif //#if defined(_POSIX_THREADS) && (_POSIX_THREADS+0 >= 0) #include <sched.h> #include <time.h> inline void cpu_relax( unsigned k ) { if( k < 4 ) { } else if(k < 16) { smt_pause(); } else if( k < 32 || k & 1 ) { sched_yield(); } else { // g++ -Wextra warns on {} or {0} struct timespec rqtp = { 0, 0 }; // POSIX says that timespec has tv_sec and tv_nsec // But it doesn't guarantee order or placement rqtp.tv_sec = 0; rqtp.tv_nsec = 1000; nanosleep( &rqtp, 0 ); } } //#endif #endif #endif // ATOMICLOCK_H_
#ifndef _IP_CONNTRACK_TALK_H #define _IP_CONNTRACK_TALK_H /* TALK tracking. */ #ifdef __KERNEL__ #include <linux/in.h> #include <linux/netfilter_ipv4/lockhelp.h> /* Protects talk part of conntracks */ DECLARE_LOCK_EXTERN(ip_talk_lock); #endif #define TALK_PORT 517 #define NTALK_PORT 518 /* talk structures and constants from <protocols/talkd.h> */ /* * 4.3BSD struct sockaddr */ struct talk_addr { u_int16_t ta_family; u_int16_t ta_port; u_int32_t ta_addr; u_int32_t ta_junk1; u_int32_t ta_junk2; }; #define TALK_OLD_NSIZE 9 #define TALK_NSIZE 12 #define TALK_TTY_NSIZE 16 /* * Client->server request message formats. */ struct talk_msg { u_char type; /* request type, see below */ char l_name[TALK_OLD_NSIZE];/* caller's name */ char r_name[TALK_OLD_NSIZE];/* callee's name */ u_char pad; u_int32_t id_num; /* message id */ int32_t pid; /* caller's process id */ char r_tty[TALK_TTY_NSIZE];/* callee's tty name */ struct talk_addr addr; /* old (4.3) style */ struct talk_addr ctl_addr; /* old (4.3) style */ }; struct ntalk_msg { u_char vers; /* protocol version */ u_char type; /* request type, see below */ u_char answer; /* not used */ u_char pad; u_int32_t id_num; /* message id */ struct talk_addr addr; /* old (4.3) style */ struct talk_addr ctl_addr; /* old (4.3) style */ int32_t pid; /* caller's process id */ char l_name[TALK_NSIZE];/* caller's name */ char r_name[TALK_NSIZE];/* callee's name */ char r_tty[TALK_TTY_NSIZE];/* callee's tty name */ }; struct ntalk2_msg { u_char vers; /* talk protocol version */ u_char type; /* request type */ u_char answer; /* */ u_char extended; /* !0 if additional parts */ u_int32_t id_num; /* message id number (dels) */ struct talk_addr addr; /* target address */ struct talk_addr ctl_addr; /* reply to address */ int32_t pid; /* caller's process id */ char l_name[TALK_NSIZE]; /* caller's name */ char r_name[TALK_NSIZE]; /* callee's name */ char r_tty[TALK_TTY_NSIZE]; /* callee's tty */ }; /* * Server->client response message formats. */ struct talk_response { u_char type; /* type of request message, see below */ u_char answer; /* response to request message, see below */ u_char pad[2]; u_int32_t id_num; /* message id */ struct talk_addr addr; /* address for establishing conversation */ }; struct ntalk_response { u_char vers; /* protocol version */ u_char type; /* type of request message, see below */ u_char answer; /* response to request message, see below */ u_char pad; u_int32_t id_num; /* message id */ struct talk_addr addr; /* address for establishing conversation */ }; struct ntalk2_response { u_char vers; /* protocol version */ u_char type; /* type of request message */ u_char answer; /* response to request */ u_char rvers; /* Version of answering vers*/ u_int32_t id_num; /* message id number */ struct talk_addr addr; /* address for connection */ /* This is at the end to compatiblize this with NTALK version. */ char r_name[TALK_NSIZE]; /* callee's name */ }; #define TALK_STR(data, talk_str, member) ((struct talk_str *)data)->member) #define TALK_RESP(data, ver, member) (ver ? ((struct ntalk_response *)data)->member : ((struct talk_response *)data)->member) #define TALK_MSG(data, ver, member) (ver ? ((struct ntalk_msg *)data)->member : ((struct talk_msg *)data)->member) #define TALK_VERSION 0 /* protocol versions */ #define NTALK_VERSION 1 #define NTALK2_VERSION 2 /* message type values */ #define LEAVE_INVITE 0 /* leave invitation with server */ #define LOOK_UP 1 /* check for invitation by callee */ #define DELETE 2 /* delete invitation by caller */ #define ANNOUNCE 3 /* announce invitation by caller */ /* NTALK2 */ #define REPLY_QUERY 4 /* request reply data from local daemon */ /* answer values */ #define SUCCESS 0 /* operation completed properly */ #define NOT_HERE 1 /* callee not logged in */ #define FAILED 2 /* operation failed for unexplained reason */ #define MACHINE_UNKNOWN 3 /* caller's machine name unknown */ #define PERMISSION_DENIED 4 /* callee's tty doesn't permit announce */ #define UNKNOWN_REQUEST 5 /* request has invalid type value */ #define BADVERSION 6 /* request has invalid protocol version */ #define BADADDR 7 /* request has invalid addr value */ #define BADCTLADDR 8 /* request has invalid ctl_addr value */ /* NTALK2 */ #define NO_CALLER 9 /* no-one calling answer from REPLY */ #define TRY_HERE 10 /* Not on this machine, try this */ #define SELECTIVE_REFUSAL 11 /* User Filter refusal. */ #define MAX_RESPONSE_TYPE 11 /* Make sure this is updated */ /* This structure exists only once per master */ struct ip_ct_talk_master { }; struct ip_conntrack; struct ip_conntrack_expect; extern unsigned int (*ip_nat_talk_resp_hook)(struct sk_buff **pskb, struct ip_conntrack_expect *exp, u_char type, u_char answer, struct talk_addr *addr); extern unsigned int (*ip_nat_talk_msg_hook)(struct sk_buff **pskb, struct ip_conntrack *ct, u_char type, struct talk_addr *addr, struct talk_addr *ctl_addr); void ip_ct_talk_expect(struct ip_conntrack *ct, struct ip_conntrack_expect *exp); void ip_ct_ntalk_expect(struct ip_conntrack *ct, struct ip_conntrack_expect *exp); #endif /* _IP_CONNTRACK_TALK_H */
<filename>UrhoEditor/GuiBuilder/Menus/Urho/UrhoSpecialActionMenu.h #pragma once #include "../../GuiBuilder.h" namespace UrhoUI { class UrhoSpecialActionMenu : public SprueEditor::GuiBuilder { public: virtual void Build(SprueEditor::UrhoEditor* editor) override; }; }
<filename>src/Main/usecases.h #ifndef HEADER_USECASES #define HEADER_USECASES #include "dataBase.h" /*! \file usescases.h \brief Genere toutes les requetes SQL et affiche les donnees en retour. \version 0.1 Permet d'executer les differentes commandes SQL, de guider l'utilisateur vers les donnees souhaitees et d'afficher les donnees. */ /*! \def sizeName \brief Definition du taille colonne "nom" */ #define sizeName 20 /*! \def sizeNum \brief Definition de la taille colonne "num" + "hp" + "atk" + "def" + autres chiffres */ #define sizeNum 5 /*! \def sizeLabel \brief Definition du taille colonne "label" */ #define sizeLabel 20 /*! \def sizeDesc \brief Definition de la taille colonne "desc" */ #define sizeDesc 200 /*! \fn int choixPokemon(int *pokeId, char *pokeName); \brief Cette fonction traite la saisie d'un pokemon par son nom ou son numero et renvoi l'id correspondant. \param pokeId pointeur sur variable contenant l'id du pokemon. \param dataBase pointeur sur la base de donnees. \return La fonction renvoie un entier de valeur 0 si la saisie s'est deroulee sans erreur et 1 si erreur de saisie */ int choicePokemon(int *pokeId, DataBase *dataBase); /*! \fn void pokemonList(int pokeId, DataBase *dataBase); \brief Cette fonction commande et affiche la liste de tous les pokemons. \param dataBase pointeur sur la base de donnees. \param pokeId pointeur sur variable contenant l'id du pokemon. */ void pokemonList(int pokeId, DataBase *dataBase); /*! \fn void myPokemonList(DataBase *dataBase); \brief Cette fonction commande et affiche la liste des pokemons possedes par l'utilisateur. \param dataBase pointeur sur la base de donnees. */ void myPokemonList(DataBase *dataBase); /*! \fn void pokemonProfil(int pokeId, DataBase *dataBase); \brief Cette fonction commande et affiche le profil detaille d'un pokemon demande par l'utilisateur. \param dataBase pointeur sur la base de donnees. */ int pokemonProfil(int pokeId, DataBase *dataBase); /*! \fn void updatePokemonList(DataBase *dataBase); \brief Cette fonction commande l'ajout d'un pokemon a la liste des pokemons possedes par l'utilisateur. \param dataBase pointeur sur la base de donnees. */ void updatePokemonList(DataBase *dataBase); /*! \fn void allCouplingPossibilitiesPokemonList(DataBase *dataBase); \brief Cette fonction commande et affiche la liste des compatibilitees d'accouplement d'un pokemon saisi par l'utilisateur. \param dataBase pointeur sur la base de donnees. */ void allCouplingPossibilitiesPokemonList(DataBase *dataBase); /*! \fn myCouplingPossibilitiesPokemonList(DataBase *dataBase); \brief Cette fonction commande et affiche la liste des pokemon possedes et compatibles en accouplement d'un pokemon saisi par l'utilisateur. \param dataBase pointeur sur la base de donnees. */ void myCouplingPossibilitiesPokemonList(DataBase *dataBase); /*! \fn void updatePokemon(DataBase *dataBase); \brief Cette fonction commande et modifie une caracteristique pokemon saisie par l'administrateur. \param dataBase pointeur sur la base de donnees. */ void updatePokemon(DataBase *dataBase); /*! \fn void addPokemon(DataBase *dataBase); \brief Cette fonction commande l'ajout d'un pokemon dans la base de donnees par l'administrateur. \param dataBase pointeur sur la base de donnees. */ void addPokemon(DataBase *dataBase); /*! \fn void deletePokemon(DataBase *dataBase); \brief Cette fonction commande la suppression d'un pokemon dans la base de donnees par l'administrateur, placement du "#" dans le fichier. \param dataBase pointeur sur la base de donnees. */ void deletePokemon(DataBase *dataBase); /*! \fn void administrator(DataBase *dataBase); \brief Cette fonction permet le rechargement des donnees de la base. \param dataBase pointeur sur la base de donnees. */ void administrator(DataBase *dataBase); /*prototype fonction: Passage en mode administration*/ #endif /* HEADER_USECASES */
/* Copyright (C) 2007-2010 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ /** * \file * * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> * * \file DCE/RPC parser and decoder * * \todo Remove all the unnecessary per byte incremental loops with a full one * time jump, i.e. * * input[0], input_len * for (i = 0; i < x; i++) * input++; * * with * * input += x; * * You'll be surprised at how many such cases we have here. We also need * to do the same for htp parser. Should speed up the engine drastically. */ #include "suricata-common.h" #include "suricata.h" #include "debug.h" #include "decode.h" #include "threads.h" #include "util-print.h" #include "util-pool.h" #include "util-debug.h" #include "flow-util.h" #include "detect-engine-state.h" #include "stream-tcp-private.h" #include "stream-tcp-reassemble.h" #include "stream-tcp.h" #include "stream.h" #include "app-layer-protos.h" #include "app-layer-parser.h" #include "app-layer.h" #include "util-spm.h" #include "util-unittest.h" #include "app-layer-dcerpc.h" enum { DCERPC_FIELD_NONE = 0, DCERPC_PARSE_DCERPC_HEADER, DCERPC_PARSE_DCERPC_BIND, DCERPC_PARSE_DCERPC_BIND_ACK, DCERPC_PARSE_DCERPC_REQUEST, /* must be last */ DCERPC_FIELD_MAX, }; void DCERPCUuidListFree(DCERPCUuidEntryList *list); /* \brief hexdump function from libdnet, used for debugging only */ void hexdump(/*Flow *f,*/ const void *buf, size_t len) { /* dumps len bytes of *buf to stdout. Looks like: * [0000] 75 6E 6B 6E 6F 77 6E 20 * 30 FF 00 00 00 00 39 00 unknown 0.....9. * (in a single line of course) */ const unsigned char *p = buf; unsigned char c; size_t n; char bytestr[4] = {0}; char addrstr[17] = {0}; char hexstr[ 16*3 + 5] = {0}; char charstr[16*1 + 5] = {0}; for (n=1; n<=len; n++) { if (n%16 == 1) { /* store address for this line */ #if __WORDSIZE == 64 snprintf(addrstr, sizeof(addrstr), "%.4"PRIx64, ((uint64_t)p-(uint64_t)buf) ); #else snprintf(addrstr, sizeof(addrstr), "%.4"PRIx32, ((uint32_t)p-(uint32_t)buf) ); #endif } c = *p; if (isalnum(c) == 0) { c = '.'; } /* store hex str (for left side) */ snprintf(bytestr, sizeof(bytestr), "%02X ", *p); strlcat(hexstr, bytestr, sizeof(hexstr)-strlen(hexstr)-1); /* store char str (for right side) */ snprintf(bytestr, sizeof(bytestr), "%c", c); strlcat(charstr, bytestr, sizeof(charstr)-strlen(charstr)-1); if(n%16 == 0) { /* line completed */ printf("[%4.4s] %-50.50s %s\n", addrstr, hexstr, charstr); hexstr[0] = 0; charstr[0] = 0; } else if(n%8 == 0) { /* half line: add whitespaces */ strlcat(hexstr, " ", sizeof(hexstr)-strlen(hexstr)-1); strlcat(charstr, " ", sizeof(charstr)-strlen(charstr)-1); } p++; /* next byte */ } if (strlen(hexstr) > 0) { /* print rest of buffer if not empty */ printf("[%4.4s] %-50.50s %s\n", addrstr, hexstr, charstr); } } /** * \brief printUUID function used to print UUID, Major and Minor Version Number * and if it was Accepted or Rejected in the BIND_ACK. */ void printUUID(const char *type, DCERPCUuidEntry *uuid) { uint8_t i = 0; if (uuid == NULL) { return; } printf("%s UUID [%2u] %s ", type, uuid->ctxid, (uuid->result == 0) ? "Accepted" : "Rejected"); for (i = 0; i < 16; i++) { printf("%02x", uuid->uuid[i]); } printf(" Major Version 0x%04x Minor Version 0x%04x\n", uuid->version, uuid->versionminor); } /** * \brief DCERPCParseSecondaryAddr reads secondaryaddrlen bytes from the BIND_ACK * DCERPC call. */ static uint32_t DCERPCParseSecondaryAddr(DCERPC *dcerpc, uint8_t *input, uint32_t input_len) { SCEnter(); uint8_t *p = input; while (dcerpc->dcerpcbindbindack.secondaryaddrlenleft-- && input_len--) { SCLogDebug("0x%02x ", *p); p++; } dcerpc->bytesprocessed += (p - input); SCReturnUInt((uint32_t)(p - input)); } static uint32_t PaddingParser(DCERPC *dcerpc, uint8_t *input, uint32_t input_len) { SCEnter(); uint8_t *p = input; while (dcerpc->padleft-- && input_len--) { SCLogDebug("0x%02x ", *p); p++; } dcerpc->bytesprocessed += (p - input); SCReturnUInt((uint32_t)(p - input)); } static uint32_t DCERPCGetCTXItems(DCERPC *dcerpc, uint8_t *input, uint32_t input_len) { SCEnter(); uint8_t *p = input; if (input_len) { switch (dcerpc->dcerpcbindbindack.ctxbytesprocessed) { case 0: if (input_len >= 4) { dcerpc->dcerpcbindbindack.numctxitems = *p; dcerpc->dcerpcbindbindack.numctxitemsleft = dcerpc->dcerpcbindbindack.numctxitems; dcerpc->dcerpcbindbindack.ctxbytesprocessed += 4; dcerpc->bytesprocessed += 4; SCReturnUInt(4U); } else { dcerpc->dcerpcbindbindack.numctxitems = *(p++); dcerpc->dcerpcbindbindack.numctxitemsleft = dcerpc->dcerpcbindbindack.numctxitems; if (!(--input_len)) break; } /* fall through */ case 1: p++; if (!(--input_len)) break; /* fall through */ case 2: p++; if (!(--input_len)) break; /* fall through */ case 3: p++; input_len--; break; } } dcerpc->dcerpcbindbindack.ctxbytesprocessed += (p - input); dcerpc->bytesprocessed += (p - input); SCReturnUInt((uint32_t)(p - input)); } /** * \brief DCERPCParseBINDCTXItem is called for each CTXItem found the DCERPC BIND call. * each UUID is added to a TAILQ. */ static uint32_t DCERPCParseBINDCTXItem(DCERPC *dcerpc, uint8_t *input, uint32_t input_len) { SCEnter(); uint8_t *p = input; if (input_len) { switch (dcerpc->dcerpcbindbindack.ctxbytesprocessed) { case 0: if (input_len >= 44) { if (dcerpc->dcerpchdr.packed_drep[0] & 0x10) { dcerpc->dcerpcbindbindack.ctxid = *(p); dcerpc->dcerpcbindbindack.ctxid |= *(p + 1) << 8; dcerpc->dcerpcbindbindack.uuid[3] = *(p + 4); dcerpc->dcerpcbindbindack.uuid[2] = *(p + 5); dcerpc->dcerpcbindbindack.uuid[1] = *(p + 6); dcerpc->dcerpcbindbindack.uuid[0] = *(p + 7); dcerpc->dcerpcbindbindack.uuid[5] = *(p + 8); dcerpc->dcerpcbindbindack.uuid[4] = *(p + 9); dcerpc->dcerpcbindbindack.uuid[7] = *(p + 10); dcerpc->dcerpcbindbindack.uuid[6] = *(p + 11); dcerpc->dcerpcbindbindack.uuid[8] = *(p + 12); dcerpc->dcerpcbindbindack.uuid[9] = *(p + 13); dcerpc->dcerpcbindbindack.uuid[10] = *(p + 14); dcerpc->dcerpcbindbindack.uuid[11] = *(p + 15); dcerpc->dcerpcbindbindack.uuid[12] = *(p + 16); dcerpc->dcerpcbindbindack.uuid[13] = *(p + 17); dcerpc->dcerpcbindbindack.uuid[14] = *(p + 18); dcerpc->dcerpcbindbindack.uuid[15] = *(p + 19); dcerpc->dcerpcbindbindack.version = *(p + 20); dcerpc->dcerpcbindbindack.version |= *(p + 21) << 8; dcerpc->dcerpcbindbindack.versionminor = *(p + 22); dcerpc->dcerpcbindbindack.versionminor |= *(p + 23) << 8; } else { /* Big Endian */ dcerpc->dcerpcbindbindack.ctxid = *(p) << 8; dcerpc->dcerpcbindbindack.ctxid |= *(p + 1); dcerpc->dcerpcbindbindack.uuid[0] = *(p + 4); dcerpc->dcerpcbindbindack.uuid[1] = *(p + 5); dcerpc->dcerpcbindbindack.uuid[2] = *(p + 6); dcerpc->dcerpcbindbindack.uuid[3] = *(p + 7); dcerpc->dcerpcbindbindack.uuid[4] = *(p + 8); dcerpc->dcerpcbindbindack.uuid[5] = *(p + 9); dcerpc->dcerpcbindbindack.uuid[6] = *(p + 10); dcerpc->dcerpcbindbindack.uuid[7] = *(p + 11); dcerpc->dcerpcbindbindack.uuid[8] = *(p + 12); dcerpc->dcerpcbindbindack.uuid[9] = *(p + 13); dcerpc->dcerpcbindbindack.uuid[10] = *(p + 14); dcerpc->dcerpcbindbindack.uuid[11] = *(p + 15); dcerpc->dcerpcbindbindack.uuid[12] = *(p + 16); dcerpc->dcerpcbindbindack.uuid[13] = *(p + 17); dcerpc->dcerpcbindbindack.uuid[14] = *(p + 18); dcerpc->dcerpcbindbindack.uuid[15] = *(p + 19); dcerpc->dcerpcbindbindack.version = *(p + 20) << 8; dcerpc->dcerpcbindbindack.version |= *(p + 21); dcerpc->dcerpcbindbindack.versionminor = *(p + 22) << 8; dcerpc->dcerpcbindbindack.versionminor |= *(p + 23); } //if (dcerpc->dcerpcbindbindack.ctxid == dcerpc->dcerpcbindbindack.numctxitems // - dcerpc->dcerpcbindbindack.numctxitemsleft) { dcerpc->dcerpcbindbindack.uuid_entry = (DCERPCUuidEntry *)SCCalloc(1, sizeof(DCERPCUuidEntry)); if (dcerpc->dcerpcbindbindack.uuid_entry == NULL) { SCLogDebug("UUID Entry is NULL"); SCReturnUInt(0); } dcerpc->dcerpcbindbindack.uuid_entry->internal_id = dcerpc->dcerpcbindbindack.uuid_internal_id++; memcpy(dcerpc->dcerpcbindbindack.uuid_entry->uuid, dcerpc->dcerpcbindbindack.uuid, sizeof(dcerpc->dcerpcbindbindack.uuid)); dcerpc->dcerpcbindbindack.uuid_entry->ctxid = dcerpc->dcerpcbindbindack.ctxid; dcerpc->dcerpcbindbindack.uuid_entry->version = dcerpc->dcerpcbindbindack.version; dcerpc->dcerpcbindbindack.uuid_entry->versionminor = dcerpc->dcerpcbindbindack.versionminor; /* store the first frag flag in the uuid as pfc_flags will * be overwritten by new packets. */ if (dcerpc->dcerpchdr.pfc_flags & PFC_FIRST_FRAG) { dcerpc->dcerpcbindbindack.uuid_entry->flags |= DCERPC_UUID_ENTRY_FLAG_FF; } TAILQ_INSERT_HEAD(&dcerpc->dcerpcbindbindack.uuid_list, dcerpc->dcerpcbindbindack.uuid_entry, next); #ifdef UNITTESTS if (RunmodeIsUnittests()) { printUUID("BIND", dcerpc->dcerpcbindbindack.uuid_entry); } #endif dcerpc->dcerpcbindbindack.numctxitemsleft--; dcerpc->bytesprocessed += (44); dcerpc->dcerpcbindbindack.ctxbytesprocessed += (44); SCReturnUInt(44U); //} else { // SCLogDebug("ctxitem %u, expected %u\n", dcerpc->dcerpcbindbindack.ctxid, // dcerpc->dcerpcbindbindack.numctxitems - dcerpc->dcerpcbindbindack.numctxitemsleft); // SCReturnUInt(0); //} } else { if (dcerpc->dcerpchdr.packed_drep[0] & 0x10) { dcerpc->dcerpcbindbindack.ctxid = *(p++); } else { dcerpc->dcerpcbindbindack.ctxid = *(p++) << 8; } if (!(--input_len)) break; } /* fall through */ case 1: if (dcerpc->dcerpchdr.packed_drep[0] & 0x10) { dcerpc->dcerpcbindbindack.ctxid |= *(p++) << 8; } else { dcerpc->dcerpcbindbindack.ctxid |= *(p++); } if (!(--input_len)) break; /* fall through */ case 2: /* num transact items */ p++; if (!(--input_len)) break; /* fall through */ case 3: /* reserved */ p++; if (!(--input_len)) break; /* fall through */ case 4: if (dcerpc->dcerpchdr.packed_drep[0] & 0x10) { dcerpc->dcerpcbindbindack.uuid[3] = *(p++); } else { dcerpc->dcerpcbindbindack.uuid[0] = *(p++); } if (!(--input_len)) break; /* fall through */ case 5: if (dcerpc->dcerpchdr.packed_drep[0] & 0x10) { dcerpc->dcerpcbindbindack.uuid[2] = *(p++); } else { dcerpc->dcerpcbindbindack.uuid[1] = *(p++); } if (!(--input_len)) break; /* fall through */ case 6: if (dcerpc->dcerpchdr.packed_drep[0] & 0x10) { dcerpc->dcerpcbindbindack.uuid[1] = *(p++); } else { dcerpc->dcerpcbindbindack.uuid[2] = *(p++); } if (!(--input_len)) break; /* fall through */ case 7: if (dcerpc->dcerpchdr.packed_drep[0] & 0x10) { dcerpc->dcerpcbindbindack.uuid[0] = *(p++); } else { dcerpc->dcerpcbindbindack.uuid[3] = *(p++); } if (!(--input_len)) break; /* fall through */ case 8: if (dcerpc->dcerpchdr.packed_drep[0] & 0x10) { dcerpc->dcerpcbindbindack.uuid[5] = *(p++); } else { dcerpc->dcerpcbindbindack.uuid[4] = *(p++); } if (!(--input_len)) break; /* fall through */ case 9: if (dcerpc->dcerpchdr.packed_drep[0] & 0x10) { dcerpc->dcerpcbindbindack.uuid[4] = *(p++); } else { dcerpc->dcerpcbindbindack.uuid[5] = *(p++); } if (!(--input_len)) break; /* fall through */ case 10: if (dcerpc->dcerpchdr.packed_drep[0] & 0x10) { dcerpc->dcerpcbindbindack.uuid[7] = *(p++); } else { dcerpc->dcerpcbindbindack.uuid[6] = *(p++); } if (!(--input_len)) break; /* fall through */ case 11: if (dcerpc->dcerpchdr.packed_drep[0] & 0x10) { dcerpc->dcerpcbindbindack.uuid[6] = *(p++); } else { dcerpc->dcerpcbindbindack.uuid[7] = *(p++); } if (!(--input_len)) break; /* fall through */ case 12: /* The following bytes are in the same order for both big and little endian */ dcerpc->dcerpcbindbindack.uuid[8] = *(p++); if (!(--input_len)) break; /* fall through */ case 13: dcerpc->dcerpcbindbindack.uuid[9] = *(p++); if (!(--input_len)) break; /* fall through */ case 14: dcerpc->dcerpcbindbindack.uuid[10] = *(p++); if (!(--input_len)) break; /* fall through */ case 15: dcerpc->dcerpcbindbindack.uuid[11] = *(p++); if (!(--input_len)) break; /* fall through */ case 16: dcerpc->dcerpcbindbindack.uuid[12] = *(p++); if (!(--input_len)) break; /* fall through */ case 17: dcerpc->dcerpcbindbindack.uuid[13] = *(p++); if (!(--input_len)) break; /* fall through */ case 18: dcerpc->dcerpcbindbindack.uuid[14] = *(p++); if (!(--input_len)) break; /* fall through */ case 19: dcerpc->dcerpcbindbindack.uuid[15] = *(p++); if (!(--input_len)) break; /* fall through */ case 20: if (dcerpc->dcerpchdr.packed_drep[0] & 0x10) { dcerpc->dcerpcbindbindack.version = *(p++); } else { dcerpc->dcerpcbindbindack.version = *(p++) << 8; } if (!(--input_len)) break; /* fall through */ case 21: if (dcerpc->dcerpchdr.packed_drep[0] & 0x10) { dcerpc->dcerpcbindbindack.version |= *(p++) << 8; } else { dcerpc->dcerpcbindbindack.version |= *(p++); } if (!(--input_len)) break; /* fall through */ case 22: if (dcerpc->dcerpchdr.packed_drep[0] & 0x10) { dcerpc->dcerpcbindbindack.versionminor = *(p++); } else { dcerpc->dcerpcbindbindack.versionminor = *(p++) << 8; } if (!(--input_len)) break; /* fall through */ case 23: if (dcerpc->dcerpchdr.packed_drep[0] & 0x10) { dcerpc->dcerpcbindbindack.versionminor |= *(p++) << 8; } else { dcerpc->dcerpcbindbindack.versionminor |= *(p++); } if (!(--input_len)) break; /* fall through */ case 24: p++; if (!(--input_len)) break; /* fall through */ case 25: p++; if (!(--input_len)) break; /* fall through */ case 26: p++; if (!(--input_len)) break; /* fall through */ case 27: p++; if (!(--input_len)) break; /* fall through */ case 28: p++; if (!(--input_len)) break; /* fall through */ case 29: p++; if (!(--input_len)) break; /* fall through */ case 30: p++; if (!(--input_len)) break; /* fall through */ case 31: p++; if (!(--input_len)) break; /* fall through */ case 32: p++; if (!(--input_len)) break; /* fall through */ case 33: p++; if (!(--input_len)) break; /* fall through */ case 34: p++; if (!(--input_len)) break; /* fall through */ case 35: p++; if (!(--input_len)) break; /* fall through */ case 36: p++; if (!(--input_len)) break; /* fall through */ case 37: p++; if (!(--input_len)) break; /* fall through */ case 38: p++; if (!(--input_len)) break; /* fall through */ case 39: p++; if (!(--input_len)) break; /* fall through */ case 40: p++; if (!(--input_len)) break; /* fall through */ case 41: p++; if (!(--input_len)) break; /* fall through */ case 42: p++; if (!(--input_len)) break; /* fall through */ case 43: p++; --input_len; //if (dcerpc->dcerpcbindbindack.ctxid == dcerpc->dcerpcbindbindack.numctxitems - dcerpc->dcerpcbindbindack.numctxitemsleft) { dcerpc->dcerpcbindbindack.uuid_entry = (DCERPCUuidEntry *) SCCalloc(1, sizeof(DCERPCUuidEntry)); if (dcerpc->dcerpcbindbindack.uuid_entry == NULL) { SCLogDebug("UUID Entry is NULL\n"); SCReturnUInt(0); } dcerpc->dcerpcbindbindack.uuid_entry->internal_id = dcerpc->dcerpcbindbindack.uuid_internal_id++; memcpy(dcerpc->dcerpcbindbindack.uuid_entry->uuid, dcerpc->dcerpcbindbindack.uuid, sizeof(dcerpc->dcerpcbindbindack.uuid)); dcerpc->dcerpcbindbindack.uuid_entry->ctxid = dcerpc->dcerpcbindbindack.ctxid; dcerpc->dcerpcbindbindack.uuid_entry->version = dcerpc->dcerpcbindbindack.version; dcerpc->dcerpcbindbindack.uuid_entry->versionminor = dcerpc->dcerpcbindbindack.versionminor; /* store the first frag flag in the uuid as pfc_flags will * be overwritten by new packets. */ if (dcerpc->dcerpchdr.pfc_flags & PFC_FIRST_FRAG) { dcerpc->dcerpcbindbindack.uuid_entry->flags |= DCERPC_UUID_ENTRY_FLAG_FF; } TAILQ_INSERT_HEAD(&dcerpc->dcerpcbindbindack.uuid_list, dcerpc->dcerpcbindbindack.uuid_entry, next); #ifdef UNITTESTS if (RunmodeIsUnittests()) { printUUID("BINDACK", dcerpc->dcerpcbindbindack.uuid_entry); } #endif dcerpc->dcerpcbindbindack.numctxitemsleft--; dcerpc->bytesprocessed += (p - input); dcerpc->dcerpcbindbindack.ctxbytesprocessed += (p - input); SCReturnUInt((uint32_t)(p - input)); //} else { // SCLogDebug("ctxitem %u, expected %u\n", dcerpc->dcerpcbindbindack.ctxid, // dcerpc->dcerpcbindbindack.numctxitems - dcerpc->dcerpcbindbindack.numctxitemsleft); // SCReturnUInt(0); //} break; } } dcerpc->dcerpcbindbindack.ctxbytesprocessed += (p - input); dcerpc->bytesprocessed += (p - input); SCReturnUInt((uint32_t)(p - input)); } /** * \brief DCERPCParseBINDACKCTXItem is called for each CTXItem found in * the BIND_ACK call. The result (Accepted or Rejected) is added to the * correct UUID from the BIND call. */ static uint32_t DCERPCParseBINDACKCTXItem(DCERPC *dcerpc, uint8_t *input, uint32_t input_len) { SCEnter(); uint8_t *p = input; DCERPCUuidEntry *uuid_entry; if (input_len) { switch (dcerpc->dcerpcbindbindack.ctxbytesprocessed) { case 0: if (input_len >= 24) { if (dcerpc->dcerpchdr.packed_drep[0] & 0x10) { dcerpc->dcerpcbindbindack.result = *p; dcerpc->dcerpcbindbindack.result |= *(p + 1) << 8; } else { dcerpc->dcerpcbindbindack.result = *p << 8; dcerpc->dcerpcbindbindack.result |= *(p + 1); } TAILQ_FOREACH(uuid_entry, &dcerpc->dcerpcbindbindack.uuid_list, next) { if (uuid_entry->internal_id == dcerpc->dcerpcbindbindack.uuid_internal_id) { uuid_entry->result = dcerpc->dcerpcbindbindack.result; #ifdef UNITTESTS if (RunmodeIsUnittests()) { printUUID("BIND_ACK", uuid_entry); } #endif if (uuid_entry->result != 0) break; dcerpc->dcerpcbindbindack.uuid_entry = (DCERPCUuidEntry *) SCCalloc(1, sizeof(DCERPCUuidEntry)); if (dcerpc->dcerpcbindbindack.uuid_entry != NULL) { memcpy(dcerpc->dcerpcbindbindack.uuid_entry, uuid_entry, sizeof(DCERPCUuidEntry)); TAILQ_INSERT_HEAD(&dcerpc->dcerpcbindbindack.accepted_uuid_list, dcerpc->dcerpcbindbindack.uuid_entry, next); } break; } } dcerpc->dcerpcbindbindack.uuid_internal_id++; dcerpc->dcerpcbindbindack.numctxitemsleft--; dcerpc->bytesprocessed += (24); dcerpc->dcerpcbindbindack.ctxbytesprocessed += (24); SCReturnUInt(24U); } else { if (dcerpc->dcerpchdr.packed_drep[0] & 0x10) { dcerpc->dcerpcbindbindack.result = *(p++); } else { dcerpc->dcerpcbindbindack.result = *(p++) << 8; } if (!(--input_len)) break; } /* fall through */ case 1: if (dcerpc->dcerpchdr.packed_drep[0] & 0x10) { dcerpc->dcerpcbindbindack.result |= *(p++) << 8; } else { dcerpc->dcerpcbindbindack.result |= *(p++); } if (!(--input_len)) break; /* fall through */ case 2: /* num transact items */ p++; if (!(--input_len)) break; /* fall through */ case 3: /* reserved */ p++; if (!(--input_len)) break; /* fall through */ case 4: p++; if (!(--input_len)) break; /* fall through */ case 5: p++; if (!(--input_len)) break; /* fall through */ case 6: p++; if (!(--input_len)) break; /* fall through */ case 7: p++; if (!(--input_len)) break; /* fall through */ case 8: p++; if (!(--input_len)) break; /* fall through */ case 9: p++; if (!(--input_len)) break; /* fall through */ case 10: p++; if (!(--input_len)) break; /* fall through */ case 11: p++; if (!(--input_len)) break; /* fall through */ case 12: p++; if (!(--input_len)) break; /* fall through */ case 13: p++; if (!(--input_len)) break; /* fall through */ case 14: p++; if (!(--input_len)) break; /* fall through */ case 15: p++; if (!(--input_len)) break; /* fall through */ case 16: p++; if (!(--input_len)) break; /* fall through */ case 17: p++; if (!(--input_len)) break; /* fall through */ case 18: p++; if (!(--input_len)) break; /* fall through */ case 19: p++; if (!(--input_len)) break; /* fall through */ case 20: p++; if (!(--input_len)) break; /* fall through */ case 21: p++; if (!(--input_len)) break; /* fall through */ case 22: p++; if (!(--input_len)) break; /* fall through */ case 23: TAILQ_FOREACH(uuid_entry, &dcerpc->dcerpcbindbindack.uuid_list, next) { if (uuid_entry->internal_id == dcerpc->dcerpcbindbindack.uuid_internal_id) { uuid_entry->result = dcerpc->dcerpcbindbindack.result; #ifdef UNITTESTS if (RunmodeIsUnittests()) { printUUID("BIND_ACK", uuid_entry); } #endif if (uuid_entry->result != 0) break; dcerpc->dcerpcbindbindack.uuid_entry = (DCERPCUuidEntry *) SCCalloc(1, sizeof(DCERPCUuidEntry)); if (dcerpc->dcerpcbindbindack.uuid_entry != NULL) { memcpy(dcerpc->dcerpcbindbindack.uuid_entry, uuid_entry, sizeof(DCERPCUuidEntry)); TAILQ_INSERT_HEAD(&dcerpc->dcerpcbindbindack.accepted_uuid_list, dcerpc->dcerpcbindbindack.uuid_entry, next); } break; } } dcerpc->dcerpcbindbindack.uuid_internal_id++; dcerpc->dcerpcbindbindack.numctxitemsleft--; p++; --input_len; break; } } dcerpc->dcerpcbindbindack.ctxbytesprocessed += (p - input); dcerpc->bytesprocessed += (p - input); SCReturnUInt((uint32_t)(p - input)); } static uint32_t DCERPCParseBIND(DCERPC *dcerpc, uint8_t *input, uint32_t input_len) { SCEnter(); uint8_t *p = input; if (input_len) { switch (dcerpc->bytesprocessed) { case 16: dcerpc->dcerpcbindbindack.numctxitems = 0; if (input_len >= 12) { DCERPCUuidListFree(&dcerpc->dcerpcbindbindack.uuid_list); if (dcerpc->dcerpchdr.type == BIND) { DCERPCUuidListFree(&dcerpc->dcerpcbindbindack.accepted_uuid_list); } dcerpc->dcerpcbindbindack.uuid_internal_id = 0; dcerpc->dcerpcbindbindack.numctxitems = *(p + 8); dcerpc->dcerpcbindbindack.numctxitemsleft = dcerpc->dcerpcbindbindack.numctxitems; dcerpc->bytesprocessed += 12; SCReturnUInt(12U); } else { /* max_xmit_frag */ p++; if (!(--input_len)) break; } /* fall through */ case 17: /* max_xmit_frag */ p++; if (!(--input_len)) break; /* fall through */ case 18: /* max_recv_frag */ p++; if (!(--input_len)) break; /* fall through */ case 19: /* max_recv_frag */ p++; if (!(--input_len)) break; /* fall through */ case 20: /* assoc_group_id */ p++; if (!(--input_len)) break; /* fall through */ case 21: /* assoc_group_id */ p++; if (!(--input_len)) break; /* fall through */ case 22: /* assoc_group_id */ p++; if (!(--input_len)) break; /* fall through */ case 23: /* assoc_group_id */ p++; if (!(--input_len)) break; /* fall through */ case 24: DCERPCUuidListFree(&dcerpc->dcerpcbindbindack.uuid_list); if (dcerpc->dcerpchdr.type == BIND) { DCERPCUuidListFree(&dcerpc->dcerpcbindbindack.accepted_uuid_list); } dcerpc->dcerpcbindbindack.uuid_internal_id = 0; dcerpc->dcerpcbindbindack.numctxitems = *(p++); dcerpc->dcerpcbindbindack.numctxitemsleft = dcerpc->dcerpcbindbindack.numctxitems; if (!(--input_len)) break; /* fall through */ case 25: /* pad byte 1 */ p++; if (!(--input_len)) break; /* fall through */ case 26: /* pad byte 2 */ p++; if (!(--input_len)) break; /* fall through */ case 27: /* pad byte 3 */ p++; --input_len; break; /* fall through */ default: dcerpc->bytesprocessed++; SCReturnUInt(1); break; } } dcerpc->bytesprocessed += (p - input); SCReturnUInt((uint32_t)(p - input)); } static uint32_t DCERPCParseBINDACK(DCERPC *dcerpc, uint8_t *input, uint32_t input_len) { SCEnter(); uint8_t *p = input; switch (dcerpc->bytesprocessed) { case 16: dcerpc->dcerpcbindbindack.uuid_internal_id = 0; dcerpc->dcerpcbindbindack.numctxitems = 0; if (input_len >= 10) { if (dcerpc->dcerpchdr.packed_drep[0] & 0x10) { dcerpc->dcerpcbindbindack.secondaryaddrlen = *(p + 8); dcerpc->dcerpcbindbindack.secondaryaddrlen |= *(p + 9) << 8; } else { dcerpc->dcerpcbindbindack.secondaryaddrlen = *(p + 8) << 8; dcerpc->dcerpcbindbindack.secondaryaddrlen |= *(p + 9); } dcerpc->dcerpcbindbindack.secondaryaddrlenleft = dcerpc->dcerpcbindbindack.secondaryaddrlen; dcerpc->bytesprocessed += 10; SCReturnUInt(10U); } else { /* max_xmit_frag */ p++; if (!(--input_len)) break; } /* fall through */ case 17: /* max_xmit_frag */ p++; if (!(--input_len)) break; /* fall through */ case 18: /* max_recv_frag */ p++; if (!(--input_len)) break; /* fall through */ case 19: /* max_recv_frag */ p++; if (!(--input_len)) break; /* fall through */ case 20: /* assoc_group_id */ p++; if (!(--input_len)) break; /* fall through */ case 21: /* assoc_group_id */ p++; if (!(--input_len)) break; /* fall through */ case 22: /* assoc_group_id */ p++; if (!(--input_len)) break; /* fall through */ case 23: /* assoc_group_id */ p++; if (!(--input_len)) break; /* fall through */ case 24: dcerpc->dcerpcbindbindack.secondaryaddrlen = *(p++) << 8; if (!(--input_len)) break; /* fall through */ case 25: dcerpc->dcerpcbindbindack.secondaryaddrlen |= *(p++); if (dcerpc->dcerpchdr.packed_drep[0] & 0x10) { dcerpc->dcerpcbindbindack.secondaryaddrlen = SCByteSwap16(dcerpc->dcerpcbindbindack.secondaryaddrlen); } dcerpc->dcerpcbindbindack.secondaryaddrlenleft = dcerpc->dcerpcbindbindack.secondaryaddrlen; SCLogDebug("secondaryaddrlen %u 0x%04x\n", dcerpc->dcerpcbindbindack.secondaryaddrlen, dcerpc->dcerpcbindbindack.secondaryaddrlen); --input_len; break; default: dcerpc->bytesprocessed++; SCReturnUInt(1); break; } dcerpc->bytesprocessed += (p - input); SCReturnUInt((uint32_t)(p - input)); } static uint32_t DCERPCParseREQUEST(DCERPC *dcerpc, uint8_t *input, uint32_t input_len) { SCEnter(); uint8_t *p = input; switch (dcerpc->bytesprocessed) { case 16: dcerpc->dcerpcbindbindack.numctxitems = 0; if (input_len >= 8) { if (dcerpc->dcerpchdr.type == REQUEST) { if (dcerpc->dcerpchdr.packed_drep[0] & 0x10) { dcerpc->dcerpcrequest.ctxid = *(p + 4); dcerpc->dcerpcrequest.ctxid |= *(p + 5) << 8; dcerpc->dcerpcrequest.opnum = *(p + 6); dcerpc->dcerpcrequest.opnum |= *(p + 7) << 8; } else { dcerpc->dcerpcrequest.ctxid = *(p + 4) << 8; dcerpc->dcerpcrequest.ctxid |= *(p + 5); dcerpc->dcerpcrequest.opnum = *(p + 6) << 8; dcerpc->dcerpcrequest.opnum |= *(p + 7); } dcerpc->dcerpcrequest.first_request_seen = 1; } dcerpc->bytesprocessed += 8; SCReturnUInt(8U); } else { /* alloc hint 1 */ p++; if (!(--input_len)) break; } /* fall through */ case 17: /* alloc hint 2 */ p++; if (!(--input_len)) break; /* fall through */ case 18: /* alloc hint 3 */ p++; if (!(--input_len)) break; /* fall through */ case 19: /* alloc hint 4 */ p++; if (!(--input_len)) break; /* fall through */ case 20: /* context id 1 */ dcerpc->dcerpcrequest.ctxid = *(p++); if (!(--input_len)) break; /* fall through */ case 21: /* context id 2 */ dcerpc->dcerpcrequest.ctxid |= *(p++) << 8; if (!(dcerpc->dcerpchdr.packed_drep[0] & 0x10)) { dcerpc->dcerpcrequest.ctxid = SCByteSwap16(dcerpc->dcerpcrequest.ctxid); } dcerpc->dcerpcrequest.first_request_seen = 1; if (!(--input_len)) break; /* fall through */ case 22: if (dcerpc->dcerpchdr.type == REQUEST) { dcerpc->dcerpcrequest.opnum = *(p++); } else { p++; } if (!(--input_len)) break; /* fall through */ case 23: if (dcerpc->dcerpchdr.type == REQUEST) { dcerpc->dcerpcrequest.opnum |= *(p++) << 8; if (!(dcerpc->dcerpchdr.packed_drep[0] & 0x10)) { dcerpc->dcerpcrequest.opnum = SCByteSwap16(dcerpc->dcerpcrequest.opnum); } } else { p++; } --input_len; break; default: dcerpc->bytesprocessed++; SCReturnUInt(1); break; } dcerpc->bytesprocessed += (p - input); SCReturnUInt((uint32_t)(p - input)); } /** \internal * \retval stub_len or 0 in case of error */ static uint32_t StubDataParser(DCERPC *dcerpc, const uint8_t *input, uint32_t input_len) { SCEnter(); uint8_t **stub_data_buffer = NULL; uint32_t *stub_data_buffer_len = NULL; SCLogDebug("input_len %u", input_len); /* request PDU. Retrieve the request stub buffer */ if (dcerpc->dcerpchdr.type == REQUEST) { stub_data_buffer = &dcerpc->dcerpcrequest.stub_data_buffer; stub_data_buffer_len = &dcerpc->dcerpcrequest.stub_data_buffer_len; SCLogDebug("REQUEST stub_data_buffer_len %u", *stub_data_buffer_len); /* response PDU. Retrieve the response stub buffer */ } else { stub_data_buffer = &dcerpc->dcerpcresponse.stub_data_buffer; stub_data_buffer_len = &dcerpc->dcerpcresponse.stub_data_buffer_len; SCLogDebug("RESPONSE stub_data_buffer_len %u", *stub_data_buffer_len); } if (*stub_data_buffer_len > (1024 * 1024)) { SCFree(*stub_data_buffer); *stub_data_buffer = NULL; SCReturnUInt(0); } uint32_t stub_len = MIN(dcerpc->padleft, input_len); if (stub_len == 0) { SCReturnInt(0); } SCLogDebug("stub_len %u input_len %u", stub_len, input_len); const uint8_t f = dcerpc->dcerpchdr.pfc_flags & (PFC_FIRST_FRAG|PFC_LAST_FRAG); SCLogDebug("f %02x, FIRST %s LAST %s", f, f & PFC_FIRST_FRAG ? "true" : "false", f & PFC_LAST_FRAG ? "true" : "false"); if (stub_len == dcerpc->padleft && ((f == 0) || (f & PFC_LAST_FRAG))) { if (dcerpc->dcerpchdr.type == REQUEST) { dcerpc->dcerpcrequest.stub_data_buffer_reset = true; SCLogDebug("REQUEST reset stub"); } else { dcerpc->dcerpcresponse.stub_data_buffer_reset = true; SCLogDebug("RESPONSE reset stub"); } } void *ptmp = SCRealloc(*stub_data_buffer, *stub_data_buffer_len + stub_len); if (ptmp == NULL) { SCFree(*stub_data_buffer); *stub_data_buffer = NULL; SCReturnUInt(0); } *stub_data_buffer = ptmp; memcpy(*stub_data_buffer + *stub_data_buffer_len, input, stub_len); /* length of the buffered stub */ *stub_data_buffer_len += stub_len; /* To see the total reassembled stubdata */ //hexdump(*stub_data_buffer, *stub_data_buffer_len); dcerpc->padleft -= stub_len; dcerpc->bytesprocessed += stub_len; SCLogDebug("padleft %u bytesprocessed %u", dcerpc->padleft, dcerpc->bytesprocessed); #ifdef DEBUG if (SCLogDebugEnabled()) { uint32_t i = 0; for (i = 0; i < stub_len; i++) { SCLogDebug("0x%02x ", input[i]); } } #endif SCReturnUInt((uint32_t)stub_len); } /** * \brief DCERPCParseHeader parses the 16 byte DCERPC header * A fast path for normal decoding is used when there is enough bytes * present to parse the entire header. A slow path is used to parse * fragmented packets. * \retval -1 if DCERPC Header does not validate * \retval Number of bytes processed */ static int DCERPCParseHeader(DCERPC *dcerpc, uint8_t *input, uint32_t input_len) { SCEnter(); uint8_t *p = input; if (input_len) { SCLogDebug("dcerpc->bytesprocessed %u", dcerpc->bytesprocessed); switch (dcerpc->bytesprocessed) { case 0: if (input_len >= DCERPC_HDR_LEN) { dcerpc->dcerpchdr.rpc_vers = *p; dcerpc->dcerpchdr.rpc_vers_minor = *(p + 1); if ((dcerpc->dcerpchdr.rpc_vers != 5) || ((dcerpc->dcerpchdr.rpc_vers_minor != 0) && (dcerpc->dcerpchdr.rpc_vers_minor != 1))) { SCLogDebug("DCERPC Header did not validate"); SCReturnInt(-1); } dcerpc->dcerpchdr.type = *(p + 2); SCLogDebug("dcerpc->dcerpchdr.type %02x", dcerpc->dcerpchdr.type); dcerpc->dcerpchdr.pfc_flags = *(p + 3); dcerpc->dcerpchdr.packed_drep[0] = *(p + 4); dcerpc->dcerpchdr.packed_drep[1] = *(p + 5); dcerpc->dcerpchdr.packed_drep[2] = *(p + 6); dcerpc->dcerpchdr.packed_drep[3] = *(p + 7); if (dcerpc->dcerpchdr.packed_drep[0] & 0x10) { dcerpc->dcerpchdr.frag_length = *(p + 8); dcerpc->dcerpchdr.frag_length |= *(p + 9) << 8; dcerpc->dcerpchdr.auth_length = *(p + 10); dcerpc->dcerpchdr.auth_length |= *(p + 11) << 8; dcerpc->dcerpchdr.call_id = (uint32_t) *(p + 12) << 24; dcerpc->dcerpchdr.call_id |= (uint32_t) *(p + 13) << 16; dcerpc->dcerpchdr.call_id |= (uint32_t) *(p + 14) << 8; dcerpc->dcerpchdr.call_id |= (uint32_t) *(p + 15); } else { dcerpc->dcerpchdr.frag_length = *(p + 8) << 8; dcerpc->dcerpchdr.frag_length |= *(p + 9); dcerpc->dcerpchdr.auth_length = *(p + 10) << 8; dcerpc->dcerpchdr.auth_length |= *(p + 11); dcerpc->dcerpchdr.call_id = (uint32_t) *(p + 12); dcerpc->dcerpchdr.call_id |= (uint32_t) *(p + 13) << 8; dcerpc->dcerpchdr.call_id |= (uint32_t) *(p + 14) << 16; dcerpc->dcerpchdr.call_id |= (uint32_t) *(p + 15) << 24; } dcerpc->bytesprocessed = DCERPC_HDR_LEN; SCReturnInt(16); break; } else { dcerpc->dcerpchdr.rpc_vers = *(p++); if (!(--input_len)) break; } /* fall through */ case 1: dcerpc->dcerpchdr.rpc_vers_minor = *(p++); if ((dcerpc->dcerpchdr.rpc_vers != 5) || ((dcerpc->dcerpchdr.rpc_vers_minor != 0) && (dcerpc->dcerpchdr.rpc_vers_minor != 1))) { SCLogDebug("DCERPC Header did not validate"); SCReturnInt(-1); } if (!(--input_len)) break; /* fall through */ case 2: dcerpc->dcerpchdr.type = *(p++); SCLogDebug("dcerpc->dcerpchdr.type %02x", dcerpc->dcerpchdr.type); if (!(--input_len)) break; /* fall through */ case 3: dcerpc->dcerpchdr.pfc_flags = *(p++); if (!(--input_len)) break; /* fall through */ case 4: dcerpc->dcerpchdr.packed_drep[0] = *(p++); if (!(--input_len)) break; /* fall through */ case 5: dcerpc->dcerpchdr.packed_drep[1] = *(p++); if (!(--input_len)) break; /* fall through */ case 6: dcerpc->dcerpchdr.packed_drep[2] = *(p++); if (!(--input_len)) break; /* fall through */ case 7: dcerpc->dcerpchdr.packed_drep[3] = *(p++); if (!(--input_len)) break; /* fall through */ case 8: dcerpc->dcerpchdr.frag_length = *(p++); if (!(--input_len)) break; /* fall through */ case 9: dcerpc->dcerpchdr.frag_length |= *(p++) << 8; if (!(--input_len)) break; /* fall through */ case 10: dcerpc->dcerpchdr.auth_length = *(p++); if (!(--input_len)) break; /* fall through */ case 11: dcerpc->dcerpchdr.auth_length |= *(p++) << 8; if (!(--input_len)) break; /* fall through */ case 12: dcerpc->dcerpchdr.call_id = (uint32_t) *(p++); if (!(--input_len)) break; /* fall through */ case 13: dcerpc->dcerpchdr.call_id |= (uint32_t) *(p++) << 8; if (!(--input_len)) break; /* fall through */ case 14: dcerpc->dcerpchdr.call_id |= (uint32_t) *(p++) << 16; if (!(--input_len)) break; /* fall through */ case 15: dcerpc->dcerpchdr.call_id |= (uint32_t) *(p++) << 24; if (!(dcerpc->dcerpchdr.packed_drep[0] & 0x10)) { dcerpc->dcerpchdr.frag_length = SCByteSwap16(dcerpc->dcerpchdr.frag_length); dcerpc->dcerpchdr.auth_length = SCByteSwap16(dcerpc->dcerpchdr.auth_length); dcerpc->dcerpchdr.call_id = SCByteSwap32(dcerpc->dcerpchdr.call_id); } --input_len; break; default: dcerpc->bytesprocessed++; SCReturnInt(1); } } dcerpc->bytesprocessed += (p - input); SCReturnInt((p - input)); } static inline void DCERPCResetParsingState(DCERPC *dcerpc) { dcerpc->bytesprocessed = 0; dcerpc->dcerpcbindbindack.ctxbytesprocessed = 0; return; } static inline void DCERPCResetStub(DCERPC *dcerpc) { if (dcerpc->dcerpchdr.type == REQUEST) { SCLogDebug("REQUEST resetting stub"); dcerpc->dcerpcrequest.stub_data_buffer_len = 0; dcerpc->dcerpcrequest.stub_data_buffer_reset = false; } else if (dcerpc->dcerpchdr.type == RESPONSE) { SCLogDebug("RESPONSE resetting stub"); dcerpc->dcerpcresponse.stub_data_buffer_len = 0; dcerpc->dcerpcresponse.stub_data_buffer_reset = false; } return; } static inline int DCERPCThrowOutExtraData(DCERPC *dcerpc, uint8_t *input, uint16_t input_len) { int parsed = 0; /* the function always assumes that * dcerpc->bytesprocessed < dcerpc->dcerpchdr.frag_length */ if (input_len > (dcerpc->dcerpchdr.frag_length - dcerpc->bytesprocessed)) { parsed = dcerpc->dcerpchdr.frag_length - dcerpc->bytesprocessed; } else { parsed = input_len; } dcerpc->bytesprocessed += parsed; return parsed; } /** * \todo - Currently the parser is very generic. Enable target based * reassembly. * - Disable reiniting tailq for mid and last bind/alter_context pdus. * - Use a PM to search for subsequent 05 00 when we see an inconsistent * pdu. This should be done for each platform based on how it handles * a condition where it has receives a segment with 2 pdus, while the * first pdu in the segment is corrupt. */ int32_t DCERPCParser(DCERPC *dcerpc, uint8_t *input, uint32_t input_len) { SCEnter(); uint32_t retval = 0; uint32_t parsed = 0; int hdrretval = 0; /* temporary use. we will get rid of this later, once we have ironed out * all the endless loops cases */ int counter = 0; while (input_len) { /* in case we have any corner cases remainging, we have this */ if (counter++ == 30) { SCLogDebug("Somehow seem to be stuck inside the dce " "parser for quite sometime. Let's get out of here."); DCERPCResetParsingState(dcerpc); SCReturnInt(0); } while (dcerpc->bytesprocessed < DCERPC_HDR_LEN && input_len) { hdrretval = DCERPCParseHeader(dcerpc, input + parsed, input_len); if (hdrretval == -1 || hdrretval > (int32_t)input_len) { SCLogDebug("Error parsing dce header. Discarding " "PDU and reseting parsing state to parse next PDU"); /* error parsing pdu header. Let's clear the dce state */ DCERPCResetParsingState(dcerpc); SCReturnInt(0); } else { parsed += hdrretval; input_len -= hdrretval; } } SCLogDebug("Done with DCERPCParseHeader bytesprocessed %u/%u left %u", dcerpc->bytesprocessed, dcerpc->dcerpchdr.frag_length, input_len); #if 0 printf("Done with DCERPCParseHeader bytesprocessed %u/%u input_len left %u\n", dcerpc->bytesprocessed, dcerpc->dcerpchdr.frag_length, input_len); printf("\nDCERPC Version:\t%u\n", dcerpc->dcerpchdr.rpc_vers); printf("DCERPC Version Minor:\t%u\n", dcerpc->dcerpchdr.rpc_vers_minor); printf("DCERPC Type:\t%u\n", dcerpc->dcerpchdr.type); printf("DCERPC Flags:\t0x%02x\n", dcerpc->dcerpchdr.pfc_flags); printf("DCERPC Packed Drep:\t%02x %02x %02x %02x\n", dcerpc->dcerpchdr.packed_drep[0], dcerpc->dcerpchdr.packed_drep[1], dcerpc->dcerpchdr.packed_drep[2], dcerpc->dcerpchdr.packed_drep[3]); printf("DCERPC Frag Length:\t0x%04x %u\n", dcerpc->dcerpchdr.frag_length, dcerpc->dcerpchdr.frag_length); printf("DCERPC Auth Length:\t0x%04x\n", dcerpc->dcerpchdr.auth_length); printf("DCERPC Call Id:\t0x%08x\n", dcerpc->dcerpchdr.call_id); #endif /* check if we have parsed the entire input passed in the header parser. * If we have, time to leave */ if (input_len == 0) { if (dcerpc->bytesprocessed < 10) { } else { if (dcerpc->bytesprocessed >= dcerpc->dcerpchdr.frag_length) { SCLogDebug("Weird DCE PDU"); DCERPCResetParsingState(dcerpc); } } SCReturnInt(parsed); } switch (dcerpc->dcerpchdr.type) { case BIND: case ALTER_CONTEXT: while (dcerpc->bytesprocessed < DCERPC_HDR_LEN + 12 && dcerpc->bytesprocessed < dcerpc->dcerpchdr.frag_length && input_len) { retval = DCERPCParseBIND(dcerpc, input + parsed, input_len); if (retval && retval <= input_len) { parsed += retval; input_len -= retval; } else if (input_len) { SCLogDebug("Error Parsing DCERPC %s PDU", (dcerpc->dcerpchdr.type == BIND) ? "BIND" : "ALTER_CONTEXT"); parsed = 0; (void)parsed; /* for scan-build */ input_len = 0; (void)input_len; /* for scan-build */ DCERPCResetParsingState(dcerpc); SCReturnInt(0); } } SCLogDebug("Done with DCERPCParseBIND bytesprocessed %u/%u numctxitems %u", dcerpc->bytesprocessed, dcerpc->dcerpchdr.frag_length, dcerpc->dcerpcbindbindack.numctxitems); while (dcerpc->dcerpcbindbindack.numctxitemsleft && dcerpc->bytesprocessed < dcerpc->dcerpchdr.frag_length && input_len) { retval = DCERPCParseBINDCTXItem(dcerpc, input + parsed, input_len); if (retval && retval <= input_len) { if (dcerpc->dcerpcbindbindack.ctxbytesprocessed == 44) { dcerpc->dcerpcbindbindack.ctxbytesprocessed = 0; } parsed += retval; input_len -= retval; SCLogDebug("BIND processed %u/%u ctxitems %u/%u input_len left %u\n", dcerpc->bytesprocessed, dcerpc->dcerpchdr.frag_length, dcerpc->dcerpcbindbindack.numctxitemsleft, dcerpc->dcerpcbindbindack.numctxitems, input_len); } else if (input_len) { //parsed -= input_len; SCLogDebug("Error Parsing CTX Item %u\n", parsed); parsed = 0; (void)parsed; /* for scan-build */ input_len = 0; (void)input_len; /* for scan-build */ dcerpc->dcerpcbindbindack.numctxitemsleft = 0; DCERPCResetParsingState(dcerpc); SCReturnInt(0); } } if (dcerpc->bytesprocessed == dcerpc->dcerpchdr.frag_length) { DCERPCResetParsingState(dcerpc); } else if (dcerpc->bytesprocessed > dcerpc->dcerpchdr.frag_length) { DCERPCResetParsingState(dcerpc); SCReturnInt(0); } else { /* temporary fix */ if (input_len) { retval = DCERPCThrowOutExtraData(dcerpc, input + parsed, input_len); if (retval && retval <= input_len) { input_len -= retval; parsed += retval; if (dcerpc->bytesprocessed == dcerpc->dcerpchdr.frag_length) { DCERPCResetParsingState(dcerpc); } } else { SCLogDebug("Error Parsing DCERPC"); parsed = 0; (void)parsed; /* for scan-build */ input_len = 0; (void)input_len; /* for scan-build */ DCERPCResetParsingState(dcerpc); SCReturnInt(0); } } } break; case BIND_ACK: case ALTER_CONTEXT_RESP: while (dcerpc->bytesprocessed < DCERPC_HDR_LEN + 9 && dcerpc->bytesprocessed < dcerpc->dcerpchdr.frag_length && input_len) { retval = DCERPCParseBINDACK(dcerpc, input + parsed, input_len); if (retval && retval <= input_len) { parsed += retval; input_len -= retval; SCLogDebug("DCERPCParseBINDACK processed %u/%u input_len left %u", dcerpc->bytesprocessed, dcerpc->dcerpchdr.frag_length, input_len); } else if (input_len) { SCLogDebug("Error parsing %s\n", (dcerpc->dcerpchdr.type == BIND_ACK) ? "BIND_ACK" : "ALTER_CONTEXT_RESP"); parsed = 0; (void)parsed; /* for scan-build */ input_len = 0; (void)input_len; /* for scan-build */ DCERPCResetParsingState(dcerpc); SCReturnInt(0); } } while (dcerpc->bytesprocessed < DCERPC_HDR_LEN + 10 + dcerpc->dcerpcbindbindack.secondaryaddrlen && dcerpc->bytesprocessed < dcerpc->dcerpchdr.frag_length && input_len) { retval = DCERPCParseSecondaryAddr(dcerpc, input + parsed, input_len); if (retval && retval <= input_len) { parsed += retval; input_len -= retval; SCLogDebug("DCERPCParseSecondaryAddr %u/%u left %u secondaryaddr len(%u)", dcerpc->bytesprocessed, dcerpc->dcerpchdr.frag_length, input_len, dcerpc->dcerpcbindbindack.secondaryaddrlen); } else if (input_len) { SCLogDebug("Error parsing Secondary Address"); parsed = 0; (void)parsed; /* for scan-build */ input_len = 0; (void)input_len; /* for scan-build */ DCERPCResetParsingState(dcerpc); SCReturnInt(0); } } if (dcerpc->bytesprocessed == DCERPC_HDR_LEN + 10 + dcerpc->dcerpcbindbindack.secondaryaddrlen) { if (dcerpc->bytesprocessed % 4) { dcerpc->pad = (4 - dcerpc->bytesprocessed % 4); dcerpc->padleft = dcerpc->pad; } } while (dcerpc->bytesprocessed < DCERPC_HDR_LEN + 10 + dcerpc->dcerpcbindbindack.secondaryaddrlen + dcerpc->pad && dcerpc->bytesprocessed < dcerpc->dcerpchdr.frag_length && input_len) { retval = PaddingParser(dcerpc, input + parsed, input_len); if (retval && retval <= input_len) { parsed += retval; input_len -= retval; SCLogDebug("PaddingParser %u/%u left %u pad(%u)", dcerpc->bytesprocessed, dcerpc->dcerpchdr.frag_length, input_len, dcerpc->pad); } else if (input_len) { SCLogDebug("Error parsing DCERPC Padding"); parsed = 0; (void)parsed; /* for scan-build */ input_len = 0; (void)input_len; /* for scan-build */ DCERPCResetParsingState(dcerpc); SCReturnInt(0); } } while (dcerpc->bytesprocessed >= DCERPC_HDR_LEN + 10 + dcerpc->pad + dcerpc->dcerpcbindbindack.secondaryaddrlen && dcerpc->bytesprocessed < DCERPC_HDR_LEN + 14 + dcerpc->pad + dcerpc->dcerpcbindbindack.secondaryaddrlen && dcerpc->bytesprocessed < dcerpc->dcerpchdr.frag_length && input_len) { retval = DCERPCGetCTXItems(dcerpc, input + parsed, input_len); if (retval && retval <= input_len) { parsed += retval; input_len -= retval; SCLogDebug("DCERPCGetCTXItems %u/%u (%u)", dcerpc->bytesprocessed, dcerpc->dcerpchdr.frag_length, dcerpc->dcerpcbindbindack.numctxitems); } else if (input_len) { SCLogDebug("Error parsing CTX Items"); parsed = 0; (void)parsed; /* for scan-build */ input_len = 0; (void)input_len; /* for scan-build */ DCERPCResetParsingState(dcerpc); SCReturnInt(0); } } if (dcerpc->bytesprocessed == DCERPC_HDR_LEN + 14 + dcerpc->pad + dcerpc->dcerpcbindbindack.secondaryaddrlen) { dcerpc->dcerpcbindbindack.ctxbytesprocessed = 0; } while (dcerpc->dcerpcbindbindack.numctxitemsleft && dcerpc->bytesprocessed < dcerpc->dcerpchdr.frag_length && input_len) { retval = DCERPCParseBINDACKCTXItem(dcerpc, input + parsed, input_len); if (retval && retval <= input_len) { if (dcerpc->dcerpcbindbindack.ctxbytesprocessed == 24) { dcerpc->dcerpcbindbindack.ctxbytesprocessed = 0; } parsed += retval; input_len -= retval; } else if (input_len) { SCLogDebug("Error parsing CTX Items"); parsed = 0; (void)parsed; /* for scan-build */ input_len = 0; (void)input_len; /* for scan-build */ dcerpc->dcerpcbindbindack.numctxitemsleft = 0; DCERPCResetParsingState(dcerpc); SCReturnInt(0); } } SCLogDebug("BINDACK processed %u/%u input_len left %u", dcerpc->bytesprocessed, dcerpc->dcerpchdr.frag_length, input_len); if (dcerpc->bytesprocessed == dcerpc->dcerpchdr.frag_length) { /* response and request done */ if (dcerpc->dcerpchdr.type == BIND_ACK) { /* update transaction id */ dcerpc->transaction_id++; SCLogDebug("transaction_id updated to %"PRIu16, dcerpc->transaction_id); } DCERPCResetParsingState(dcerpc); } else if (dcerpc->bytesprocessed > dcerpc->dcerpchdr.frag_length) { DCERPCResetParsingState(dcerpc); SCReturnInt(0); } else { /* temporary fix */ if (input_len) { retval = DCERPCThrowOutExtraData(dcerpc, input + parsed, input_len); if (retval && retval <= input_len) { input_len -= retval; parsed += retval; if (dcerpc->bytesprocessed == dcerpc->dcerpchdr.frag_length) { DCERPCResetParsingState(dcerpc); } } else { SCLogDebug("Error Parsing DCERPC"); parsed = 0; (void)parsed; /* for scan-build */ input_len = 0; (void)input_len; /* for scan-build */ DCERPCResetParsingState(dcerpc); SCReturnInt(0); } } } break; case REQUEST: case RESPONSE: SCLogDebug("parsing DCERPC %s", (dcerpc->dcerpchdr.type == REQUEST) ? "REQUEST" : "RESPONSE"); if ((dcerpc->dcerpchdr.type == REQUEST && dcerpc->dcerpcrequest.stub_data_buffer_reset) || (dcerpc->dcerpchdr.type == RESPONSE && dcerpc->dcerpcresponse.stub_data_buffer_reset)) { DCERPCResetStub(dcerpc); } while (dcerpc->bytesprocessed < DCERPC_HDR_LEN + 8 && dcerpc->bytesprocessed < dcerpc->dcerpchdr.frag_length && input_len) { retval = DCERPCParseREQUEST(dcerpc, input + parsed, input_len); if (retval && retval <= input_len) { parsed += retval; input_len -= retval; dcerpc->padleft = dcerpc->dcerpchdr.frag_length - dcerpc->bytesprocessed; } else if (input_len) { SCLogDebug("Error parsing DCERPC %s", (dcerpc->dcerpchdr.type == REQUEST) ? "REQUEST" : "RESPONSE"); parsed = 0; (void)parsed; /* for scan-build */ dcerpc->padleft = 0; input_len = 0; (void)input_len; /* for scan-build */ DCERPCResetParsingState(dcerpc); SCReturnInt(0); } } while (dcerpc->bytesprocessed >= DCERPC_HDR_LEN + 8 && dcerpc->bytesprocessed < dcerpc->dcerpchdr.frag_length && dcerpc->padleft && input_len) { retval = StubDataParser(dcerpc, input + parsed, input_len); if (retval && retval <= input_len) { parsed += retval; input_len -= retval; } else if (input_len) { SCLogDebug("Error parsing DCERPC Stub Data"); parsed = 0; (void)parsed; /* for scan-build */ input_len = 0; (void)input_len; /* for scan-build */ DCERPCResetParsingState(dcerpc); SCReturnInt(0); } } if (dcerpc->dcerpchdr.type == REQUEST) { SCLogDebug("REQUEST processed %u frag length %u opnum %u input_len %u", dcerpc->bytesprocessed, dcerpc->dcerpchdr.frag_length, dcerpc->dcerpcrequest.opnum, input_len); } else { SCLogDebug("RESPONSE processed %u frag length %u opnum %u input_len %u", dcerpc->bytesprocessed, dcerpc->dcerpchdr.frag_length, dcerpc->dcerpcrequest.opnum, input_len); } /* don't see how we could break the parser for request pdus, by * pusing bytesprocessed beyond frag_length. Let's have the * check anyways */ if (dcerpc->bytesprocessed == dcerpc->dcerpchdr.frag_length) { DCERPCResetParsingState(dcerpc); } else if (dcerpc->bytesprocessed > dcerpc->dcerpchdr.frag_length) { DCERPCResetParsingState(dcerpc); SCReturnInt(0); } else { /* temporary fix */ if (input_len) { retval = DCERPCThrowOutExtraData(dcerpc, input + parsed, input_len); if (retval && retval <= input_len) { input_len -= retval; parsed += retval; if (dcerpc->bytesprocessed == dcerpc->dcerpchdr.frag_length) { DCERPCResetParsingState(dcerpc); } } else { SCLogDebug("Error Parsing DCERPC"); parsed = 0; (void)parsed; /* for scan-build */ input_len = 0; (void)input_len; /* for scan-build */ DCERPCResetParsingState(dcerpc); SCReturnInt(0); } } } /* response and request done */ if (dcerpc->dcerpchdr.type == RESPONSE) { /* update transaction id */ dcerpc->transaction_id++; SCLogDebug("transaction_id updated to %"PRIu16, dcerpc->transaction_id); } break; default: SCLogDebug("DCERPC Type 0x%02x not implemented yet", dcerpc->dcerpchdr.type); retval = DCERPCThrowOutExtraData(dcerpc, input + parsed, input_len); if (retval && retval <= input_len) { input_len -= retval; parsed += retval; if (dcerpc->bytesprocessed == dcerpc->dcerpchdr.frag_length) { DCERPCResetParsingState(dcerpc); } } else { SCLogDebug("Error Parsing DCERPC"); parsed = 0; (void)parsed; /* for scan-build */ input_len = 0; (void)input_len; /* for scan-build */ DCERPCResetParsingState(dcerpc); SCReturnInt(0); } break; } } SCReturnInt(parsed); } static int DCERPCParse(Flow *f, void *dcerpc_state, AppLayerParserState *pstate, uint8_t *input, uint32_t input_len, void *local_data, int dir) { SCEnter(); int32_t retval = 0; DCERPCState *sstate = (DCERPCState *) dcerpc_state; if (input == NULL && AppLayerParserStateIssetFlag(pstate, APP_LAYER_PARSER_EOF)) { SCReturnInt(1); } else if (input == NULL || input_len == 0) { SCReturnInt(-1); } if (sstate->dcerpc.bytesprocessed != 0 && sstate->data_needed_for_dir != dir) { SCReturnInt(-1); } retval = DCERPCParser(&sstate->dcerpc, input, input_len); if (retval == -1) { SCReturnInt(0); } sstate->data_needed_for_dir = dir; if (pstate == NULL) SCReturnInt(-1); SCReturnInt(1); } static int DCERPCParseRequest(Flow *f, void *dcerpc_state, AppLayerParserState *pstate, uint8_t *input, uint32_t input_len, void *local_data, const uint8_t flags) { return DCERPCParse(f, dcerpc_state, pstate, input, input_len, local_data, 0); } static int DCERPCParseResponse(Flow *f, void *dcerpc_state, AppLayerParserState *pstate, uint8_t *input, uint32_t input_len, void *local_data, const uint8_t flags) { return DCERPCParse(f, dcerpc_state, pstate, input, input_len, local_data, 1); } void DCERPCInit(DCERPC *dcerpc) { dcerpc->transaction_id = 1; TAILQ_INIT(&dcerpc->dcerpcbindbindack.uuid_list); TAILQ_INIT(&dcerpc->dcerpcbindbindack.accepted_uuid_list); } static void *DCERPCStateAlloc(void) { SCEnter(); DCERPCState *s = SCCalloc(1, sizeof(DCERPCState)); if (unlikely(s == NULL)) { SCReturnPtr(NULL, "void"); } DCERPCInit(&s->dcerpc); SCReturnPtr((void *)s, "void"); } void DCERPCUuidListFree(DCERPCUuidEntryList *list) { DCERPCUuidEntry *entry; while ((entry = TAILQ_FIRST(list))) { TAILQ_REMOVE(list, entry, next); SCFree(entry); } } void DCERPCCleanup(DCERPC *dcerpc) { DCERPCUuidListFree(&dcerpc->dcerpcbindbindack.uuid_list); DCERPCUuidListFree(&dcerpc->dcerpcbindbindack.accepted_uuid_list); if (dcerpc->dcerpcrequest.stub_data_buffer != NULL) { SCFree(dcerpc->dcerpcrequest.stub_data_buffer); dcerpc->dcerpcrequest.stub_data_buffer = NULL; dcerpc->dcerpcrequest.stub_data_buffer_len = 0; } if (dcerpc->dcerpcresponse.stub_data_buffer != NULL) { SCFree(dcerpc->dcerpcresponse.stub_data_buffer); dcerpc->dcerpcresponse.stub_data_buffer = NULL; dcerpc->dcerpcresponse.stub_data_buffer_len = 0; } } static void DCERPCStateFree(void *s) { DCERPCState *sstate = (DCERPCState *) s; DCERPCCleanup(&sstate->dcerpc); if (sstate->de_state != NULL) { DetectEngineStateFree(sstate->de_state); } SCFree(s); } static int DCERPCSetTxDetectState(void *vtx, DetectEngineState *de_state) { DCERPCState *dce_state = (DCERPCState *)vtx; dce_state->de_state = de_state; return 0; } static DetectEngineState *DCERPCGetTxDetectState(void *vtx) { DCERPCState *dce_state = (DCERPCState *)vtx; return dce_state->de_state; } static void DCERPCStateTransactionFree(void *state, uint64_t tx_id) { /* do nothing */ } static void *DCERPCGetTx(void *state, uint64_t tx_id) { DCERPCState *dce_state = (DCERPCState *)state; return dce_state; } static uint64_t DCERPCGetTxCnt(void *state) { /* single tx */ return 1; } static int DCERPCGetAlstateProgressCompletionStatus(uint8_t direction) { return 1; } static int DCERPCGetAlstateProgress(void *tx, uint8_t direction) { return 0; } static int DCERPCRegisterPatternsForProtocolDetection(void) { if (AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_DCERPC, "|05 00|", 2, 0, STREAM_TOSERVER) < 0) { return -1; } if (AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_DCERPC, "|05 00|", 2, 0, STREAM_TOCLIENT) < 0) { return -1; } return 0; } void RegisterDCERPCParsers(void) { const char *proto_name = "dcerpc"; if (AppLayerProtoDetectConfProtoDetectionEnabled("tcp", proto_name)) { AppLayerProtoDetectRegisterProtocol(ALPROTO_DCERPC, proto_name); if (DCERPCRegisterPatternsForProtocolDetection() < 0) return; } else { SCLogInfo("Protocol detection and parser disabled for %s protocol.", proto_name); return; } if (AppLayerParserConfParserEnabled("tcp", proto_name)) { AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_DCERPC, STREAM_TOSERVER, DCERPCParseRequest); AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_DCERPC, STREAM_TOCLIENT, DCERPCParseResponse); AppLayerParserRegisterStateFuncs(IPPROTO_TCP, ALPROTO_DCERPC, DCERPCStateAlloc, DCERPCStateFree); AppLayerParserRegisterParserAcceptableDataDirection(IPPROTO_TCP, ALPROTO_DCERPC, STREAM_TOSERVER); AppLayerParserRegisterTxFreeFunc(IPPROTO_TCP, ALPROTO_DCERPC, DCERPCStateTransactionFree); AppLayerParserRegisterDetectStateFuncs(IPPROTO_TCP, ALPROTO_DCERPC, DCERPCGetTxDetectState, DCERPCSetTxDetectState); AppLayerParserRegisterGetTx(IPPROTO_TCP, ALPROTO_DCERPC, DCERPCGetTx); AppLayerParserRegisterGetTxCnt(IPPROTO_TCP, ALPROTO_DCERPC, DCERPCGetTxCnt); AppLayerParserRegisterGetStateProgressFunc(IPPROTO_TCP, ALPROTO_DCERPC, DCERPCGetAlstateProgress); AppLayerParserRegisterGetStateProgressCompletionStatus(ALPROTO_DCERPC, DCERPCGetAlstateProgressCompletionStatus); } else { SCLogInfo("Parsed disabled for %s protocol. Protocol detection" "still on.", proto_name); } #ifdef UNITTESTS AppLayerParserRegisterProtocolUnittests(IPPROTO_TCP, ALPROTO_DCERPC, DCERPCParserRegisterTests); #endif return; } /* UNITTESTS */ #ifdef UNITTESTS /** \test DCERPC Header Parsing and BIND / BIND_ACK multiple UUID handling */ /* set this to 1 to see problem */ static int DCERPCParserTest01(void) { int result = 1; Flow f; uint8_t dcerpcbind[] = { 0x05, 0x00, 0x0b, 0x03, 0x10, 0x00, 0x00, 0x00, 0x3c, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x16, 0xd0, 0x16, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x2c, 0xd0, 0x28, 0xda, 0x76, 0x91, 0xf6, 0x6e, 0xcb, 0x0f, 0xbf, 0x85, 0xcd, 0x9b, 0xf6, 0x39, 0x01, 0x00, 0x03, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x2c, 0x75, 0xce, 0x7e, 0x82, 0x3b, 0x06, 0xac, 0x1b, 0xf0, 0xf5, 0xb7, 0xa7, 0xf7, 0x28, 0xaf, 0x05, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0xe3, 0xb2, 0x10, 0xd1, 0xd0, 0x0c, 0xcc, 0x3d, 0x2f, 0x80, 0x20, 0x7c, 0xef, 0xe7, 0x09, 0xe0, 0x04, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0xde, 0x85, 0x70, 0xc4, 0x02, 0x7c, 0x60, 0x23, 0x67, 0x0c, 0x22, 0xbf, 0x18, 0x36, 0x79, 0x17, 0x01, 0x00, 0x02, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x00, 0x41, 0x65, 0x29, 0x51, 0xaa, 0xe7, 0x7b, 0xa8, 0xf2, 0x37, 0x0b, 0xd0, 0x3f, 0xb3, 0x36, 0xed, 0x05, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x05, 0x00, 0x01, 0x00, 0x14, 0x96, 0x80, 0x01, 0x2e, 0x78, 0xfb, 0x5d, 0xb4, 0x3c, 0x14, 0xb3, 0x3d, 0xaa, 0x02, 0xfb, 0x06, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x06, 0x00, 0x01, 0x00, 0x3b, 0x04, 0x68, 0x3e, 0x63, 0xfe, 0x9f, 0xd8, 0x64, 0x55, 0xcd, 0xe7, 0x39, 0xaf, 0x98, 0x9f, 0x03, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x07, 0x00, 0x01, 0x00, 0x16, 0x7a, 0x4f, 0x1b, 0xdb, 0x25, 0x92, 0x55, 0xdd, 0xae, 0x9e, 0x5b, 0x3e, 0x93, 0x66, 0x93, 0x04, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00, 0xe8, 0xa4, 0x8a, 0xcf, 0x95, 0x6c, 0xc7, 0x8f, 0x14, 0xcc, 0x56, 0xfc, 0x7b, 0x5f, 0x4f, 0xe8, 0x04, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x09, 0x00, 0x01, 0x00, 0xd8, 0xda, 0xfb, 0xbc, 0xa2, 0x55, 0x6f, 0x5d, 0xc0, 0x2d, 0x88, 0x6f, 0x00, 0x17, 0x52, 0x8d, 0x06, 0x00, 0x03, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x01, 0x00, 0x3f, 0x17, 0x55, 0x0c, 0xf4, 0x23, 0x3c, 0xca, 0xe6, 0xa0, 0xaa, 0xcc, 0xb5, 0xe3, 0xf9, 0xce, 0x04, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x01, 0x00, 0x6a, 0x28, 0x19, 0x39, 0x0c, 0xb1, 0xd0, 0x11, 0x9b, 0xa8, 0x00, 0xc0, 0x4f, 0xd9, 0x2e, 0xf5, 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x01, 0x00, 0xc9, 0x9f, 0x3e, 0x6e, 0x82, 0x0a, 0x2b, 0x28, 0x37, 0x78, 0xe1, 0x13, 0x70, 0x05, 0x38, 0x4d, 0x01, 0x00, 0x02, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x01, 0x00, 0x11, 0xaa, 0x4b, 0x15, 0xdf, 0xa6, 0x86, 0x3f, 0xfb, 0xe0, 0x09, 0xb7, 0xf8, 0x56, 0xd2, 0x3f, 0x05, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x01, 0x00, 0xee, 0x99, 0xc4, 0x25, 0x11, 0xe4, 0x95, 0x62, 0x29, 0xfa, 0xfd, 0x26, 0x57, 0x02, 0xf1, 0xce, 0x03, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x01, 0x00, 0xba, 0x81, 0x9e, 0x1a, 0xdf, 0x2b, 0xba, 0xe4, 0xd3, 0x17, 0x41, 0x60, 0x6d, 0x2d, 0x9e, 0x28, 0x03, 0x00, 0x03, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x10, 0x00, 0x01, 0x00, 0xa0, 0x24, 0x03, 0x9a, 0xa9, 0x99, 0xfb, 0xbe, 0x49, 0x11, 0xad, 0x77, 0x30, 0xaa, 0xbc, 0xb6, 0x02, 0x00, 0x03, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x11, 0x00, 0x01, 0x00, 0x32, 0x04, 0x7e, 0xae, 0xec, 0x28, 0xd1, 0x55, 0x83, 0x4e, 0xc3, 0x47, 0x5d, 0x1d, 0xc6, 0x65, 0x02, 0x00, 0x03, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x12, 0x00, 0x01, 0x00, 0xc6, 0xa4, 0x81, 0x48, 0x66, 0x2a, 0x74, 0x7d, 0x56, 0x6e, 0xc5, 0x1d, 0x19, 0xf2, 0xb5, 0xb6, 0x03, 0x00, 0x02, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x13, 0x00, 0x01, 0x00, 0xcb, 0xae, 0xb3, 0xc0, 0x0c, 0xf4, 0xa4, 0x5e, 0x91, 0x72, 0xdd, 0x53, 0x24, 0x70, 0x89, 0x02, 0x05, 0x00, 0x03, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x14, 0x00, 0x01, 0x00, 0xb8, 0xd0, 0xa0, 0x1a, 0x5e, 0x7a, 0x2d, 0xfe, 0x35, 0xc6, 0x7d, 0x08, 0x0d, 0x33, 0x73, 0x18, 0x02, 0x00, 0x02, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x15, 0x00, 0x01, 0x00, 0x21, 0xd3, 0xaa, 0x09, 0x03, 0xa7, 0x0b, 0xc2, 0x06, 0x45, 0xd9, 0x6c, 0x75, 0xc2, 0x15, 0xa8, 0x01, 0x00, 0x03, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x16, 0x00, 0x01, 0x00, 0xe1, 0xbd, 0x59, 0xfc, 0xbc, 0xa9, 0x95, 0xc2, 0x68, 0x79, 0xf3, 0x75, 0xe0, 0xae, 0x6c, 0xe5, 0x04, 0x00, 0x02, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x17, 0x00, 0x01, 0x00, 0x06, 0x52, 0xb4, 0x71, 0x70, 0x15, 0x4e, 0xf5, 0x7f, 0x08, 0x86, 0x14, 0xe6, 0x17, 0xd5, 0x97, 0x04, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00}; uint8_t dcerpcbindack[] = { 0x05, 0x00, 0x0c, 0x03, 0x10, 0x00, 0x00, 0x00, 0x6c, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb8, 0x10, 0xb8, 0x10, 0xce, 0x47, 0x00, 0x00, 0x0c, 0x00, 0x5c, 0x50, 0x49, 0x50, 0x45, 0x5c, 0x6c, 0x73, 0x61, 0x73, 0x73, 0x00, 0xf6, 0x6e, 0x18, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; uint8_t dcerpcrequest[] = { 0x05, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00, 0x0b, 0x00, 0x09, 0x00, 0x45, 0x00, 0x2c, 0x00, 0x4d, 0x00, 0x73, 0x00, 0x53, 0x00, 0x59, 0x00, 0x2a, 0x00, 0x4a, 0x00, 0x7a, 0x00, 0x3e, 0x00, 0x58, 0x00, 0x21, 0x00, 0x4a, 0x00, 0x30, 0x00, 0x41, 0x00, 0x4b, 0x00, 0x4b, 0x00, 0x3c, 0x00, 0x48, 0x00, 0x24, 0x00, 0x38, 0x00, 0x54, 0x00, 0x60, 0x00, 0x2d, 0x00, 0x29, 0x00, 0x64, 0x00, 0x5b, 0x00, 0x77, 0x00, 0x3a, 0x00, 0x4c, 0x00, 0x24, 0x00, 0x23, 0x00, 0x66, 0x00, 0x43, 0x00, 0x68, 0x00, 0x22, 0x00, 0x55, 0x00, 0x29, 0x00, 0x2c, 0x00, 0x4f, 0x00, 0x5a, 0x00, 0x50, 0x00, 0x61, 0x00, 0x2a, 0x00, 0x6f, 0x00, 0x2f, 0x00, 0x4d, 0x00, 0x68, 0x00, 0x3a, 0x00, 0x5c, 0x00, 0x67, 0x00, 0x68, 0x00, 0x68, 0x00, 0x49, 0x00, 0x45, 0x00, 0x4c, 0x00, 0x72, 0x00, 0x53, 0x00, 0x4c, 0x00, 0x25, 0x00, 0x4d, 0x00, 0x67, 0x00, 0x2e, 0x00, 0x4f, 0x00, 0x64, 0x00, 0x61, 0x00, 0x73, 0x00, 0x24, 0x00, 0x46, 0x00, 0x35, 0x00, 0x2e, 0x00, 0x45, 0x00, 0x6f, 0x00, 0x40, 0x00, 0x41, 0x00, 0x33, 0x00, 0x38, 0x00, 0x47, 0x00, 0x71, 0x00, 0x5a, 0x00, 0x37, 0x00, 0x7a, 0x00, 0x35, 0x00, 0x6b, 0x00, 0x3c, 0x00, 0x26, 0x00, 0x37, 0x00, 0x69, 0x00, 0x75, 0x00, 0x36, 0x00, 0x37, 0x00, 0x47, 0x00, 0x21, 0x00, 0x2d, 0x00, 0x69, 0x00, 0x37, 0x00, 0x78, 0x00, 0x5f, 0x00, 0x72, 0x00, 0x4b, 0x00, 0x5c, 0x00, 0x74, 0x00, 0x3e, 0x00, 0x52, 0x00, 0x7a, 0x00, 0x49, 0x00, 0x31, 0x00, 0x5a, 0x00, 0x7b, 0x00, 0x29, 0x00, 0x3b, 0x00, 0x78, 0x00, 0x3b, 0x00, 0x55, 0x00, 0x3e, 0x00, 0x35, 0x00, 0x2b, 0x00, 0x4e, 0x00, 0x4f, 0x00, 0x59, 0x00, 0x38, 0x00, 0x2a, 0x00, 0x59, 0x00, 0x6b, 0x00, 0x42, 0x00, 0x4c, 0x00, 0x3e, 0x00, 0x6a, 0x00, 0x49, 0x00, 0x2c, 0x00, 0x79, 0x00, 0x6e, 0x00, 0x35, 0x00, 0x4f, 0x00, 0x49, 0x00, 0x55, 0x00, 0x35, 0x00, 0x61, 0x00, 0x72, 0x00, 0x77, 0x00, 0x38, 0x00, 0x32, 0x00, 0x24, 0x00, 0x46, 0x00, 0x32, 0x00, 0x32, 0x00, 0x27, 0x00, 0x64, 0x00, 0x5a, 0x00, 0x77, 0x00, 0x2e, 0x00, 0x37, 0x00, 0x77, 0x00, 0x2e, 0x00, 0x28, 0x00, 0x63, 0x00, 0x4f, 0x00, 0x67, 0x00, 0x64, 0x00, 0x39, 0x00, 0x37, 0x00, 0x31, 0x00, 0x30, 0x00, 0x28, 0x00, 0x2e, 0x00, 0x6f, 0x00, 0x3e, 0x00, 0x59, 0x00, 0x28, 0x00, 0x67, 0x00, 0x52, 0x00, 0x35, 0x00, 0x5a, 0x00, 0x7c, 0x00, 0x56, 0x00, 0x6a, 0x00, 0x5c, 0x00, 0x3c, 0x00, 0x30, 0x00, 0x59, 0x00, 0x5c, 0x00, 0x5e, 0x00, 0x38, 0x00, 0x54, 0x00, 0x5c, 0x00, 0x5b, 0x00, 0x42, 0x00, 0x62, 0x00, 0x70, 0x00, 0x34, 0x00, 0x5c, 0x00, 0x57, 0x00, 0x7a, 0x00, 0x4b, 0x00, 0x2f, 0x00, 0x6b, 0x00, 0x6a, 0x00, 0x4f, 0x00, 0x41, 0x00, 0x33, 0x00, 0x52, 0x00, 0x36, 0x00, 0x27, 0x00, 0x30, 0x00, 0x6d, 0x00, 0x4a, 0x00, 0x30, 0x00, 0x78, 0x00, 0x46, 0x00, 0x65, 0x00, 0x4e, 0x00, 0x29, 0x00, 0x66, 0x00, 0x3f, 0x00, 0x72, 0x00, 0x71, 0x00, 0x75, 0x00, 0x4c, 0x00, 0x2b, 0x00, 0x5c, 0x00, 0x46, 0x00, 0x52, 0x00, 0x7b, 0x00, 0x5c, 0x00, 0x69, 0x00, 0x66, 0x00, 0x56, 0x00, 0x31, 0x00, 0x2d, 0x00, 0x72, 0x00, 0x61, 0x00, 0x68, 0x00, 0x28, 0x00, 0x7d, 0x00, 0x58, 0x00, 0x2a, 0x00, 0x7b, 0x00, 0x28, 0x00, 0x5b, 0x00, 0x54, 0x00, 0x3a, 0x00, 0x26, 0x00, 0x52, 0x00, 0x44, 0x00, 0x60, 0x00, 0x50, 0x00, 0x65, 0x00, 0x48, 0x00, 0x7d, 0x00, 0x2a, 0x00, 0x74, 0x00, 0x49, 0x00, 0x7b, 0x00, 0x21, 0x00, 0x61, 0x00, 0x52, 0x00, 0x43, 0x00, 0x5f, 0x00, 0x5a, 0x00, 0x74, 0x00, 0x5c, 0x00, 0x62, 0x00, 0x68, 0x00, 0x6c, 0x00, 0x6c, 0x00, 0x2b, 0x00, 0x6f, 0x00, 0x7c, 0x00, 0x42, 0x00, 0x67, 0x00, 0x32, 0x00, 0x58, 0x00, 0x35, 0x00, 0x30, 0x00, 0x2f, 0x00, 0x2d, 0x00, 0x60, 0x00, 0x62, 0x00, 0x51, 0x00, 0x2a, 0x00, 0x30, 0x00, 0x31, 0x00, 0x48, 0x00, 0x5b, 0x00, 0x5b, 0x00, 0x5d, 0x00, 0x25, 0x00, 0x58, 0x00, 0x4a, 0x00, 0x76, 0x00, 0x32, 0x00, 0x62, 0x00, 0x27, 0x00, 0x42, 0x00, 0x40, 0x00, 0x53, 0x00, 0x7c, 0x00, 0x7d, 0x00, 0x50, 0x00, 0x3d, 0x00, 0x40, 0x00, 0x76, 0x00, 0x38, 0x00, 0x58, 0x00, 0x39, 0x00, 0x63, 0x00, 0x3c, 0x00, 0x5b, 0x00, 0x23, 0x00, 0x53, 0x00, 0x7a, 0x00, 0x54, 0x00, 0x74, 0x00, 0x61, 0x00, 0x76, 0x00, 0x4a, 0x00, 0x3e, 0x00, 0x33, 0x00, 0x75, 0x00, 0x66, 0x00, 0x2d, 0x00, 0x48, 0x00, 0x33, 0x00, 0x71, 0x00, 0x76, 0x00, 0x48, 0x00, 0x71, 0x00, 0x41, 0x00, 0x6f, 0x00, 0x2a, 0x00, 0x67, 0x00, 0x70, 0x00, 0x21, 0x00, 0x70, 0x00, 0x4b, 0x00, 0x52, 0x00, 0x58, 0x00, 0x68, 0x00, 0x23, 0x00, 0x39, 0x00, 0x46, 0x00, 0x4d, 0x00, 0x51, 0x00, 0x57, 0x00, 0x3a, 0x00, 0x79, 0x00, 0x7b, 0x00, 0x6c, 0x00, 0x55, 0x00, 0x33, 0x00, 0x65, 0x00, 0x49, 0x00, 0x72, 0x00, 0x30, 0x00, 0x4f, 0x00, 0x41, 0x00, 0x6e, 0x00, 0x31, 0x00, 0x4a, 0x00, 0x60, 0x00, 0x79, 0x00, 0x70, 0x00, 0x4f, 0x00, 0x58, 0x00, 0x75, 0x00, 0x44, 0x00, 0x59, 0x00, 0x58, 0x00, 0x46, 0x00, 0x3d, 0x00, 0x46, 0x00, 0x74, 0x00, 0x51, 0x00, 0x57, 0x00, 0x6e, 0x00, 0x2d, 0x00, 0x47, 0x00, 0x23, 0x00, 0x45, 0x00, 0x60, 0x00, 0x4c, 0x00, 0x72, 0x00, 0x4e, 0x00, 0x74, 0x00, 0x40, 0x00, 0x76, 0x00, 0x75, 0x00, 0x74, 0x00, 0x56, 0x00, 0x44, 0x00, 0x29, 0x00, 0x62, 0x00, 0x58, 0x00, 0x31, 0x00, 0x78, 0x00, 0x32, 0x00, 0x52, 0x00, 0x4a, 0x00, 0x6b, 0x00, 0x55, 0x00, 0x72, 0x00, 0x6f, 0x00, 0x6f, 0x00, 0x4a, 0x00, 0x54, 0x00, 0x7d, 0x00, 0x68, 0x00, 0x3f, 0x00, 0x28, 0x00, 0x21, 0x00, 0x53, 0x00, 0x48, 0x00, 0x5a, 0x00, 0x34, 0x00, 0x36, 0x00, 0x35, 0x00, 0x64, 0x00, 0x4e, 0x00, 0x75, 0x00, 0x69, 0x00, 0x23, 0x00, 0x75, 0x00, 0x55, 0x00, 0x43, 0x00, 0x75, 0x00, 0x2f, 0x00, 0x73, 0x00, 0x62, 0x00, 0x6f, 0x00, 0x37, 0x00, 0x4e, 0x00, 0x25, 0x00, 0x25, 0x00, 0x21, 0x00, 0x3d, 0x00, 0x3c, 0x00, 0x71, 0x00, 0x3e, 0x00, 0x3f, 0x00, 0x30, 0x00, 0x36, 0x00, 0x62, 0x00, 0x63, 0x00, 0x53, 0x00, 0x54, 0x00, 0x5d, 0x00, 0x61, 0x00, 0x4c, 0x00, 0x28, 0x00, 0x2b, 0x00, 0x4c, 0x00, 0x4e, 0x00, 0x66, 0x00, 0x5f, 0x00, 0x4b, 0x00, 0x43, 0x00, 0x75, 0x00, 0x45, 0x00, 0x37, 0x00, 0x28, 0x00, 0x56, 0x00, 0x36, 0x00, 0x6a, 0x00, 0x3e, 0x00, 0x64, 0x00, 0x34, 0x00, 0x6a, 0x00, 0x7d, 0x00, 0x4a, 0x00, 0x66, 0x00, 0x7a, 0x00, 0x3e, 0x00, 0x75, 0x00, 0x38, 0x00, 0x7b, 0x00, 0x42, 0x00, 0x76, 0x00, 0x29, 0x00, 0x4c, 0x00, 0x65, 0x00, 0x2e, 0x00, 0x32, 0x00, 0x4b, 0x00, 0x2b, 0x00, 0x51, 0x00, 0x47, 0x00, 0x22, 0x00, 0x48, 0x00, 0x3d, 0x00, 0x49, 0x00, 0x44, 0x00, 0x5d, 0x00, 0x59, 0x00, 0x63, 0x00, 0x5c, 0x00, 0x24, 0x00, 0x35, 0x00, 0x34, 0x00, 0x70, 0x00, 0x69, 0x00}; uint32_t requestlen = sizeof(dcerpcrequest); uint32_t bindlen = sizeof(dcerpcbind); uint32_t bindacklen = sizeof(dcerpcbindack); TcpSession ssn; DCERPCUuidEntry *uuid_entry; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&f, 0, sizeof(f)); memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); f.protoctx = (void *)&ssn; f.proto = IPPROTO_TCP; f.alproto = ALPROTO_DCERPC; StreamTcpInitConfig(TRUE); FLOWLOCK_WRLOCK(&f); int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER | STREAM_START, dcerpcbind, bindlen); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); DCERPCState *dcerpc_state = f.alstate; if (dcerpc_state == NULL) { printf("no dcerpc state: "); result = 0; goto end; } if (dcerpc_state->dcerpc.dcerpchdr.rpc_vers != 5) { printf("expected dcerpc version 0x05, got 0x%02x : ", dcerpc_state->dcerpc.dcerpchdr.rpc_vers); result = 0; goto end; } if (dcerpc_state->dcerpc.dcerpchdr.type != BIND) { printf("expected dcerpc type 0x%02x , got 0x%02x : ", BIND, dcerpc_state->dcerpc.dcerpchdr.type); result = 0; goto end; } if (dcerpc_state->dcerpc.dcerpchdr.frag_length != 1084) { printf("expected dcerpc frag_length 0x%02x , got 0x%02x : ", 1084, dcerpc_state->dcerpc.dcerpchdr.frag_length); result = 0; goto end; } FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOCLIENT, dcerpcbindack, bindacklen); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); if (dcerpc_state->dcerpc.dcerpchdr.type != BIND_ACK) { printf("expected dcerpc type 0x%02x , got 0x%02x : ", BIND_ACK, dcerpc_state->dcerpc.dcerpchdr.type); result = 0; goto end; } if (dcerpc_state->dcerpc.dcerpchdr.frag_length != 620) { printf("expected dcerpc frag_length 0x%02x , got 0x%02x : ", 620, dcerpc_state->dcerpc.dcerpchdr.frag_length); result = 0; goto end; } TAILQ_FOREACH(uuid_entry, &dcerpc_state->dcerpc.dcerpcbindbindack.uuid_list, next) { printUUID("BIND_ACK", uuid_entry); } FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER | STREAM_EOF, dcerpcrequest, requestlen); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); if (dcerpc_state->dcerpc.dcerpchdr.type != REQUEST) { printf("expected dcerpc type 0x%02x , got 0x%02x : ", REQUEST, dcerpc_state->dcerpc.dcerpchdr.type); result = 0; goto end; } end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); StreamTcpFreeConfig(TRUE); FLOW_DESTROY(&f); return result; } /** \test DCERPC Request decoding and opnum parsing. */ static int DCERPCParserTest02(void) { int result = 1; Flow f; uint8_t dcerpcrequest[] = { 0x05, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00, 0x0b, 0x00, 0x09, 0x00, 0x45, 0x00, 0x2c, 0x00, 0x4d, 0x00, 0x73, 0x00, 0x53, 0x00, 0x59, 0x00, 0x2a, 0x00, 0x4a, 0x00, 0x7a, 0x00, 0x3e, 0x00, 0x58, 0x00, 0x21, 0x00, 0x4a, 0x00, 0x30, 0x00, 0x41, 0x00, 0x4b, 0x00, 0x4b, 0x00, 0x3c, 0x00, 0x48, 0x00, 0x24, 0x00, 0x38, 0x00, 0x54, 0x00, 0x60, 0x00, 0x2d, 0x00, 0x29, 0x00, 0x64, 0x00, 0x5b, 0x00, 0x77, 0x00, 0x3a, 0x00, 0x4c, 0x00, 0x24, 0x00, 0x23, 0x00, 0x66, 0x00, 0x43, 0x00, 0x68, 0x00, 0x22, 0x00, 0x55, 0x00, 0x29, 0x00, 0x2c, 0x00, 0x4f, 0x00, 0x5a, 0x00, 0x50, 0x00, 0x61, 0x00, 0x2a, 0x00, 0x6f, 0x00, 0x2f, 0x00, 0x4d, 0x00, 0x68, 0x00, 0x3a, 0x00, 0x5c, 0x00, 0x67, 0x00, 0x68, 0x00, 0x68, 0x00, 0x49, 0x00, 0x45, 0x00, 0x4c, 0x00, 0x72, 0x00, 0x53, 0x00, 0x4c, 0x00, 0x25, 0x00, 0x4d, 0x00, 0x67, 0x00, 0x2e, 0x00, 0x4f, 0x00, 0x64, 0x00, 0x61, 0x00, 0x73, 0x00, 0x24, 0x00, 0x46, 0x00, 0x35, 0x00, 0x2e, 0x00, 0x45, 0x00, 0x6f, 0x00, 0x40, 0x00, 0x41, 0x00, 0x33, 0x00, 0x38, 0x00, 0x47, 0x00, 0x71, 0x00, 0x5a, 0x00, 0x37, 0x00, 0x7a, 0x00, 0x35, 0x00, 0x6b, 0x00, 0x3c, 0x00, 0x26, 0x00, 0x37, 0x00, 0x69, 0x00, 0x75, 0x00, 0x36, 0x00, 0x37, 0x00, 0x47, 0x00, 0x21, 0x00, 0x2d, 0x00, 0x69, 0x00, 0x37, 0x00, 0x78, 0x00, 0x5f, 0x00, 0x72, 0x00, 0x4b, 0x00, 0x5c, 0x00, 0x74, 0x00, 0x3e, 0x00, 0x52, 0x00, 0x7a, 0x00, 0x49, 0x00, 0x31, 0x00, 0x5a, 0x00, 0x7b, 0x00, 0x29, 0x00, 0x3b, 0x00, 0x78, 0x00, 0x3b, 0x00, 0x55, 0x00, 0x3e, 0x00, 0x35, 0x00, 0x2b, 0x00, 0x4e, 0x00, 0x4f, 0x00, 0x59, 0x00, 0x38, 0x00, 0x2a, 0x00, 0x59, 0x00, 0x6b, 0x00, 0x42, 0x00, 0x4c, 0x00, 0x3e, 0x00, 0x6a, 0x00, 0x49, 0x00, 0x2c, 0x00, 0x79, 0x00, 0x6e, 0x00, 0x35, 0x00, 0x4f, 0x00, 0x49, 0x00, 0x55, 0x00, 0x35, 0x00, 0x61, 0x00, 0x72, 0x00, 0x77, 0x00, 0x38, 0x00, 0x32, 0x00, 0x24, 0x00, 0x46, 0x00, 0x32, 0x00, 0x32, 0x00, 0x27, 0x00, 0x64, 0x00, 0x5a, 0x00, 0x77, 0x00, 0x2e, 0x00, 0x37, 0x00, 0x77, 0x00, 0x2e, 0x00, 0x28, 0x00, 0x63, 0x00, 0x4f, 0x00, 0x67, 0x00, 0x64, 0x00, 0x39, 0x00, 0x37, 0x00, 0x31, 0x00, 0x30, 0x00, 0x28, 0x00, 0x2e, 0x00, 0x6f, 0x00, 0x3e, 0x00, 0x59, 0x00, 0x28, 0x00, 0x67, 0x00, 0x52, 0x00, 0x35, 0x00, 0x5a, 0x00, 0x7c, 0x00, 0x56, 0x00, 0x6a, 0x00, 0x5c, 0x00, 0x3c, 0x00, 0x30, 0x00, 0x59, 0x00, 0x5c, 0x00, 0x5e, 0x00, 0x38, 0x00, 0x54, 0x00, 0x5c, 0x00, 0x5b, 0x00, 0x42, 0x00, 0x62, 0x00, 0x70, 0x00, 0x34, 0x00, 0x5c, 0x00, 0x57, 0x00, 0x7a, 0x00, 0x4b, 0x00, 0x2f, 0x00, 0x6b, 0x00, 0x6a, 0x00, 0x4f, 0x00, 0x41, 0x00, 0x33, 0x00, 0x52, 0x00, 0x36, 0x00, 0x27, 0x00, 0x30, 0x00, 0x6d, 0x00, 0x4a, 0x00, 0x30, 0x00, 0x78, 0x00, 0x46, 0x00, 0x65, 0x00, 0x4e, 0x00, 0x29, 0x00, 0x66, 0x00, 0x3f, 0x00, 0x72, 0x00, 0x71, 0x00, 0x75, 0x00, 0x4c, 0x00, 0x2b, 0x00, 0x5c, 0x00, 0x46, 0x00, 0x52, 0x00, 0x7b, 0x00, 0x5c, 0x00, 0x69, 0x00, 0x66, 0x00, 0x56, 0x00, 0x31, 0x00, 0x2d, 0x00, 0x72, 0x00, 0x61, 0x00, 0x68, 0x00, 0x28, 0x00, 0x7d, 0x00, 0x58, 0x00, 0x2a, 0x00, 0x7b, 0x00, 0x28, 0x00, 0x5b, 0x00, 0x54, 0x00, 0x3a, 0x00, 0x26, 0x00, 0x52, 0x00, 0x44, 0x00, 0x60, 0x00, 0x50, 0x00, 0x65, 0x00, 0x48, 0x00, 0x7d, 0x00, 0x2a, 0x00, 0x74, 0x00, 0x49, 0x00, 0x7b, 0x00, 0x21, 0x00, 0x61, 0x00, 0x52, 0x00, 0x43, 0x00, 0x5f, 0x00, 0x5a, 0x00, 0x74, 0x00, 0x5c, 0x00, 0x62, 0x00, 0x68, 0x00, 0x6c, 0x00, 0x6c, 0x00, 0x2b, 0x00, 0x6f, 0x00, 0x7c, 0x00, 0x42, 0x00, 0x67, 0x00, 0x32, 0x00, 0x58, 0x00, 0x35, 0x00, 0x30, 0x00, 0x2f, 0x00, 0x2d, 0x00, 0x60, 0x00, 0x62, 0x00, 0x51, 0x00, 0x2a, 0x00, 0x30, 0x00, 0x31, 0x00, 0x48, 0x00, 0x5b, 0x00, 0x5b, 0x00, 0x5d, 0x00, 0x25, 0x00, 0x58, 0x00, 0x4a, 0x00, 0x76, 0x00, 0x32, 0x00, 0x62, 0x00, 0x27, 0x00, 0x42, 0x00, 0x40, 0x00, 0x53, 0x00, 0x7c, 0x00, 0x7d, 0x00, 0x50, 0x00, 0x3d, 0x00, 0x40, 0x00, 0x76, 0x00, 0x38, 0x00, 0x58, 0x00, 0x39, 0x00, 0x63, 0x00, 0x3c, 0x00, 0x5b, 0x00, 0x23, 0x00, 0x53, 0x00, 0x7a, 0x00, 0x54, 0x00, 0x74, 0x00, 0x61, 0x00, 0x76, 0x00, 0x4a, 0x00, 0x3e, 0x00, 0x33, 0x00, 0x75, 0x00, 0x66, 0x00, 0x2d, 0x00, 0x48, 0x00, 0x33, 0x00, 0x71, 0x00, 0x76, 0x00, 0x48, 0x00, 0x71, 0x00, 0x41, 0x00, 0x6f, 0x00, 0x2a, 0x00, 0x67, 0x00, 0x70, 0x00, 0x21, 0x00, 0x70, 0x00, 0x4b, 0x00, 0x52, 0x00, 0x58, 0x00, 0x68, 0x00, 0x23, 0x00, 0x39, 0x00, 0x46, 0x00, 0x4d, 0x00, 0x51, 0x00, 0x57, 0x00, 0x3a, 0x00, 0x79, 0x00, 0x7b, 0x00, 0x6c, 0x00, 0x55, 0x00, 0x33, 0x00, 0x65, 0x00, 0x49, 0x00, 0x72, 0x00, 0x30, 0x00, 0x4f, 0x00, 0x41, 0x00, 0x6e, 0x00, 0x31, 0x00, 0x4a, 0x00, 0x60, 0x00, 0x79, 0x00, 0x70, 0x00, 0x4f, 0x00, 0x58, 0x00, 0x75, 0x00, 0x44, 0x00, 0x59, 0x00, 0x58, 0x00, 0x46, 0x00, 0x3d, 0x00, 0x46, 0x00, 0x74, 0x00, 0x51, 0x00, 0x57, 0x00, 0x6e, 0x00, 0x2d, 0x00, 0x47, 0x00, 0x23, 0x00, 0x45, 0x00, 0x60, 0x00, 0x4c, 0x00, 0x72, 0x00, 0x4e, 0x00, 0x74, 0x00, 0x40, 0x00, 0x76, 0x00, 0x75, 0x00, 0x74, 0x00, 0x56, 0x00, 0x44, 0x00, 0x29, 0x00, 0x62, 0x00, 0x58, 0x00, 0x31, 0x00, 0x78, 0x00, 0x32, 0x00, 0x52, 0x00, 0x4a, 0x00, 0x6b, 0x00, 0x55, 0x00, 0x72, 0x00, 0x6f, 0x00, 0x6f, 0x00, 0x4a, 0x00, 0x54, 0x00, 0x7d, 0x00, 0x68, 0x00, 0x3f, 0x00, 0x28, 0x00, 0x21, 0x00, 0x53, 0x00, 0x48, 0x00, 0x5a, 0x00, 0x34, 0x00, 0x36, 0x00, 0x35, 0x00, 0x64, 0x00, 0x4e, 0x00, 0x75, 0x00, 0x69, 0x00, 0x23, 0x00, 0x75, 0x00, 0x55, 0x00, 0x43, 0x00, 0x75, 0x00, 0x2f, 0x00, 0x73, 0x00, 0x62, 0x00, 0x6f, 0x00, 0x37, 0x00, 0x4e, 0x00, 0x25, 0x00, 0x25, 0x00, 0x21, 0x00, 0x3d, 0x00, 0x3c, 0x00, 0x71, 0x00, 0x3e, 0x00, 0x3f, 0x00, 0x30, 0x00, 0x36, 0x00, 0x62, 0x00, 0x63, 0x00, 0x53, 0x00, 0x54, 0x00, 0x5d, 0x00, 0x61, 0x00, 0x4c, 0x00, 0x28, 0x00, 0x2b, 0x00, 0x4c, 0x00, 0x4e, 0x00, 0x66, 0x00, 0x5f, 0x00, 0x4b, 0x00, 0x43, 0x00, 0x75, 0x00, 0x45, 0x00, 0x37, 0x00, 0x28, 0x00, 0x56, 0x00, 0x36, 0x00, 0x6a, 0x00, 0x3e, 0x00, 0x64, 0x00, 0x34, 0x00, 0x6a, 0x00, 0x7d, 0x00, 0x4a, 0x00, 0x66, 0x00, 0x7a, 0x00, 0x3e, 0x00, 0x75, 0x00, 0x38, 0x00, 0x7b, 0x00, 0x42, 0x00, 0x76, 0x00, 0x29, 0x00, 0x4c, 0x00, 0x65, 0x00, 0x2e, 0x00, 0x32, 0x00, 0x4b, 0x00, 0x2b, 0x00, 0x51, 0x00, 0x47, 0x00, 0x22, 0x00, 0x48, 0x00, 0x3d, 0x00, 0x49, 0x00, 0x44, 0x00, 0x5d, 0x00, 0x59, 0x00, 0x63, 0x00, 0x5c, 0x00, 0x24, 0x00, 0x35, 0x00, 0x34, 0x00, 0x70, 0x00, 0x69, 0x00}; uint32_t requestlen = sizeof(dcerpcrequest); TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&f, 0, sizeof(f)); memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); f.protoctx = (void *)&ssn; f.proto = IPPROTO_TCP; f.alproto = ALPROTO_DCERPC; StreamTcpInitConfig(TRUE); FLOWLOCK_WRLOCK(&f); int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER | STREAM_START, dcerpcrequest, requestlen); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); DCERPCState *dcerpc_state = f.alstate; if (dcerpc_state == NULL) { printf("no dcerpc state: "); result = 0; goto end; } if (dcerpc_state->dcerpc.dcerpchdr.rpc_vers != 5) { printf("expected dcerpc version 0x05, got 0x%02x : ", dcerpc_state->dcerpc.dcerpchdr.rpc_vers); result = 0; goto end; } if (dcerpc_state->dcerpc.dcerpchdr.type != REQUEST) { printf("expected dcerpc type 0x%02x , got 0x%02x : ", REQUEST, dcerpc_state->dcerpc.dcerpchdr.type); result = 0; goto end; } if (dcerpc_state->dcerpc.dcerpchdr.frag_length != 1024) { printf("expected dcerpc frag_length 0x%02x , got 0x%02x : ", 1024, dcerpc_state->dcerpc.dcerpchdr.frag_length); result = 0; goto end; } if (dcerpc_state->dcerpc.dcerpcrequest.opnum != 9) { printf("expected dcerpc opnum 0x%02x , got 0x%02x : ", 9, dcerpc_state->dcerpc.dcerpcrequest.opnum); result = 0; goto end; } end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); StreamTcpFreeConfig(TRUE); FLOW_DESTROY(&f); return result; } /** \test Test endianness handling */ static int DCERPCParserTest03(void) { int result = 1; Flow f; uint8_t dcerpcrequest[] = { 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x09, 0x45, 0x00, 0x2c, 0x00, 0x4d, 0x00, 0x73, 0x00, 0x53, 0x00, 0x59, 0x00, 0x2a, 0x00, 0x4a, 0x00, 0x7a, 0x00, 0x3e, 0x00, 0x58, 0x00, 0x21, 0x00, 0x4a, 0x00, 0x30, 0x00, 0x41, 0x00, 0x4b, 0x00, 0x4b, 0x00, 0x3c, 0x00, 0x48, 0x00, 0x24, 0x00, 0x38, 0x00, 0x54, 0x00, 0x60, 0x00, 0x2d, 0x00, 0x29, 0x00, 0x64, 0x00, 0x5b, 0x00, 0x77, 0x00, 0x3a, 0x00, 0x4c, 0x00, 0x24, 0x00, 0x23, 0x00, 0x66, 0x00, 0x43, 0x00, 0x68, 0x00, 0x22, 0x00, 0x55, 0x00, 0x29, 0x00, 0x2c, 0x00, 0x4f, 0x00, 0x5a, 0x00, 0x50, 0x00, 0x61, 0x00, 0x2a, 0x00, 0x6f, 0x00, 0x2f, 0x00, 0x4d, 0x00, 0x68, 0x00, 0x3a, 0x00, 0x5c, 0x00, 0x67, 0x00, 0x68, 0x00, 0x68, 0x00, 0x49, 0x00, 0x45, 0x00, 0x4c, 0x00, 0x72, 0x00, 0x53, 0x00, 0x4c, 0x00, 0x25, 0x00, 0x4d, 0x00, 0x67, 0x00, 0x2e, 0x00, 0x4f, 0x00, 0x64, 0x00, 0x61, 0x00, 0x73, 0x00, 0x24, 0x00, 0x46, 0x00, 0x35, 0x00, 0x2e, 0x00, 0x45, 0x00, 0x6f, 0x00, 0x40, 0x00, 0x41, 0x00, 0x33, 0x00, 0x38, 0x00, 0x47, 0x00, 0x71, 0x00, 0x5a, 0x00, 0x37, 0x00, 0x7a, 0x00, 0x35, 0x00, 0x6b, 0x00, 0x3c, 0x00, 0x26, 0x00, 0x37, 0x00, 0x69, 0x00, 0x75, 0x00, 0x36, 0x00, 0x37, 0x00, 0x47, 0x00, 0x21, 0x00, 0x2d, 0x00, 0x69, 0x00, 0x37, 0x00, 0x78, 0x00, 0x5f, 0x00, 0x72, 0x00, 0x4b, 0x00, 0x5c, 0x00, 0x74, 0x00, 0x3e, 0x00, 0x52, 0x00, 0x7a, 0x00, 0x49, 0x00, 0x31, 0x00, 0x5a, 0x00, 0x7b, 0x00, 0x29, 0x00, 0x3b, 0x00, 0x78, 0x00, 0x3b, 0x00, 0x55, 0x00, 0x3e, 0x00, 0x35, 0x00, 0x2b, 0x00, 0x4e, 0x00, 0x4f, 0x00, 0x59, 0x00, 0x38, 0x00, 0x2a, 0x00, 0x59, 0x00, 0x6b, 0x00, 0x42, 0x00, 0x4c, 0x00, 0x3e, 0x00, 0x6a, 0x00, 0x49, 0x00, 0x2c, 0x00, 0x79, 0x00, 0x6e, 0x00, 0x35, 0x00, 0x4f, 0x00, 0x49, 0x00, 0x55, 0x00, 0x35, 0x00, 0x61, 0x00, 0x72, 0x00, 0x77, 0x00, 0x38, 0x00, 0x32, 0x00, 0x24, 0x00, 0x46, 0x00, 0x32, 0x00, 0x32, 0x00, 0x27, 0x00, 0x64, 0x00, 0x5a, 0x00, 0x77, 0x00, 0x2e, 0x00, 0x37, 0x00, 0x77, 0x00, 0x2e, 0x00, 0x28, 0x00, 0x63, 0x00, 0x4f, 0x00, 0x67, 0x00, 0x64, 0x00, 0x39, 0x00, 0x37, 0x00, 0x31, 0x00, 0x30, 0x00, 0x28, 0x00, 0x2e, 0x00, 0x6f, 0x00, 0x3e, 0x00, 0x59, 0x00, 0x28, 0x00, 0x67, 0x00, 0x52, 0x00, 0x35, 0x00, 0x5a, 0x00, 0x7c, 0x00, 0x56, 0x00, 0x6a, 0x00, 0x5c, 0x00, 0x3c, 0x00, 0x30, 0x00, 0x59, 0x00, 0x5c, 0x00, 0x5e, 0x00, 0x38, 0x00, 0x54, 0x00, 0x5c, 0x00, 0x5b, 0x00, 0x42, 0x00, 0x62, 0x00, 0x70, 0x00, 0x34, 0x00, 0x5c, 0x00, 0x57, 0x00, 0x7a, 0x00, 0x4b, 0x00, 0x2f, 0x00, 0x6b, 0x00, 0x6a, 0x00, 0x4f, 0x00, 0x41, 0x00, 0x33, 0x00, 0x52, 0x00, 0x36, 0x00, 0x27, 0x00, 0x30, 0x00, 0x6d, 0x00, 0x4a, 0x00, 0x30, 0x00, 0x78, 0x00, 0x46, 0x00, 0x65, 0x00, 0x4e, 0x00, 0x29, 0x00, 0x66, 0x00, 0x3f, 0x00, 0x72, 0x00, 0x71, 0x00, 0x75, 0x00, 0x4c, 0x00, 0x2b, 0x00, 0x5c, 0x00, 0x46, 0x00, 0x52, 0x00, 0x7b, 0x00, 0x5c, 0x00, 0x69, 0x00, 0x66, 0x00, 0x56, 0x00, 0x31, 0x00, 0x2d, 0x00, 0x72, 0x00, 0x61, 0x00, 0x68, 0x00, 0x28, 0x00, 0x7d, 0x00, 0x58, 0x00, 0x2a, 0x00, 0x7b, 0x00, 0x28, 0x00, 0x5b, 0x00, 0x54, 0x00, 0x3a, 0x00, 0x26, 0x00, 0x52, 0x00, 0x44, 0x00, 0x60, 0x00, 0x50, 0x00, 0x65, 0x00, 0x48, 0x00, 0x7d, 0x00, 0x2a, 0x00, 0x74, 0x00, 0x49, 0x00, 0x7b, 0x00, 0x21, 0x00, 0x61, 0x00, 0x52, 0x00, 0x43, 0x00, 0x5f, 0x00, 0x5a, 0x00, 0x74, 0x00, 0x5c, 0x00, 0x62, 0x00, 0x68, 0x00, 0x6c, 0x00, 0x6c, 0x00, 0x2b, 0x00, 0x6f, 0x00, 0x7c, 0x00, 0x42, 0x00, 0x67, 0x00, 0x32, 0x00, 0x58, 0x00, 0x35, 0x00, 0x30, 0x00, 0x2f, 0x00, 0x2d, 0x00, 0x60, 0x00, 0x62, 0x00, 0x51, 0x00, 0x2a, 0x00, 0x30, 0x00, 0x31, 0x00, 0x48, 0x00, 0x5b, 0x00, 0x5b, 0x00, 0x5d, 0x00, 0x25, 0x00, 0x58, 0x00, 0x4a, 0x00, 0x76, 0x00, 0x32, 0x00, 0x62, 0x00, 0x27, 0x00, 0x42, 0x00, 0x40, 0x00, 0x53, 0x00, 0x7c, 0x00, 0x7d, 0x00, 0x50, 0x00, 0x3d, 0x00, 0x40, 0x00, 0x76, 0x00, 0x38, 0x00, 0x58, 0x00, 0x39, 0x00, 0x63, 0x00, 0x3c, 0x00, 0x5b, 0x00, 0x23, 0x00, 0x53, 0x00, 0x7a, 0x00, 0x54, 0x00, 0x74, 0x00, 0x61, 0x00, 0x76, 0x00, 0x4a, 0x00, 0x3e, 0x00, 0x33, 0x00, 0x75, 0x00, 0x66, 0x00, 0x2d, 0x00, 0x48, 0x00, 0x33, 0x00, 0x71, 0x00, 0x76, 0x00, 0x48, 0x00, 0x71, 0x00, 0x41, 0x00, 0x6f, 0x00, 0x2a, 0x00, 0x67, 0x00, 0x70, 0x00, 0x21, 0x00, 0x70, 0x00, 0x4b, 0x00, 0x52, 0x00, 0x58, 0x00, 0x68, 0x00, 0x23, 0x00, 0x39, 0x00, 0x46, 0x00, 0x4d, 0x00, 0x51, 0x00, 0x57, 0x00, 0x3a, 0x00, 0x79, 0x00, 0x7b, 0x00, 0x6c, 0x00, 0x55, 0x00, 0x33, 0x00, 0x65, 0x00, 0x49, 0x00, 0x72, 0x00, 0x30, 0x00, 0x4f, 0x00, 0x41, 0x00, 0x6e, 0x00, 0x31, 0x00, 0x4a, 0x00, 0x60, 0x00, 0x79, 0x00, 0x70, 0x00, 0x4f, 0x00, 0x58, 0x00, 0x75, 0x00, 0x44, 0x00, 0x59, 0x00, 0x58, 0x00, 0x46, 0x00, 0x3d, 0x00, 0x46, 0x00, 0x74, 0x00, 0x51, 0x00, 0x57, 0x00, 0x6e, 0x00, 0x2d, 0x00, 0x47, 0x00, 0x23, 0x00, 0x45, 0x00, 0x60, 0x00, 0x4c, 0x00, 0x72, 0x00, 0x4e, 0x00, 0x74, 0x00, 0x40, 0x00, 0x76, 0x00, 0x75, 0x00, 0x74, 0x00, 0x56, 0x00, 0x44, 0x00, 0x29, 0x00, 0x62, 0x00, 0x58, 0x00, 0x31, 0x00, 0x78, 0x00, 0x32, 0x00, 0x52, 0x00, 0x4a, 0x00, 0x6b, 0x00, 0x55, 0x00, 0x72, 0x00, 0x6f, 0x00, 0x6f, 0x00, 0x4a, 0x00, 0x54, 0x00, 0x7d, 0x00, 0x68, 0x00, 0x3f, 0x00, 0x28, 0x00, 0x21, 0x00, 0x53, 0x00, 0x48, 0x00, 0x5a, 0x00, 0x34, 0x00, 0x36, 0x00, 0x35, 0x00, 0x64, 0x00, 0x4e, 0x00, 0x75, 0x00, 0x69, 0x00, 0x23, 0x00, 0x75, 0x00, 0x55, 0x00, 0x43, 0x00, 0x75, 0x00, 0x2f, 0x00, 0x73, 0x00, 0x62, 0x00, 0x6f, 0x00, 0x37, 0x00, 0x4e, 0x00, 0x25, 0x00, 0x25, 0x00, 0x21, 0x00, 0x3d, 0x00, 0x3c, 0x00, 0x71, 0x00, 0x3e, 0x00, 0x3f, 0x00, 0x30, 0x00, 0x36, 0x00, 0x62, 0x00, 0x63, 0x00, 0x53, 0x00, 0x54, 0x00, 0x5d, 0x00, 0x61, 0x00, 0x4c, 0x00, 0x28, 0x00, 0x2b, 0x00, 0x4c, 0x00, 0x4e, 0x00, 0x66, 0x00, 0x5f, 0x00, 0x4b, 0x00, 0x43, 0x00, 0x75, 0x00, 0x45, 0x00, 0x37, 0x00, 0x28, 0x00, 0x56, 0x00, 0x36, 0x00, 0x6a, 0x00, 0x3e, 0x00, 0x64, 0x00, 0x34, 0x00, 0x6a, 0x00, 0x7d, 0x00, 0x4a, 0x00, 0x66, 0x00, 0x7a, 0x00, 0x3e, 0x00, 0x75, 0x00, 0x38, 0x00, 0x7b, 0x00, 0x42, 0x00, 0x76, 0x00, 0x29, 0x00, 0x4c, 0x00, 0x65, 0x00, 0x2e, 0x00, 0x32, 0x00, 0x4b, 0x00, 0x2b, 0x00, 0x51, 0x00, 0x47, 0x00, 0x22, 0x00, 0x48, 0x00, 0x3d, 0x00, 0x49, 0x00, 0x44, 0x00, 0x5d, 0x00, 0x59, 0x00, 0x63, 0x00, 0x5c, 0x00, 0x24, 0x00, 0x35, 0x00, 0x34, 0x00, 0x70, 0x00, 0x69, 0x00}; uint32_t requestlen = sizeof(dcerpcrequest); TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&f, 0, sizeof(f)); memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); f.protoctx = (void *)&ssn; f.proto = IPPROTO_TCP; f.alproto = ALPROTO_DCERPC; StreamTcpInitConfig(TRUE); FLOWLOCK_WRLOCK(&f); int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER | STREAM_START, dcerpcrequest, requestlen); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); DCERPCState *dcerpc_state = f.alstate; if (dcerpc_state == NULL) { printf("no dcerpc state: "); result = 0; goto end; } if (dcerpc_state->dcerpc.dcerpchdr.packed_drep[0] != 0x01) { printf("expected dcerpc data representation 0x01, got 0x%02x : ", dcerpc_state->dcerpc.dcerpchdr.packed_drep[0]); result = 0; goto end; } if (dcerpc_state->dcerpc.dcerpchdr.frag_length != 1024) { printf("expected dcerpc frag_length 0x%02x , got 0x%02x : ", 1024, dcerpc_state->dcerpc.dcerpchdr.frag_length); result = 0; goto end; } if (dcerpc_state->dcerpc.dcerpcrequest.opnum != 9) { printf("expected dcerpc opnum 0x%02x , got 0x%02x : ", 9, dcerpc_state->dcerpc.dcerpcrequest.opnum); result = 0; goto end; } end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); StreamTcpFreeConfig(TRUE); FLOW_DESTROY(&f); return result; } /** * \test General test. */ static int DCERPCParserTest05(void) { int result = 1; Flow f; int r = 0; uint8_t bind1[] = { 0x05, 0x00, 0x0b, 0x01, 0x10, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x16, 0xd0, 0x16, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0xb8, 0x4a, 0x9f, 0x4d, 0x1c, 0x7d, 0xcf, 0x11, 0x86, 0x1e, 0x00, 0x20, 0xaf, 0x6e, 0x7c, 0x57, 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00 }; uint32_t bind1_len = sizeof(bind1); uint8_t bind2[] = { 0x05, 0x00, 0x0b, 0x02, 0x10, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x16, 0xd0, 0x16, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xb8, 0x4a, 0x9f, 0x4d, 0x1c, 0x7d, 0xcf, 0x11, 0x86, 0x1e, 0x00, 0x20, 0xaf, 0x6e, 0x7c, 0x67, 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00 }; uint32_t bind2_len = sizeof(bind2); TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&f, 0, sizeof(f)); memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); f.protoctx = (void *)&ssn; f.proto = IPPROTO_TCP; f.alproto = ALPROTO_DCERPC; StreamTcpInitConfig(TRUE); FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER | STREAM_START, bind1, bind1_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); DCERPCState *dcerpc_state = f.alstate; if (dcerpc_state == NULL) { printf("no dcerpc state: "); result = 0; goto end; } DCERPCUuidEntry *item = NULL; int m = 0; TAILQ_FOREACH(item, &dcerpc_state->dcerpc.dcerpcbindbindack.uuid_list, next) { printf("%d ", m); printUUID("BIND",item); m++; } FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, bind2, bind2_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); item = NULL; m = 0; TAILQ_FOREACH(item, &dcerpc_state->dcerpc.dcerpcbindbindack.uuid_list, next) { printf("%d ", m); printUUID("BIND",item); m++; } /* we will need this test later for fragged bind pdus. keep it */ result = 1; end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); StreamTcpFreeConfig(TRUE); FLOW_DESTROY(&f); return result; } /** * \test DCERPC fragmented bind PDU(one PDU which is frag'ed) */ static int DCERPCParserTest06(void) { int result = 1; Flow f; int r = 0; uint8_t bind1[] = { 0x05, 0x00, 0x0b, 0x03, 0x10, 0x00, 0x00, 0x00, 0xdc, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x16, 0xd0, 0x16, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0xc7, 0x70, 0x0d, 0x3e, 0x71, 0x37, 0x39, 0x0d, 0x3a, 0x4f, 0xd3, 0xdc, 0xca, 0x49, 0xe8, 0xa3, 0x05, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x84, 0xb6, 0x55, 0x75, 0xdb, 0x9e, 0xba, 0x54, 0x56, 0xd3, 0x45, 0x10, 0xb7, 0x7a, 0x2a, 0xe2, 0x04, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x6e, 0x39, 0x21, 0x24, 0x70, 0x6f, 0x41, 0x57, 0x54, 0x70, 0xb8, 0xc3, 0x5e, 0x89, 0x3b, 0x43, 0x03, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x39, 0x6a, 0x86, 0x5d, 0x24, 0x0f, 0xd2, 0xf7, 0xb6, 0xce, 0x95, 0x9c, 0x54, 0x1d, 0x3a, 0xdb, 0x02, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x00, 0x12, 0xa5, 0xdd, 0xc5, 0x55, 0xce, 0xc3, 0x46, 0xbd, 0xa0, 0x94, 0x39, 0x3c, 0x0d, 0x9b, 0x5b, 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x05, 0x00, 0x01, 0x00, 0x87, 0x1c, 0x8b, 0x6e, 0x11, 0xa8, 0x67, 0x98, 0xd4, 0x5d, 0xf6, 0x8a, 0x2f, 0x33, 0x24, 0x7b, 0x05, 0x00, 0x03, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x06, 0x00, 0x01, 0x00, 0x9b, 0x82, 0x13, 0xd1, 0x28, 0xe0, 0x63, 0xf3, 0x62, 0xee, 0x76, 0x73, 0xf9, 0xac, 0x3d, 0x2e, 0x03, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x07, 0x00, 0x01, 0x00, 0xa9, 0xd4, 0x73, 0xf2, 0xed, 0xad, 0xe8, 0x82, 0xf8, 0xcf, 0x9d, 0x9f, 0x66, 0xe6, 0x43, 0x37, 0x02, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00, 0x06, 0x2b, 0x85, 0x38, 0x4f, 0x73, 0x96, 0xb1, 0x73, 0xe1, 0x59, 0xbe, 0x9d, 0xe2, 0x6c, 0x07, 0x05, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60}; uint32_t bind1_len = sizeof(bind1); uint8_t bind2[] = { 0x02, 0x00, 0x00, 0x00, 0x09, 0x00, 0x01, 0x00, 0xbf, 0xfa, 0xbb, 0xa4, 0x9e, 0x5c, 0x80, 0x61, 0xb5, 0x8b, 0x79, 0x69, 0xa6, 0x32, 0x88, 0x77, 0x01, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x01, 0x00, 0x39, 0xa8, 0x2c, 0x39, 0x73, 0x50, 0x06, 0x8d, 0xf2, 0x37, 0x1e, 0x1e, 0xa8, 0x8f, 0x46, 0x98, 0x02, 0x00, 0x02, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x01, 0x00, 0x91, 0x13, 0xd0, 0xa7, 0xef, 0xc4, 0xa7, 0x96, 0x0c, 0x4a, 0x0d, 0x29, 0x80, 0xd3, 0xfe, 0xbf, 0x00, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x01, 0x00, 0xcc, 0x2b, 0x55, 0x1d, 0xd4, 0xa4, 0x0d, 0xfb, 0xcb, 0x6f, 0x86, 0x36, 0xa6, 0x57, 0xc3, 0x21, 0x02, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x01, 0x00, 0x43, 0x7b, 0x07, 0xee, 0x85, 0xa8, 0xb9, 0x3a, 0x0f, 0xf9, 0x83, 0x70, 0xe6, 0x0b, 0x4f, 0x33, 0x02, 0x00, 0x02, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x01, 0x00, 0x9c, 0x6a, 0x15, 0x8c, 0xd6, 0x9c, 0xa6, 0xc3, 0xb2, 0x9e, 0x62, 0x9f, 0x3d, 0x8e, 0x47, 0x73, 0x02, 0x00, 0x02, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x01, 0x00, 0xc8, 0x4f, 0x32, 0x4b, 0x70, 0x16, 0xd3, 0x01, 0x12, 0x78, 0x5a, 0x47, 0xbf, 0x6e, 0xe1, 0x88, 0x03, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00 }; uint32_t bind2_len = sizeof(bind2); TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&f, 0, sizeof(f)); memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); f.protoctx = (void *)&ssn; f.proto = IPPROTO_TCP; f.alproto = ALPROTO_DCERPC; StreamTcpInitConfig(TRUE); FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER | STREAM_START, bind1, bind1_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); DCERPCState *dcerpc_state = f.alstate; if (dcerpc_state == NULL) { printf("no dcerpc state: "); result = 0; goto end; } result &= (dcerpc_state->dcerpc.bytesprocessed == 420); result &= (dcerpc_state->dcerpc.dcerpcbindbindack.ctxbytesprocessed == 40); result &= (dcerpc_state->dcerpc.dcerpcbindbindack.numctxitems == 16); result &= (dcerpc_state->dcerpc.dcerpcbindbindack.numctxitemsleft == 8); FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, bind2, bind2_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); result &= (dcerpc_state->dcerpc.bytesprocessed == 0); result &= (dcerpc_state->dcerpc.dcerpcbindbindack.ctxbytesprocessed == 0); result &= (dcerpc_state->dcerpc.dcerpcbindbindack.numctxitems == 16); result &= (dcerpc_state->dcerpc.dcerpcbindbindack.numctxitemsleft == 0); end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); StreamTcpFreeConfig(TRUE); FLOW_DESTROY(&f); return result; } /** * \test DCERPC fragmented bind PDU(one PDU which is frag'ed). */ static int DCERPCParserTest07(void) { uint8_t request1[] = { 0x05, 0x00, 0x00, 0x03, 0x10, 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C }; uint32_t request1_len = sizeof(request1); uint8_t request2[] = { 0x0D, 0x0E }; uint32_t request2_len = sizeof(request2); uint8_t request3[] = { 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14 }; uint32_t request3_len = sizeof(request3); Flow f; int r = 0; TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&f, 0, sizeof(f)); memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); f.protoctx = (void *)&ssn; f.proto = IPPROTO_TCP; f.alproto = ALPROTO_DCERPC; StreamTcpInitConfig(TRUE); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER | STREAM_START, request1, request1_len); FAIL_IF(r != 0); DCERPCState *dcerpc_state = f.alstate; FAIL_IF_NULL(dcerpc_state); FAIL_IF_NOT(dcerpc_state->dcerpc.bytesprocessed == 36); FAIL_IF_NOT(dcerpc_state->dcerpc.dcerpcrequest.stub_data_buffer != NULL); FAIL_IF_NOT(dcerpc_state->dcerpc.dcerpcrequest.stub_data_buffer_len == 12); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, request2, request2_len); FAIL_IF(r != 0); FAIL_IF_NOT(dcerpc_state->dcerpc.bytesprocessed == 38); FAIL_IF_NOT(dcerpc_state->dcerpc.dcerpcrequest.stub_data_buffer != NULL); FAIL_IF_NOT(dcerpc_state->dcerpc.dcerpcrequest.stub_data_buffer_len == 14); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, request3, request3_len); FAIL_IF(r != 0); FAIL_IF_NOT(dcerpc_state->dcerpc.bytesprocessed == 0); FAIL_IF_NOT(dcerpc_state->dcerpc.dcerpcrequest.stub_data_buffer != NULL); FAIL_IF_NOT(dcerpc_state->dcerpc.dcerpcrequest.stub_data_buffer_len == 20); AppLayerParserThreadCtxFree(alp_tctx); StreamTcpFreeConfig(TRUE); FLOW_DESTROY(&f); PASS; } /** * \test DCERPC fragmented bind PDU(one PDU which is frag'ed). */ static int DCERPCParserTest08(void) { int result = 1; Flow f; int r = 0; uint8_t request[] = { 0x05, 0x02, 0x00, 0x03, 0x10, 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, }; uint32_t request_len = sizeof(request); TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&f, 0, sizeof(f)); memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); f.protoctx = (void *)&ssn; f.proto = IPPROTO_TCP; f.alproto = ALPROTO_DCERPC; StreamTcpInitConfig(TRUE); FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER | STREAM_START, request, request_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); DCERPCState *dcerpc_state = f.alstate; if (dcerpc_state == NULL) { printf("no dcerpc state: "); result = 0; goto end; } result &= (dcerpc_state->dcerpc.bytesprocessed == 0); result &= (dcerpc_state->dcerpc.dcerpcrequest.stub_data_buffer == NULL && dcerpc_state->dcerpc.dcerpcrequest.stub_data_buffer_len == 0); end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); StreamTcpFreeConfig(TRUE); FLOW_DESTROY(&f); return result; } /** * \test DCERPC fragmented bind PDU(one PDU which is frag'ed). */ static int DCERPCParserTest09(void) { int result = 1; Flow f; int r = 0; uint8_t request[] = { 0x05, 0x00, 0x00, 0x03, 0x10, 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, }; uint32_t request_len = sizeof(request); TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&f, 0, sizeof(f)); memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); f.protoctx = (void *)&ssn; f.proto = IPPROTO_TCP; f.alproto = ALPROTO_DCERPC; StreamTcpInitConfig(TRUE); FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER | STREAM_START, request, request_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); DCERPCState *dcerpc_state = f.alstate; if (dcerpc_state == NULL) { printf("no dcerpc state: "); result = 0; goto end; } result &= (dcerpc_state->dcerpc.bytesprocessed == 36); result &= (dcerpc_state->dcerpc.dcerpcrequest.stub_data_buffer != NULL && dcerpc_state->dcerpc.dcerpcrequest.stub_data_buffer_len == 12); end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); StreamTcpFreeConfig(TRUE); FLOW_DESTROY(&f); return result; } /** * \test DCERPC fragmented PDU. */ static int DCERPCParserTest10(void) { int result = 1; Flow f; int r = 0; uint8_t fault[] = { 0x05, 0x00, 0x03, 0x03, 0x10, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0xf7, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; uint32_t fault_len = sizeof(fault); uint8_t request1[] = { 0x05, 0x00 }; uint32_t request1_len = sizeof(request1); uint8_t request2[] = { 0x00, 0x03, 0x10, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C }; uint32_t request2_len = sizeof(request2); TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&f, 0, sizeof(f)); memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); f.protoctx = (void *)&ssn; f.proto = IPPROTO_TCP; f.alproto = ALPROTO_DCERPC; StreamTcpInitConfig(TRUE); FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER | STREAM_START, fault, fault_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); DCERPCState *dcerpc_state = f.alstate; if (dcerpc_state == NULL) { printf("no dcerpc state: "); result = 0; goto end; } FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, request1, request1_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); result &= (dcerpc_state->dcerpc.bytesprocessed == 2); result &= (dcerpc_state->dcerpc.dcerpcrequest.stub_data_buffer == NULL); FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, request2, request2_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); result &= (dcerpc_state->dcerpc.bytesprocessed == 0); result &= (dcerpc_state->dcerpc.dcerpcrequest.stub_data_buffer != NULL && dcerpc_state->dcerpc.dcerpcrequest.stub_data_buffer_len == 12); end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); StreamTcpFreeConfig(TRUE); FLOW_DESTROY(&f); return result; } /** * \test DCERPC fragmented PDU. */ static int DCERPCParserTest11(void) { int result = 1; Flow f; int r = 0; uint8_t request1[] = { 0x05, 0x00, 0x00, 0x03, 0x10, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C }; uint32_t request1_len = sizeof(request1); uint8_t request2[] = { 0x05, 0x00 }; uint32_t request2_len = sizeof(request2); uint8_t request3[] = { 0x00, 0x03, 0x10, 0x00, 0x00, 0x00, 0x26, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0xFF, 0xFF }; uint32_t request3_len = sizeof(request3); TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&f, 0, sizeof(f)); memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); f.protoctx = (void *)&ssn; f.proto = IPPROTO_TCP; f.alproto = ALPROTO_DCERPC; StreamTcpInitConfig(TRUE); FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, request1, request1_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); DCERPCState *dcerpc_state = f.alstate; if (dcerpc_state == NULL) { printf("no dcerpc state: "); result = 0; goto end; } result &= (dcerpc_state->dcerpc.bytesprocessed == 0); result &= (dcerpc_state->dcerpc.dcerpcrequest.stub_data_buffer != NULL && dcerpc_state->dcerpc.dcerpcrequest.stub_data_buffer_len == 12); FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, request2, request2_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); result &= (dcerpc_state->dcerpc.bytesprocessed == 2); FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, request3, request3_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); result &= (dcerpc_state->dcerpc.bytesprocessed == 0); result &= (dcerpc_state->dcerpc.dcerpcrequest.stub_data_buffer != NULL && dcerpc_state->dcerpc.dcerpcrequest.stub_data_buffer_len == 14); end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); StreamTcpFreeConfig(TRUE); FLOW_DESTROY(&f); return result; } /** * \test DCERPC fragmented PDU. */ static int DCERPCParserTest12(void) { int result = 1; Flow f; int r = 0; uint8_t bind_ack1[] = { 0x05, 0x00, 0x0c, 0x03, 0x10, 0x00, 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb8, 0x10, 0xb8, 0x10, 0x48, 0x1a, 0x00, 0x00, }; uint32_t bind_ack1_len = sizeof(bind_ack1); uint8_t bind_ack2[] = { 0x0c, 0x00, 0x5c, 0x50, 0x49, 0x50, 0x45, 0x5c, 0x6c, 0x73, 0x61, 0x73, 0x73, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00 }; uint32_t bind_ack2_len = sizeof(bind_ack2); TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&f, 0, sizeof(f)); memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); f.protoctx = (void *)&ssn; f.proto = IPPROTO_TCP; f.alproto = ALPROTO_DCERPC; StreamTcpInitConfig(TRUE); FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOCLIENT, bind_ack1, bind_ack1_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); DCERPCState *dcerpc_state = f.alstate; if (dcerpc_state == NULL) { printf("no dcerpc state: "); result = 0; goto end; } result &= (dcerpc_state->dcerpc.bytesprocessed == 24); FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOCLIENT, bind_ack2, bind_ack2_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); result &= (dcerpc_state->dcerpc.bytesprocessed == 0); end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); StreamTcpFreeConfig(TRUE); FLOW_DESTROY(&f); return result; } /** * \test Check if the parser accepts bind pdus that have context ids starting * from a non-zero value. */ static int DCERPCParserTest13(void) { int result = 1; Flow f; int r = 0; uint8_t bindbuf[] = { 0x05, 0x00, 0x0b, 0x03, 0x10, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0xd0, 0x16, 0xd0, 0x16, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xa0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00 }; uint32_t bindbuf_len = sizeof(bindbuf); TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&f, 0, sizeof(f)); memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); f.protoctx = (void *)&ssn; f.proto = IPPROTO_TCP; f.alproto = ALPROTO_DCERPC; StreamTcpInitConfig(TRUE); FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, bindbuf, bindbuf_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); DCERPCState *dcerpc_state = f.alstate; if (dcerpc_state == NULL) { printf("no dcerpc state: "); result = 0; goto end; } result &= (dcerpc_state->dcerpc.bytesprocessed == 0); result &= (dcerpc_state->dcerpc.dcerpcbindbindack.numctxitems == 1); if (result == 0) goto end; result = 0; uint8_t ctx_uuid_from_pcap[16] = { 0x00, 0x00, 0x01, 0xa0, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}; DCERPCUuidEntry *item = NULL; int internal_id = 0; TAILQ_FOREACH(item, &dcerpc_state->dcerpc.dcerpcbindbindack.uuid_list, next) { int i = 0; /* check the interface uuid */ for (i = 0; i < 16; i++) { if (ctx_uuid_from_pcap[i] != item->uuid[i]) { result = 0; goto end; } } result = 1; result &= (item->internal_id == internal_id++); } end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); StreamTcpFreeConfig(TRUE); FLOW_DESTROY(&f); return result; } /** * \test Check for another endless loop with bind pdus. */ static int DCERPCParserTest14(void) { int result = 1; Flow f; int r = 0; uint8_t bindbuf[] = { 0x05, 0x00, 0x0b, 0x03, 0x10, 0x00, 0x00, 0x00, 0x4A, 0x00, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0xd0, 0x16, 0xd0, 0x16, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xa0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0xFF /* ka boom - endless loop */ }; uint32_t bindbuf_len = sizeof(bindbuf); TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&f, 0, sizeof(f)); memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); f.protoctx = (void *)&ssn; f.proto = IPPROTO_TCP; f.alproto = ALPROTO_DCERPC; StreamTcpInitConfig(TRUE); FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, bindbuf, bindbuf_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); DCERPCState *dcerpc_state = f.alstate; if (dcerpc_state == NULL) { printf("no dcerpc state: "); result = 0; goto end; } end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); StreamTcpFreeConfig(TRUE); FLOW_DESTROY(&f); return result; } /** * \test Check for another endless loop for bind_ack pdus. */ static int DCERPCParserTest15(void) { int result = 1; Flow f; int r = 0; uint8_t bind_ack[] = { 0x05, 0x00, 0x0c, 0x03, 0x10, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0xd0, 0x16, 0xd0, 0x16, 0xfd, 0x04, 0x01, 0x00, 0x04, 0x00, 0x31, 0x33, 0x35, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x01, 0x02, 0x03, 0x04, 0xFF }; uint32_t bind_ack_len = sizeof(bind_ack); TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&f, 0, sizeof(f)); memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); f.protoctx = (void *)&ssn; f.proto = IPPROTO_TCP; f.alproto = ALPROTO_DCERPC; StreamTcpInitConfig(TRUE); FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOCLIENT, bind_ack, bind_ack_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); DCERPCState *dcerpc_state = f.alstate; if (dcerpc_state == NULL) { printf("no dcerpc state: "); result = 0; goto end; } end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); StreamTcpFreeConfig(TRUE); FLOW_DESTROY(&f); return result; } /** * \test Check for correct internal ids for bind_acks. */ static int DCERPCParserTest16(void) { int result = 1; Flow f; int r = 0; uint8_t bind1[] = { 0x05, 0x00, 0x0b, 0x03, 0x10, 0x00, 0x00, 0x00, 0x58, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x16, 0xd0, 0x16, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x50, 0x08, 0x43, 0x95, 0x43, 0x5a, 0x8b, 0xb2, 0xf4, 0xc5, 0xb9, 0xee, 0x67, 0x55, 0x7c, 0x19, 0x00, 0x00, 0x03, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xda, 0xc2, 0xbc, 0x9b, 0x35, 0x2e, 0xd4, 0xc9, 0x1f, 0x85, 0x01, 0xe6, 0x4e, 0x5a, 0x5e, 0xd4, 0x04, 0x00, 0x03, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0xb2, 0x97, 0xcc, 0x14, 0x6f, 0x70, 0x0d, 0xa5, 0x33, 0xd7, 0xf4, 0xe3, 0x8e, 0xb2, 0x2a, 0x1e, 0x05, 0x00, 0x02, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x96, 0x4e, 0xa6, 0xf6, 0xb2, 0x4b, 0xae, 0xb3, 0x21, 0xf4, 0x97, 0x7c, 0xcd, 0xa7, 0x08, 0xb0, 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x00, 0xbc, 0xc0, 0xf7, 0x71, 0x3f, 0x71, 0x54, 0x44, 0x22, 0xa8, 0x55, 0x0f, 0x98, 0x83, 0x1f, 0xfe, 0x04, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x05, 0x00, 0x01, 0x00, 0xbe, 0x52, 0xf2, 0x58, 0x4a, 0xc3, 0xb5, 0xd0, 0xba, 0xac, 0xda, 0xf0, 0x12, 0x99, 0x38, 0x6e, 0x04, 0x00, 0x02, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x06, 0x00, 0x01, 0x00, 0xdb, 0xfa, 0x73, 0x01, 0xb3, 0x81, 0x01, 0xd4, 0x7f, 0xa0, 0x36, 0xb1, 0x97, 0xae, 0x29, 0x7f, 0x01, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x07, 0x00, 0x01, 0x00, 0x89, 0xbe, 0x41, 0x1d, 0x38, 0x75, 0xf5, 0xb5, 0xad, 0x27, 0x73, 0xf1, 0xb0, 0x7a, 0x28, 0x82, 0x05, 0x00, 0x02, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00, 0xf6, 0x87, 0x09, 0x93, 0xb8, 0xa8, 0x20, 0xc4, 0xb8, 0x63, 0xe6, 0x95, 0xed, 0x59, 0xee, 0x3f, 0x05, 0x00, 0x03, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x09, 0x00, 0x01, 0x00, 0x92, 0x77, 0x92, 0x68, 0x3e, 0xa4, 0xbc, 0x3f, 0x44, 0x33, 0x0e, 0xb8, 0x33, 0x0a, 0x2f, 0xdf, 0x01, 0x00, 0x02, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x01, 0x00, 0xa1, 0x03, 0xd2, 0xa9, 0xd2, 0x16, 0xc9, 0x89, 0x67, 0x18, 0x3e, 0xb1, 0xee, 0x6b, 0xf9, 0x18, 0x02, 0x00, 0x03, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x01, 0x00, 0x2f, 0x09, 0x5e, 0x74, 0xec, 0xa0, 0xbb, 0xc1, 0x60, 0x18, 0xf1, 0x93, 0x04, 0x17, 0x11, 0xf9, 0x01, 0x00, 0x03, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x01, 0x00, 0xc8, 0x4f, 0x32, 0x4b, 0x70, 0x16, 0xd3, 0x01, 0x12, 0x78, 0x5a, 0x47, 0xbf, 0x6e, 0xe1, 0x88, 0x03, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00 }; uint32_t bind1_len = sizeof(bind1); uint8_t bind_ack1[] = { 0x05, 0x00, 0x0c, 0x03, 0x10, 0x00, 0x00, 0x00, 0x64, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb8, 0x10, 0xb8, 0x10, 0xc1, 0x2b, 0x00, 0x00, 0x0e, 0x00, 0x5c, 0x50, 0x49, 0x50, 0x45, 0x5c, 0x62, 0x72, 0x6f, 0x77, 0x73, 0x65, 0x72, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00 }; uint32_t bind_ack1_len = sizeof(bind_ack1); uint8_t bind2[] = { 0x05, 0x00, 0x0b, 0x03, 0x10, 0x00, 0x00, 0x00, 0xdc, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x16, 0xd0, 0x16, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0xc7, 0x70, 0x0d, 0x3e, 0x71, 0x37, 0x39, 0x0d, 0x3a, 0x4f, 0xd3, 0xdc, 0xca, 0x49, 0xe8, 0xa3, 0x05, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x84, 0xb6, 0x55, 0x75, 0xdb, 0x9e, 0xba, 0x54, 0x56, 0xd3, 0x45, 0x10, 0xb7, 0x7a, 0x2a, 0xe2, 0x04, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x6e, 0x39, 0x21, 0x24, 0x70, 0x6f, 0x41, 0x57, 0x54, 0x70, 0xb8, 0xc3, 0x5e, 0x89, 0x3b, 0x43, 0x03, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x39, 0x6a, 0x86, 0x5d, 0x24, 0x0f, 0xd2, 0xf7, 0xb6, 0xce, 0x95, 0x9c, 0x54, 0x1d, 0x3a, 0xdb, 0x02, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x00, 0x12, 0xa5, 0xdd, 0xc5, 0x55, 0xce, 0xc3, 0x46, 0xbd, 0xa0, 0x94, 0x39, 0x3c, 0x0d, 0x9b, 0x5b, 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x05, 0x00, 0x01, 0x00, 0x87, 0x1c, 0x8b, 0x6e, 0x11, 0xa8, 0x67, 0x98, 0xd4, 0x5d, 0xf6, 0x8a, 0x2f, 0x33, 0x24, 0x7b, 0x05, 0x00, 0x03, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x06, 0x00, 0x01, 0x00, 0x9b, 0x82, 0x13, 0xd1, 0x28, 0xe0, 0x63, 0xf3, 0x62, 0xee, 0x76, 0x73, 0xf9, 0xac, 0x3d, 0x2e, 0x03, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x07, 0x00, 0x01, 0x00, 0xa9, 0xd4, 0x73, 0xf2, 0xed, 0xad, 0xe8, 0x82, 0xf8, 0xcf, 0x9d, 0x9f, 0x66, 0xe6, 0x43, 0x37, 0x02, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00, 0x06, 0x2b, 0x85, 0x38, 0x4f, 0x73, 0x96, 0xb1, 0x73, 0xe1, 0x59, 0xbe, 0x9d, 0xe2, 0x6c, 0x07, 0x05, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x09, 0x00, 0x01, 0x00, 0xbf, 0xfa, 0xbb, 0xa4, 0x9e, 0x5c, 0x80, 0x61, 0xb5, 0x8b, 0x79, 0x69, 0xa6, 0x32, 0x88, 0x77, 0x01, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x01, 0x00, 0x39, 0xa8, 0x2c, 0x39, 0x73, 0x50, 0x06, 0x8d, 0xf2, 0x37, 0x1e, 0x1e, 0xa8, 0x8f, 0x46, 0x98, 0x02, 0x00, 0x02, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x01, 0x00, 0x91, 0x13, 0xd0, 0xa7, 0xef, 0xc4, 0xa7, 0x96, 0x0c, 0x4a, 0x0d, 0x29, 0x80, 0xd3, 0xfe, 0xbf, 0x00, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x01, 0x00, 0xcc, 0x2b, 0x55, 0x1d, 0xd4, 0xa4, 0x0d, 0xfb, 0xcb, 0x6f, 0x86, 0x36, 0xa6, 0x57, 0xc3, 0x21, 0x02, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x01, 0x00, 0x43, 0x7b, 0x07, 0xee, 0x85, 0xa8, 0xb9, 0x3a, 0x0f, 0xf9, 0x83, 0x70, 0xe6, 0x0b, 0x4f, 0x33, 0x02, 0x00, 0x02, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x01, 0x00, 0x9c, 0x6a, 0x15, 0x8c, 0xd6, 0x9c, 0xa6, 0xc3, 0xb2, 0x9e, 0x62, 0x9f, 0x3d, 0x8e, 0x47, 0x73, 0x02, 0x00, 0x02, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x01, 0x00, 0xc8, 0x4f, 0x32, 0x4b, 0x70, 0x16, 0xd3, 0x01, 0x12, 0x78, 0x5a, 0x47, 0xbf, 0x6e, 0xe1, 0x88, 0x03, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00 }; uint32_t bind2_len = sizeof(bind2); uint8_t bind_ack2[] = { 0x05, 0x00, 0x0c, 0x03, 0x10, 0x00, 0x00, 0x00, 0xac, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb8, 0x10, 0xb8, 0x10, 0xc2, 0x2b, 0x00, 0x00, 0x0e, 0x00, 0x5c, 0x50, 0x49, 0x50, 0x45, 0x5c, 0x62, 0x72, 0x6f, 0x77, 0x73, 0x65, 0x72, 0x00, 0x10, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00 }; uint32_t bind_ack2_len = sizeof(bind_ack2); uint8_t bind3[] = { 0x05, 0x00, 0x0b, 0x03, 0x10, 0x00, 0x00, 0x00, 0x2c, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x16, 0xd0, 0x16, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0xa4, 0x7f, 0x8e, 0xc6, 0xef, 0x56, 0x9b, 0x63, 0x92, 0xfa, 0x08, 0xb3, 0x35, 0xe2, 0xa5, 0x81, 0x00, 0x00, 0x03, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x9f, 0xfc, 0x78, 0xd2, 0x5f, 0x16, 0x0b, 0xbc, 0xc6, 0xdb, 0x5d, 0xef, 0xde, 0x54, 0xa2, 0x6f, 0x04, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x78, 0xb8, 0x96, 0xc7, 0x2f, 0xda, 0x11, 0x6b, 0xd1, 0x28, 0x68, 0xe1, 0xd6, 0x71, 0xac, 0x9d, 0x03, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0xcf, 0xf4, 0xd7, 0x37, 0x03, 0xda, 0xcc, 0xe3, 0x3e, 0x34, 0x7f, 0x67, 0x99, 0x91, 0x41, 0x3d, 0x01, 0x00, 0x02, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x00, 0x48, 0xeb, 0x32, 0xf0, 0x27, 0xd5, 0x9d, 0xd0, 0x1e, 0xc6, 0x48, 0x46, 0x97, 0xe9, 0xdb, 0x09, 0x05, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x05, 0x00, 0x01, 0x00, 0x82, 0xec, 0x0d, 0x08, 0xf2, 0x8f, 0x22, 0x57, 0x42, 0x9b, 0xce, 0xa8, 0x74, 0x16, 0xc6, 0xec, 0x00, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x06, 0x00, 0x01, 0x00, 0x2e, 0x00, 0x70, 0x44, 0xee, 0xc9, 0x30, 0x6b, 0xf4, 0x34, 0x1e, 0x3d, 0x35, 0x0f, 0xf7, 0xf7, 0x00, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x07, 0x00, 0x01, 0x00, 0x59, 0x04, 0x39, 0x3f, 0x59, 0x87, 0x14, 0x0e, 0x76, 0x8d, 0x17, 0xc2, 0x47, 0xfa, 0x67, 0x7f, 0x04, 0x00, 0x02, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00, 0x30, 0xd6, 0xed, 0x2e, 0x57, 0xfa, 0xf4, 0x72, 0x6c, 0x10, 0x0d, 0xe5, 0x51, 0x7f, 0xd0, 0x39, 0x02, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x09, 0x00, 0x01, 0x00, 0xea, 0x8b, 0x84, 0x4d, 0x44, 0x43, 0xc1, 0x94, 0x75, 0xe2, 0x81, 0x48, 0xd8, 0x77, 0xd9, 0xce, 0x05, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x01, 0x00, 0x89, 0x4f, 0xe7, 0x95, 0xa3, 0xc1, 0x62, 0x36, 0x26, 0x9e, 0x67, 0xdb, 0x2c, 0x52, 0x89, 0xd3, 0x01, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x01, 0x00, 0x78, 0x56, 0x34, 0x12, 0x34, 0x12, 0xcd, 0xab, 0xef, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0x01, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00 }; uint32_t bind3_len = sizeof(bind3); uint8_t bind_ack3[] = { 0x05, 0x00, 0x0c, 0x03, 0x10, 0x00, 0x00, 0x00, 0x4c, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb8, 0x10, 0xb8, 0x10, 0x1a, 0x33, 0x00, 0x00, 0x0e, 0x00, 0x5c, 0x70, 0x69, 0x70, 0x65, 0x5c, 0x73, 0x70, 0x6f, 0x6f, 0x6c, 0x73, 0x73, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00 }; uint32_t bind_ack3_len = sizeof(bind_ack3); TcpSession ssn; DCERPCUuidEntry *item = NULL; int count = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); uint8_t accepted_uuids[3][16] = { {0x4b, 0x32, 0x4f, 0xc8, 0x16, 0x70, 0x01, 0xd3, 0x12, 0x78, 0x5a, 0x47, 0xbf, 0x6e, 0xe1, 0x88}, {0x4b, 0x32, 0x4f, 0xc8, 0x16, 0x70, 0x01, 0xd3, 0x12, 0x78, 0x5a, 0x47, 0xbf, 0x6e, 0xe1, 0x88}, {0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0xab, 0xcd, 0xef, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab} }; uint16_t accepted_ctxids[3] = {12, 15, 11}; memset(&f, 0, sizeof(f)); memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); f.protoctx = (void *)&ssn; f.proto = IPPROTO_TCP; f.alproto = ALPROTO_DCERPC; StreamTcpInitConfig(TRUE); FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, bind1, bind1_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); DCERPCState *dcerpc_state = f.alstate; if (dcerpc_state == NULL) { printf("no dcerpc state: "); result = 0; goto end; } FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOCLIENT, bind_ack1, bind_ack1_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); count = 0; TAILQ_FOREACH(item, &dcerpc_state->dcerpc.dcerpcbindbindack.accepted_uuid_list, next) { int i = 0; /* check the interface uuid */ for (i = 0; i < 16; i++) { if (accepted_uuids[0][i] != item->uuid[i]) { result = 0; goto end; } } if (accepted_ctxids[0] != item->ctxid) { result = 0; goto end; } count++; } if (count != 1) { result = 0; goto end; } FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, bind2, bind2_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); count = 0; TAILQ_FOREACH(item, &dcerpc_state->dcerpc.dcerpcbindbindack.accepted_uuid_list, next) { count++; } if (count != 0) { result = 0; goto end; } FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOCLIENT, bind_ack2, bind_ack2_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); count = 0; TAILQ_FOREACH(item, &dcerpc_state->dcerpc.dcerpcbindbindack.accepted_uuid_list, next) { int i = 0; /* check the interface uuid */ for (i = 0; i < 16; i++) { if (accepted_uuids[1][i] != item->uuid[i]) { result = 0; goto end; } } if (accepted_ctxids[1] != item->ctxid) { result = 0; goto end; } count++; } if (count != 1) { result = 0; goto end; } FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, bind3, bind3_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); count = 0; TAILQ_FOREACH(item, &dcerpc_state->dcerpc.dcerpcbindbindack.accepted_uuid_list, next) { count++; } if (count != 0) { result = 0; goto end; } FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOCLIENT, bind_ack3, bind_ack3_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); count = 0; TAILQ_FOREACH(item, &dcerpc_state->dcerpc.dcerpcbindbindack.accepted_uuid_list, next) { int i = 0; /* check the interface uuid */ for (i = 0; i < 16; i++) { if (accepted_uuids[2][i] != item->uuid[i]) { result = 0; goto end; } } if (accepted_ctxids[2] != item->ctxid) { result = 0; goto end; } count++; } if (count != 1) { result = 0; goto end; } end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); StreamTcpFreeConfig(TRUE); FLOW_DESTROY(&f); return result; } /** * \test Check for correct internal ids for bind_acks + alter_contexts */ static int DCERPCParserTest17(void) { int result = 1; Flow f; int r = 0; uint8_t bindbuf[] = { 0x05, 0x00, 0x0b, 0x03, 0x10, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xd0, 0x16, 0xd0, 0x16, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x40, 0xfd, 0x2c, 0x34, 0x6c, 0x3c, 0xce, 0x11, 0xa8, 0x93, 0x08, 0x00, 0x2b, 0x2e, 0x9c, 0x6d, 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00 }; uint32_t bindbuf_len = sizeof(bindbuf); uint8_t bind_ack[] = { 0x05, 0x00, 0x0c, 0x03, 0x10, 0x00, 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xb8, 0x10, 0xb8, 0x10, 0x7d, 0xd8, 0x00, 0x00, 0x0d, 0x00, 0x5c, 0x70, 0x69, 0x70, 0x65, 0x5c, 0x6c, 0x6c, 0x73, 0x72, 0x70, 0x63, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00 }; uint32_t bind_ack_len = sizeof(bind_ack); uint8_t alter_context[] = { 0x05, 0x00, 0x0e, 0x03, 0x10, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xd0, 0x16, 0xd0, 0x16, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xd0, 0x4c, 0x67, 0x57, 0x00, 0x52, 0xce, 0x11, 0xa8, 0x97, 0x08, 0x00, 0x2b, 0x2e, 0x9c, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00 }; uint32_t alter_context_len = sizeof(alter_context); uint8_t alter_context_resp[] = { 0x05, 0x00, 0x0f, 0x03, 0x10, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xb8, 0x10, 0xb8, 0x10, 0x7d, 0xd8, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00 }; uint32_t alter_context_resp_len = sizeof(alter_context_resp); TcpSession ssn; DCERPCUuidEntry *item = NULL; int count = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); uint8_t accepted_uuids[2][16] = { {0x57, 0x67, 0x4c, 0xd0, 0x52, 0x00, 0x11, 0xce, 0xa8, 0x97, 0x08, 0x00, 0x2b, 0x2e, 0x9c, 0x6d}, {0x34, 0x2c, 0xfd, 0x40, 0x3c, 0x6c, 0x11, 0xce, 0xa8, 0x93, 0x08, 0x00, 0x2b, 0x2e, 0x9c, 0x6d}, }; uint16_t accepted_ctxids[2] = {1, 0}; memset(&f, 0, sizeof(f)); memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); f.protoctx = (void *)&ssn; f.proto = IPPROTO_TCP; f.alproto = ALPROTO_DCERPC; StreamTcpInitConfig(TRUE); FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, bindbuf, bindbuf_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); DCERPCState *dcerpc_state = f.alstate; if (dcerpc_state == NULL) { printf("no dcerpc state: "); result = 0; goto end; } FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOCLIENT, bind_ack, bind_ack_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); count = 0; TAILQ_FOREACH(item, &dcerpc_state->dcerpc.dcerpcbindbindack.accepted_uuid_list, next) { int i = 0; /* check the interface uuid */ for (i = 0; i < 16; i++) { if (accepted_uuids[1][i] != item->uuid[i]) { result = 0; goto end; } } if (accepted_ctxids[1] != item->ctxid) { result = 0; goto end; } count++; } if (count != 1) { result = 0; goto end; } FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, alter_context, alter_context_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); count = 0; TAILQ_FOREACH(item, &dcerpc_state->dcerpc.dcerpcbindbindack.accepted_uuid_list, next) { count++; } if (count != 1) { result = 0; goto end; } FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOCLIENT, alter_context_resp, alter_context_resp_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); count = 0; TAILQ_FOREACH(item, &dcerpc_state->dcerpc.dcerpcbindbindack.accepted_uuid_list, next) { int i = 0; /* check the interface uuid */ for (i = 0; i < 16; i++) { if (accepted_uuids[count][i] != item->uuid[i]) { result = 0; goto end; } } if (accepted_ctxids[count] != item->ctxid) { result = 0; goto end; } count++; } if (count != 2) { result = 0; goto end; } end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); StreamTcpFreeConfig(TRUE); FLOW_DESTROY(&f); return result; } /** * \test DCERPC fragmented PDU. */ static int DCERPCParserTest18(void) { int result = 1; Flow f; int r = 0; uint8_t request1[] = { 0x05, 0x00, 0x00, 0x03, 0x10, 0x00, 0x00, 0x00, 0x26, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x00, }; uint32_t request1_len = sizeof(request1); uint8_t request2[] = { 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0xFF, 0xFF }; uint32_t request2_len = sizeof(request2); TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&f, 0, sizeof(f)); memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); f.protoctx = (void *)&ssn; f.proto = IPPROTO_TCP; f.alproto = ALPROTO_DCERPC; StreamTcpInitConfig(TRUE); FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, request1, request1_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); DCERPCState *dcerpc_state = f.alstate; if (dcerpc_state == NULL) { printf("no dcerpc state: "); result = 0; goto end; } result &= (dcerpc_state->dcerpc.bytesprocessed == 18); result &= (dcerpc_state->dcerpc.dcerpcrequest.stub_data_buffer == NULL); FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, request2, request2_len); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); result = 0; FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); result &= (dcerpc_state->dcerpc.bytesprocessed == 0); result &= (dcerpc_state->dcerpc.dcerpcrequest.stub_data_buffer != NULL && dcerpc_state->dcerpc.dcerpcrequest.stub_data_buffer_len == 14); result &= (dcerpc_state->dcerpc.dcerpcrequest.opnum == 2); end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); StreamTcpFreeConfig(TRUE); FLOW_DESTROY(&f); return result; } static int DCERPCParserTest19(void) { int result = 0; Flow f; uint8_t dcerpcbind[] = { 0x05, 0x00, 0x0b, 0x03, 0x10, 0x00, 0x00, 0x00, 0x3c, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x16, 0xd0, 0x16, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x2c, 0xd0, 0x28, 0xda, 0x76, 0x91, 0xf6, 0x6e, 0xcb, 0x0f, 0xbf, 0x85, 0xcd, 0x9b, 0xf6, 0x39, 0x01, 0x00, 0x03, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x2c, 0x75, 0xce, 0x7e, 0x82, 0x3b, 0x06, 0xac, 0x1b, 0xf0, 0xf5, 0xb7, 0xa7, 0xf7, 0x28, 0xaf, 0x05, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0xe3, 0xb2, 0x10, 0xd1, 0xd0, 0x0c, 0xcc, 0x3d, 0x2f, 0x80, 0x20, 0x7c, 0xef, 0xe7, 0x09, 0xe0, 0x04, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0xde, 0x85, 0x70, 0xc4, 0x02, 0x7c, 0x60, 0x23, 0x67, 0x0c, 0x22, 0xbf, 0x18, 0x36, 0x79, 0x17, 0x01, 0x00, 0x02, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x00, 0x41, 0x65, 0x29, 0x51, 0xaa, 0xe7, 0x7b, 0xa8, 0xf2, 0x37, 0x0b, 0xd0, 0x3f, 0xb3, 0x36, 0xed, 0x05, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x05, 0x00, 0x01, 0x00, 0x14, 0x96, 0x80, 0x01, 0x2e, 0x78, 0xfb, 0x5d, 0xb4, 0x3c, 0x14, 0xb3, 0x3d, 0xaa, 0x02, 0xfb, 0x06, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x06, 0x00, 0x01, 0x00, 0x3b, 0x04, 0x68, 0x3e, 0x63, 0xfe, 0x9f, 0xd8, 0x64, 0x55, 0xcd, 0xe7, 0x39, 0xaf, 0x98, 0x9f, 0x03, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x07, 0x00, 0x01, 0x00, 0x16, 0x7a, 0x4f, 0x1b, 0xdb, 0x25, 0x92, 0x55, 0xdd, 0xae, 0x9e, 0x5b, 0x3e, 0x93, 0x66, 0x93, 0x04, 0x00, 0x01, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, 0x01, 0x00, 0xe8, 0xa4, 0x8a, 0xcf, 0x95, 0x6c, 0xc7, 0x8f, 0x14, 0xcc, 0x56, 0xfc, 0x7b, 0x5f, 0x4f, 0xe8, 0x04, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x09, 0x00, 0x01, 0x00, 0xd8, 0xda, 0xfb, 0xbc, 0xa2, 0x55, 0x6f, 0x5d, 0xc0, 0x2d, 0x88, 0x6f, 0x00, 0x17, 0x52, 0x8d, 0x06, 0x00, 0x03, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x01, 0x00, 0x3f, 0x17, 0x55, 0x0c, 0xf4, 0x23, 0x3c, 0xca, 0xe6, 0xa0, 0xaa, 0xcc, 0xb5, 0xe3, 0xf9, 0xce, 0x04, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x01, 0x00, 0x6a, 0x28, 0x19, 0x39, 0x0c, 0xb1, 0xd0, 0x11, 0x9b, 0xa8, 0x00, 0xc0, 0x4f, 0xd9, 0x2e, 0xf5, 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x01, 0x00, 0xc9, 0x9f, 0x3e, 0x6e, 0x82, 0x0a, 0x2b, 0x28, 0x37, 0x78, 0xe1, 0x13, 0x70, 0x05, 0x38, 0x4d, 0x01, 0x00, 0x02, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x01, 0x00, 0x11, 0xaa, 0x4b, 0x15, 0xdf, 0xa6, 0x86, 0x3f, 0xfb, 0xe0, 0x09, 0xb7, 0xf8, 0x56, 0xd2, 0x3f, 0x05, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x01, 0x00, 0xee, 0x99, 0xc4, 0x25, 0x11, 0xe4, 0x95, 0x62, 0x29, 0xfa, 0xfd, 0x26, 0x57, 0x02, 0xf1, 0xce, 0x03, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x01, 0x00, 0xba, 0x81, 0x9e, 0x1a, 0xdf, 0x2b, 0xba, 0xe4, 0xd3, 0x17, 0x41, 0x60, 0x6d, 0x2d, 0x9e, 0x28, 0x03, 0x00, 0x03, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x10, 0x00, 0x01, 0x00, 0xa0, 0x24, 0x03, 0x9a, 0xa9, 0x99, 0xfb, 0xbe, 0x49, 0x11, 0xad, 0x77, 0x30, 0xaa, 0xbc, 0xb6, 0x02, 0x00, 0x03, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x11, 0x00, 0x01, 0x00, 0x32, 0x04, 0x7e, 0xae, 0xec, 0x28, 0xd1, 0x55, 0x83, 0x4e, 0xc3, 0x47, 0x5d, 0x1d, 0xc6, 0x65, 0x02, 0x00, 0x03, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x12, 0x00, 0x01, 0x00, 0xc6, 0xa4, 0x81, 0x48, 0x66, 0x2a, 0x74, 0x7d, 0x56, 0x6e, 0xc5, 0x1d, 0x19, 0xf2, 0xb5, 0xb6, 0x03, 0x00, 0x02, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x13, 0x00, 0x01, 0x00, 0xcb, 0xae, 0xb3, 0xc0, 0x0c, 0xf4, 0xa4, 0x5e, 0x91, 0x72, 0xdd, 0x53, 0x24, 0x70, 0x89, 0x02, 0x05, 0x00, 0x03, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x14, 0x00, 0x01, 0x00, 0xb8, 0xd0, 0xa0, 0x1a, 0x5e, 0x7a, 0x2d, 0xfe, 0x35, 0xc6, 0x7d, 0x08, 0x0d, 0x33, 0x73, 0x18, 0x02, 0x00, 0x02, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, }; uint8_t dcerpcbindack[] = { 0x05, 0x00, 0x0c, 0x03, 0x10, 0x00, 0x00, 0x00, 0x6c, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb8, 0x10, 0xb8, 0x10, 0xce, 0x47, 0x00, 0x00, 0x0c, 0x00, 0x5c, 0x50, 0x49, 0x50, 0x45, 0x5c, 0x6c, 0x73, 0x61, 0x73, 0x73, 0x00, 0xf6, 0x6e, 0x18, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x5d, 0x88, 0x8a, 0xeb, 0x1c, 0xc9, 0x11, 0x9f, 0xe8, 0x08, 0x00, 0x2b, 0x10, 0x48, 0x60, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; uint32_t bindlen = sizeof(dcerpcbind); uint32_t bindacklen = sizeof(dcerpcbindack); TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&f, 0, sizeof(f)); memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); f.protoctx = (void *)&ssn; f.proto = IPPROTO_TCP; f.alproto = ALPROTO_DCERPC; StreamTcpInitConfig(TRUE); FLOWLOCK_WRLOCK(&f); int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER | STREAM_START, dcerpcbind, bindlen); if (r != 0) { printf("dcerpc header check returned %" PRId32 ", expected 0: ", r); FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); DCERPCState *dcerpc_state = f.alstate; if (dcerpc_state == NULL) { printf("no dcerpc state: "); goto end; } if (dcerpc_state->dcerpc.bytesprocessed == 0) { printf("request - dce parser bytesprocessed should not be 0.\n"); goto end; } FLOWLOCK_WRLOCK(&f); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOCLIENT, dcerpcbindack, bindacklen); if (r == 0) { printf("dce parser didn't return fail\n"); FLOWLOCK_UNLOCK(&f); goto end; } FLOWLOCK_UNLOCK(&f); result = 1; end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); StreamTcpFreeConfig(TRUE); FLOW_DESTROY(&f); return result; } #endif /* UNITTESTS */ void DCERPCParserRegisterTests(void) { #ifdef UNITTESTS UtRegisterTest("DCERPCParserTest01", DCERPCParserTest01); UtRegisterTest("DCERPCParserTest02", DCERPCParserTest02); UtRegisterTest("DCERPCParserTest03", DCERPCParserTest03); UtRegisterTest("DCERPCParserTest05", DCERPCParserTest05); UtRegisterTest("DCERPCParserTest06", DCERPCParserTest06); UtRegisterTest("DCERPCParserTest07", DCERPCParserTest07); UtRegisterTest("DCERPCParserTest08", DCERPCParserTest08); UtRegisterTest("DCERPCParserTest09", DCERPCParserTest09); UtRegisterTest("DCERPCParserTest10", DCERPCParserTest10); UtRegisterTest("DCERPCParserTest11", DCERPCParserTest11); UtRegisterTest("DCERPCParserTest12", DCERPCParserTest12); UtRegisterTest("DCERPCParserTest13", DCERPCParserTest13); UtRegisterTest("DCERPCParserTest14", DCERPCParserTest14); UtRegisterTest("DCERPCParserTest15", DCERPCParserTest15); UtRegisterTest("DCERPCParserTest16", DCERPCParserTest16); UtRegisterTest("DCERPCParserTest17", DCERPCParserTest17); UtRegisterTest("DCERPCParserTest18", DCERPCParserTest18); UtRegisterTest("DCERPCParserTest19", DCERPCParserTest19); #endif /* UNITTESTS */ return; }
<reponame>souxinzn/SXOpenSDK // // DeviceControlCallback.h // SXIotSDK // // Created by ShimLin on 2019/8/9. // #import <Foundation/Foundation.h> #import "UdpClientCallBack.h" #import "UdpClientBack.h" NS_ASSUME_NONNULL_BEGIN @interface DeviceControlCallback : NSObject<UdpClientCallBack> typedef void(^ DEV_CTRL_CALLBACK)(UdpClientBack* udpClientBack); @property(atomic, copy) DEV_CTRL_CALLBACK callback; - (instancetype)initByCallback:(DEV_CTRL_CALLBACK)callback; @end NS_ASSUME_NONNULL_END
/* * (C) Copyright 2010 * MediaTek <www.MediaTek.com> * * Android Exception Device * */ #include <linux/cdev.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/fs.h> #include <linux/hardirq.h> #include <linux/init.h> #include <linux/kallsyms.h> #include <linux/miscdevice.h> #include <linux/module.h> #include <linux/poll.h> #include <linux/proc_fs.h> #include <linux/wait.h> #include <linux/sched.h> #include <linux/vmalloc.h> #include <disp_assert_layer.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <linux/semaphore.h> #include <linux/workqueue.h> #include <linux/kthread.h> #include <mt-plat/aee.h> #include <linux/seq_file.h> #include "aed.h" #include <linux/pid.h> #include <mt-plat/mt_boot_common.h> static DEFINE_SPINLOCK(pwk_hang_lock); static int wdt_kick_status; static int hwt_kick_times; static int pwk_start_monitor; #define AEEIOCTL_RT_MON_Kick _IOR('p', 0x0A, int) /****************************************************************************** * FUNCTION PROTOTYPES *****************************************************************************/ static long monitor_hang_ioctl(struct file *file, unsigned int cmd, unsigned long arg); /****************************************************************************** * hang detect File operations *****************************************************************************/ static int monitor_hang_open(struct inode *inode, struct file *filp) { /* LOGD("%s\n", __func__); */ /* aee_kernel_RT_Monitor_api (600) ; */ return 0; } static int monitor_hang_release(struct inode *inode, struct file *filp) { /* LOGD("%s\n", __func__); */ return 0; } static unsigned int monitor_hang_poll(struct file *file, struct poll_table_struct *ptable) { /* LOGD("%s\n", __func__); */ return 0; } static ssize_t monitor_hang_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos) { /* LOGD("%s\n", __func__); */ return 0; } static ssize_t monitor_hang_write(struct file *filp, const char __user *buf, size_t count, loff_t *f_pos) { /* LOGD("%s\n", __func__); */ return 0; } /* QHQ RT Monitor */ /* QHQ RT Monitor end */ /* * aed process daemon and other command line may access me * concurrently */ static long monitor_hang_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { int ret = 0; static long long monitor_status; if (cmd == AEEIOCTL_WDT_KICK_POWERKEY) { if ((int)arg == WDT_SETBY_WMS_DISABLE_PWK_MONITOR) { /* pwk_start_monitor=0; */ /* wdt_kick_status=0; */ /* hwt_kick_times=0; */ } else if ((int)arg == WDT_SETBY_WMS_ENABLE_PWK_MONITOR) { /* pwk_start_monitor=1; */ /* wdt_kick_status=0; */ /* hwt_kick_times=0; */ } else if ((int)arg < 0xf) { aee_kernel_wdt_kick_Powkey_api("Powerkey ioctl", (int)arg); } return ret; } /* QHQ RT Monitor */ if (cmd == AEEIOCTL_RT_MON_Kick) { LOGE("AEEIOCTL_RT_MON_Kick ( %d)\n", (int)arg); aee_kernel_RT_Monitor_api((int)arg); return ret; } /* LOGE("AEEIOCTL_RT_MON_Kick unknown cmd :(%d)( %d)\n",(int)cmd, (int)arg); */ /* LOGE("AEEIOCTL_RT_MON_Kick known cmd :(%d)( %d)\n", (int)AEEIOCTL_WDT_KICK_POWERKEY, (int)AEEIOCTL_RT_MON_Kick); */ /* QHQ RT Monitor end */ if (cmd == AEEIOCTL_SET_SF_STATE) { if (copy_from_user(&monitor_status, (void __user *)arg, sizeof(long long))) ret = -1; LOGE("AEE_MONITOR_SET[status]: 0x%llx", monitor_status); return ret; } else if (cmd == AEEIOCTL_GET_SF_STATE) { if (copy_to_user((void __user *)arg, &monitor_status, sizeof(long long))) ret = -1; return ret; } return -1; } /* QHQ RT Monitor */ static const struct file_operations aed_wdt_RT_Monitor_fops = { .owner = THIS_MODULE, .open = monitor_hang_open, .release = monitor_hang_release, .poll = monitor_hang_poll, .read = monitor_hang_read, .write = monitor_hang_write, .unlocked_ioctl = monitor_hang_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = monitor_hang_ioctl, #endif }; static struct miscdevice aed_wdt_RT_Monitor_dev = { .minor = MISC_DYNAMIC_MINOR, .name = "RT_Monitor", .fops = &aed_wdt_RT_Monitor_fops, }; /* bleow code is added for monitor_hang_init */ static int monitor_hang_init(void); static int hang_detect_init(void); /* bleow code is added for hang detect */ static int __init monitor_hang_init(void) { int err = 0; /* bleow code is added by QHQ for hang detect */ err = misc_register(&aed_wdt_RT_Monitor_dev); if (unlikely(err)) { LOGE("aee: failed to register aed_wdt_RT_Monitor_dev device!\n"); return err; } hang_detect_init(); /* bleow code is added by QHQ for hang detect */ /* end */ return err; } static void __exit monitor_hang_exit(void) { int err; err = misc_deregister(&aed_wdt_RT_Monitor_dev); if (unlikely(err)) LOGE("failed to unregister RT_Monitor device!\n"); } /* bleow code is added by QHQ for hang detect */ /* For the condition, where kernel is still alive, but system server is not scheduled. */ #define HD_PROC "hang_detect" /* static DEFINE_SPINLOCK(hd_locked_up); */ #define HD_INTER 30 static int hd_detect_enabled; static int hd_timeout = 0x7fffffff; static int hang_detect_counter = 0x7fffffff; int InDumpAllStack = 0; static int system_server_pid; static int surfaceflinger_pid; static int system_ui_pid; static int init_pid; static int mmcqd0; static int mmcqd1; static int debuggerd; static int debuggerd64; static int FindTaskByName(char *name) { struct task_struct *task; int ret = -1; system_server_pid = 0; surfaceflinger_pid = 0; system_ui_pid = 0; init_pid = 0; mmcqd0 = 0; mmcqd1 = 0; debuggerd = 0; debuggerd64 = 0; read_lock(&tasklist_lock); for_each_process(task) { if (task && (strcmp(task->comm, "init") == 0)) { init_pid = task->pid; LOGE("[Hang_Detect] %s found pid:%d.\n", task->comm, task->pid); } else if (task && (strcmp(task->comm, "mmcqd/0") == 0)) { mmcqd0 = task->pid; LOGE("[Hang_Detect] %s found pid:%d.\n", task->comm, task->pid); } else if (task && (strcmp(task->comm, "mmcqd/1") == 0)) { mmcqd1 = task->pid; LOGE("[Hang_Detect] %s found pid:%d.\n", task->comm, task->pid); } else if (task && (strcmp(task->comm, "surfaceflinger") == 0)) { surfaceflinger_pid = task->pid; LOGE("[Hang_Detect] %s found pid:%d.\n", task->comm, task->pid); } else if (task && (strcmp(task->comm, "debuggerd") == 0)) { debuggerd = task->pid; LOGE("[Hang_Detect] %s found pid:%d.\n", task->comm, task->pid); } else if (task && (strcmp(task->comm, "debuggerd64") == 0)) { debuggerd64 = task->pid; LOGE("[Hang_Detect] %s found pid:%d.\n", task->comm, task->pid); } else if (task && (strcmp(task->comm, name) == 0)) { system_server_pid = task->pid; LOGE("[Hang_Detect] %s found pid:%d.\n", task->comm, task->pid); /* return task->pid; */ } else if (task && (strstr(task->comm, "systemui"))) { system_ui_pid = task->pid; LOGE("[Hang_Detect] %s found pid:%d.\n", task->comm, task->pid); /* return system_server_pid; //for_each_process list by pid */ } } read_unlock(&tasklist_lock); if (system_server_pid) ret = system_server_pid; else { LOGE("[Hang_Detect] system_server not found!\n"); ret = -1; } return ret; } void sched_show_task_local(struct task_struct *p) { unsigned long free = 0; int ppid; unsigned state; char stat_nam[] = TASK_STATE_TO_CHAR_STR; state = p->state ? __ffs(p->state) + 1 : 0; LOGE("%-15.15s %c", p->comm, state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?'); #if BITS_PER_LONG == 32 if (state == TASK_RUNNING) LOGE(" running "); else LOGE(" %08lx ", thread_saved_pc(p)); #else if (state == TASK_RUNNING) LOGE(" running task "); else LOGE(" %016lx ", thread_saved_pc(p)); #endif #ifdef CONFIG_DEBUG_STACK_USAGE free = stack_not_used(p); #endif rcu_read_lock(); ppid = task_pid_nr(rcu_dereference(p->real_parent)); rcu_read_unlock(); LOGE("%5lu %5d %6d 0x%08lx\n", free, task_pid_nr(p), ppid, (unsigned long)task_thread_info(p)->flags); print_worker_info("6", p); show_stack(p, NULL); } void show_state_filter_local(unsigned long state_filter) { struct task_struct *g, *p; #if BITS_PER_LONG == 32 LOGE(" task PC stack pid father\n"); #else LOGE(" task PC stack pid father\n"); #endif do_each_thread(g, p) { /* * reset the NMI-timeout, listing all files on a slow * console might take a lot of time: *discard wdtk-* for it always stay in D state */ if ((!state_filter || (p->state & state_filter)) && !strstr(p->comm, "wdtk")) sched_show_task_local(p); } while_each_thread(g, p); } static void show_bt_by_pid(int task_pid) { struct task_struct *t, *p; struct pid *pid; int count = 0; pid = find_get_pid(task_pid); t = p = get_pid_task(pid, PIDTYPE_PID); count = 0; if (NULL != p) { do { if (t) sched_show_task_local(t); if ((++count)%5 == 4) msleep(20); } while_each_thread(p, t); put_task_struct(t); } put_pid(pid); } static void ShowStatus(void) { InDumpAllStack = 1; LOGE("[Hang_Detect] dump system_ui all thread bt\n"); if (system_ui_pid) show_bt_by_pid(system_ui_pid); /* show all kbt in surfaceflinger */ LOGE("[Hang_Detect] dump surfaceflinger all thread bt\n"); if (surfaceflinger_pid) show_bt_by_pid(surfaceflinger_pid); /* show all kbt in system_server */ LOGE("[Hang_Detect] dump system_server all thread bt\n"); if (system_server_pid) show_bt_by_pid(system_server_pid); /* show all D state thread kbt */ LOGE("[Hang_Detect] dump all D thread bt\n"); show_state_filter_local(TASK_UNINTERRUPTIBLE); /* show all kbt in init */ LOGE("[Hang_Detect] dump init all thread bt\n"); if (init_pid) show_bt_by_pid(init_pid); /* show all kbt in mmcqd/0 */ LOGE("[Hang_Detect] dump mmcqd/0 all thread bt\n"); if (mmcqd0) show_bt_by_pid(mmcqd0); /* show all kbt in mmcqd/1 */ LOGE("[Hang_Detect] dump mmcqd/1 all thread bt\n"); if (mmcqd1) show_bt_by_pid(mmcqd1); LOGE("[Hang_Detect] dump debug_show_all_locks\n"); debug_show_all_locks(); LOGE("[Hang_Detect] show_free_areas\n"); show_free_areas(0); system_server_pid = 0; surfaceflinger_pid = 0; system_ui_pid = 0; init_pid = 0; InDumpAllStack = 0; mmcqd0 = 0; mmcqd1 = 0; debuggerd = 0; debuggerd64 = 0; } static int hang_detect_thread(void *arg) { /* unsigned long flags; */ struct sched_param param = { .sched_priority = 99 }; LOGE("[Hang_Detect] hang_detect thread starts.\n"); sched_setscheduler(current, SCHED_FIFO, &param); while (1) { if ((1 == hd_detect_enabled) && (FindTaskByName("system_server") != -1)) { LOGE("[Hang_Detect] hang_detect thread counts down %d:%d.\n", hang_detect_counter, hd_timeout); if (hang_detect_counter <= 0) ShowStatus(); if (hang_detect_counter == 0) { LOGE("[Hang_Detect] we should triger HWT ...\n"); if (aee_mode != AEE_MODE_CUSTOMER_USER) { aee_kernel_warning_api (__FILE__, __LINE__, DB_OPT_NE_JBT_TRACES | DB_OPT_DISPLAY_HANG_DUMP, "\nCRDISPATCH_KEY:SS Hang\n", "we triger HWT "); msleep(30 * 1000); } else { /* only Customer user load trigger HWT */ aee_kernel_exception_api(__FILE__, __LINE__, DB_OPT_NE_JBT_TRACES | DB_OPT_DISPLAY_HANG_DUMP, "\nCRDISPATCH_KEY:SS Hang\n", "we triger HWT "); msleep(30 * 1000); local_irq_disable(); while (1) ; BUG(); } } hang_detect_counter--; } else { /* incase of system_server restart, we give 2 mins more.(4*HD_INTER) */ if (1 == hd_detect_enabled) { hang_detect_counter = hd_timeout + 4; hd_detect_enabled = 0; } LOGE("[Hang_Detect] hang_detect disabled.\n"); } msleep((HD_INTER) * 1000); } return 0; } void hd_test(void) { hang_detect_counter = 0; hd_timeout = 0; } void aee_kernel_RT_Monitor_api(int lParam) { if (0 == lParam) { hd_detect_enabled = 0; hang_detect_counter = hd_timeout; LOGE("[Hang_Detect] hang_detect disabled\n"); } else if (lParam > 0) { /* lParem=0x1000|timeout,only set in aee call when NE in system_server * so only change hang_detect_counter when call from AEE * Others ioctl, will change hd_detect_enabled & hang_detect_counter */ if (lParam & 0x1000) { hang_detect_counter = hd_timeout = ((long)(lParam & 0x0fff) + HD_INTER - 1) / (HD_INTER); } else { hd_detect_enabled = 1; hang_detect_counter = hd_timeout = ((long)lParam + HD_INTER - 1) / (HD_INTER); } LOGE("[Hang_Detect] hang_detect enabled %d\n", hd_timeout); } } #if 0 static int hd_proc_cmd_read(char *buf, char **start, off_t offset, int count, int *eof, void *data) { /* with a read of the /proc/hang_detect, we reset the counter. */ int len = 0; LOGE("[Hang_Detect] read proc %d\n", count); len = sprintf(buf, "%d:%d\n", hang_detect_counter, hd_timeout); hang_detect_counter = hd_timeout; return len; } static int hd_proc_cmd_write(struct file *file, const char *buf, unsigned long count, void *data) { /* with a write function , we set the time out, in seconds. */ /* with a '0' argument, we set it to max int */ /* with negative number, we will triger a timeout, or for extension functions (future use) */ int counter = 0; int retval = 0; retval = sscanf(buf, "%d ", &counter); if (retval == 0) LOGE("can not identify counter!\n"); LOGE("[Hang_Detect] write proc %d, original %d: %d\n", counter, hang_detect_counter, hd_timeout); if (counter > 0) { if (counter % HD_INTER != 0) hd_timeout = 1; else hd_timeout = 0; counter = counter / HD_INTER; hd_timeout += counter; } else if (counter == 0) hd_timeout = 0x7fffffff; else if (counter == -1) hd_test(); else return count; hang_detect_counter = hd_timeout; return count; } #endif int hang_detect_init(void) { struct task_struct *hd_thread; /* struct proc_dir_entry *de = create_proc_entry(HD_PROC, 0664, 0); */ unsigned char *name = "hang_detect"; LOGD("[Hang_Detect] Initialize proc\n"); /* de->read_proc = hd_proc_cmd_read; */ /* de->write_proc = hd_proc_cmd_write; */ LOGD("[Hang_Detect] create hang_detect thread\n"); hd_thread = kthread_create (hang_detect_thread, NULL, name); wake_up_process(hd_thread); return 0; } /* added by QHQ for hang detect */ /* end */ int aee_kernel_Powerkey_is_press(void) { int ret = 0; ret = pwk_start_monitor; return ret; } EXPORT_SYMBOL(aee_kernel_Powerkey_is_press); void aee_kernel_wdt_kick_Powkey_api(const char *module, int msg) { spin_lock(&pwk_hang_lock); wdt_kick_status |= msg; spin_unlock(&pwk_hang_lock); if (pwk_start_monitor) LOGE("powerkey_kick:%s:%x,%x\r", module, msg, wdt_kick_status); } EXPORT_SYMBOL (aee_kernel_wdt_kick_Powkey_api); void aee_powerkey_notify_press(unsigned long pressed) { if (pressed) { /* pwk down or up ???? need to check */ wdt_kick_status = 0; hwt_kick_times = 0; pwk_start_monitor = 1; LOGE("(%s) HW keycode powerkey\n", pressed ? "pressed" : "released"); } } EXPORT_SYMBOL(aee_powerkey_notify_press); int aee_kernel_wdt_kick_api(int kinterval) { int ret = 0; if (pwk_start_monitor && (get_boot_mode() == NORMAL_BOOT) && (FindTaskByName("system_server") != -1)) { /* Only in normal_boot! */ LOGE("Press powerkey!! g_boot_mode=%d,wdt_kick_status=0x%x,tickTimes=0x%x,g_kinterval=%d,RT[%lld]\n", get_boot_mode(), wdt_kick_status, hwt_kick_times, kinterval, sched_clock()); hwt_kick_times++; if ((kinterval * hwt_kick_times > 180)) { /* only monitor 3 min */ pwk_start_monitor = 0; /* check all modules is ok~~~ */ if ((wdt_kick_status & (WDT_SETBY_Display | WDT_SETBY_SF)) != (WDT_SETBY_Display | WDT_SETBY_SF)) { if (aee_mode != AEE_MODE_CUSTOMER_USER) { /* disable for display not ready */ /* ShowStatus(); catch task kernel bt */ /* LOGE("[WDK] Powerkey Tick fail,kick_status 0x%08x,RT[%lld]\n ", */ /* wdt_kick_status, sched_clock()); */ /* aee_kernel_warning_api(__FILE__, __LINE__, DB_OPT_NE_JBT_TRACES|DB_OPT_DISPLAY_HANG_DUMP, "\nCRDISPATCH_KEY:<NAME>(Powerkey)\n", */ /* "Powerkey Monitor"); */ /* msleep(30 * 1000); */ } else { /* ShowStatus(); catch task kernel bt */ /* LOGE("[WDK] Powerkey Tick fail,kick_status 0x%08x,RT[%lld]\n ", */ /* wdt_kick_status, sched_clock()); */ /* aee_kernel_exception_api(__FILE__, __LINE__, DB_OPT_NE_JBT_TRACES|DB_OPT_DISPLAY_HANG_DUMP, "\nCRDISPATCH_KEY:<NAME>(Powerkey)\n", */ /* "Powerkey Monitor"); */ /* msleep(30 * 1000); */ /* ret = WDT_PWK_HANG_FORCE_HWT; trigger HWT */ } } } if ((wdt_kick_status & (WDT_SETBY_Display | WDT_SETBY_SF)) == (WDT_SETBY_Display | WDT_SETBY_SF)) { pwk_start_monitor = 0; LOGE("[WDK] Powerkey Tick ok,kick_status 0x%08x,RT[%lld]\n ", wdt_kick_status, sched_clock()); } } return ret; } EXPORT_SYMBOL(aee_kernel_wdt_kick_api); module_init(monitor_hang_init); module_exit(monitor_hang_exit); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("MediaTek AED Driver"); MODULE_AUTHOR("MediaTek Inc.");
<gh_stars>100-1000 #define cmplx_spPrefix #include "spfactor.c"
<gh_stars>100-1000 /***************************************************************************** * * * OpenNI 2.x Alpha * * Copyright (C) 2012 PrimeSense Ltd. * * * * This file is part of OpenNI. * * * * 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 _ONI_IMPL_DEVICE_H_ #define _ONI_IMPL_DEVICE_H_ #include "OniDriverHandler.h" #include "OniFrameManager.h" #include "OniSensor.h" #include "OniCommon.h" #include "XnList.h" ONI_NAMESPACE_IMPLEMENTATION_BEGIN class Context; class VideoStream; class Sensor; class DeviceDriver; class Device { public: Device(DeviceDriver* pDeviceDriver, const DriverHandler& libraryHandler, FrameManager& frameManager, const OniDeviceInfo* pDeviceInfo, xnl::ErrorLogger& errorLogger); ~Device(); OniStatus open(const char* mode); OniStatus close(); OniStatus getSensorInfoList(OniSensorInfo** pSensors, int& numSensors); const OniDeviceInfo* getInfo() const; VideoStream* createStream(OniSensorType sensorType); OniStatus setProperty(int propertyId, const void* data, int dataSize); OniStatus getProperty(int propertyId, void* data, int* pDataSize); OniBool isPropertySupported(int propertId); void notifyAllProperties(); OniStatus invoke(int commandId, void* data, int dataSize); OniBool isCommandSupported(int commandId); void* getHandle() const {return m_deviceHandle;} DeviceDriver* getDeviceDriver() {return m_pDeviceDriver; } OniBool isImageRegistrationModeSupported(OniImageRegistrationMode mode); OniStatus tryManualTrigger(); void clearStream(VideoStream* pStream); OniStatus enableDepthColorSync(Context* pContext); void disableDepthColorSync(); OniBool isDepthColorSyncEnabled(); void refreshDepthColorSyncState(); private: typedef struct { int frameId; void* pStream; } Seek; Device(const Device& other); Device& operator=(const Device& other); static void ONI_CALLBACK_TYPE stream_PropertyChanged(void* deviceHandle, int propertyId, const void* data, int dataSize, void* pCookie); const DriverHandler& m_driverHandler; FrameManager& m_frameManager; xnl::ErrorLogger& m_errorLogger; OniDeviceInfo* m_pInfo; bool m_active; int m_openCount; void* m_deviceHandle; DeviceDriver* m_pDeviceDriver; xnl::List<VideoStream*> m_streams; xnl::CriticalSection m_cs; OniFrameSyncHandle m_depthColorSyncHandle; Context* m_pContext; OniBool m_syncEnabled; enum { MAX_SENSORS_PER_DEVICE = 10 }; Sensor* m_sensors[MAX_SENSORS_PER_DEVICE]; }; ONI_NAMESPACE_IMPLEMENTATION_END #endif // _ONI_IMP_DEVICE_H_
<reponame>mit-tens/qik #include <stdbool.h> #include <math.h> #include <SDL2/SDL.h> #include <libconfig.h> #include "types.h" #include "global.h" #include "common.h" #include "control.h" typedef struct Key Key; struct Key { char *t; SDL_Scancode s; }; static Key Keylist[] = { {"A", SDL_SCANCODE_A}, {"B", SDL_SCANCODE_B}, {"C", SDL_SCANCODE_C}, {"D", SDL_SCANCODE_D}, {"E", SDL_SCANCODE_E}, {"F", SDL_SCANCODE_F}, {"G", SDL_SCANCODE_G}, {"H", SDL_SCANCODE_H}, {"I", SDL_SCANCODE_I}, {"J", SDL_SCANCODE_J}, {"K", SDL_SCANCODE_K}, {"L", SDL_SCANCODE_L}, {"M", SDL_SCANCODE_M}, {"N", SDL_SCANCODE_N}, {"O", SDL_SCANCODE_O}, {"P", SDL_SCANCODE_P}, {"Q", SDL_SCANCODE_Q}, {"R", SDL_SCANCODE_R}, {"S", SDL_SCANCODE_S}, {"T", SDL_SCANCODE_T}, {"U", SDL_SCANCODE_U}, {"V", SDL_SCANCODE_V}, {"W", SDL_SCANCODE_W}, {"X", SDL_SCANCODE_X}, {"Y", SDL_SCANCODE_Y}, {"Z", SDL_SCANCODE_Z}, {"0", SDL_SCANCODE_0}, {"1", SDL_SCANCODE_1}, {"2", SDL_SCANCODE_2}, {"3", SDL_SCANCODE_3}, {"4", SDL_SCANCODE_4}, {"5", SDL_SCANCODE_5}, {"6", SDL_SCANCODE_6}, {"7", SDL_SCANCODE_7}, {"8", SDL_SCANCODE_8}, {"9", SDL_SCANCODE_9}, {"F1", SDL_SCANCODE_F1}, {"F2", SDL_SCANCODE_F2}, {"F3", SDL_SCANCODE_F3}, {"F4", SDL_SCANCODE_F4}, {"F5", SDL_SCANCODE_F5}, {"F6", SDL_SCANCODE_F6}, {"F7", SDL_SCANCODE_F7}, {"F8", SDL_SCANCODE_F8}, {"F9", SDL_SCANCODE_F9}, {"F10", SDL_SCANCODE_F10}, {"F11", SDL_SCANCODE_F11}, {"F12", SDL_SCANCODE_F12}, {"UP", SDL_SCANCODE_UP}, {"DOWN", SDL_SCANCODE_DOWN}, {"RIGHT", SDL_SCANCODE_RIGHT}, {"LEFT", SDL_SCANCODE_LEFT}, {"LALT", SDL_SCANCODE_LALT}, {"LCTRL", SDL_SCANCODE_LCTRL}, {"LSHIFT", SDL_SCANCODE_LSHIFT}, {"RALT", SDL_SCANCODE_RALT}, {"RCTRL", SDL_SCANCODE_RCTRL}, {"RSHIFT", SDL_SCANCODE_RSHIFT}, {"ESCAPE", SDL_SCANCODE_ESCAPE} }; static int lookup_bind(config_t *cfg_t, char *str, SDL_Scancode *n) { char *tmp; config_lookup_string(cfg_t, str, (const char **)&tmp); for (size_t i = 0; i < nelem(Keylist); ++i) if (! strcmp(tmp, Keylist[i].t)) { *n = Keylist[i].s; return 0; } return 1; } int retrieve_controls(qik_bind *bind, config_t *cfg_t) { if (lookup_bind(cfg_t, "bind.dlook", &bind->dlook)) return 1; if (lookup_bind(cfg_t, "bind.rlook", &bind->rlook)) return 1; if (lookup_bind(cfg_t, "bind.llook", &bind->llook)) return 1; if (lookup_bind(cfg_t, "bind.fmove", &bind->fmove)) return 1; if (lookup_bind(cfg_t, "bind.bmove", &bind->bmove)) return 1; if (lookup_bind(cfg_t, "bind.rmove", &bind->rmove)) return 1; if (lookup_bind(cfg_t, "bind.lmove", &bind->lmove)) return 1; if (lookup_bind(cfg_t, "bind.pfire", &bind->pfire)) return 1; if (lookup_bind(cfg_t, "bind.sfire", &bind->sfire)) return 1; if (lookup_bind(cfg_t, "bind.tfire", &bind->tfire)) return 1; return 0; } void poll_controls(void) { /* Vertical position of the camera */ global_usr.z_pos = global_cfg.h / 2; global_usr.mov_speed = global_frametime * (global_map.speed * 2); global_usr.rot_speed = global_frametime * global_map.speed; /* Pump the event loop, gathering states from input */ SDL_PumpEvents(); Uint8 *Keystate = SDL_GetKeyboardState(NULL); if (Keystate[global_bind.fmove]) { if (!global_map.world.tile[(unsigned)(global_usr.x_pos + global_usr.x_dir * global_usr.mov_speed)][(unsigned)global_usr.y_pos].w) global_usr.x_pos += global_usr.x_dir * global_usr.mov_speed; if (!global_map.world.tile[(unsigned)global_usr.x_pos][(unsigned)(global_usr.y_pos + global_usr.y_dir * global_usr.mov_speed)].w) global_usr.y_pos += global_usr.y_dir * global_usr.mov_speed; } if (Keystate[global_bind.bmove]) { if (!global_map.world.tile[(unsigned)(global_usr.x_pos - global_usr.x_dir * global_usr.mov_speed)][(unsigned)global_usr.y_pos].w) global_usr.x_pos -= global_usr.x_dir * global_usr.mov_speed; if (!global_map.world.tile[(unsigned)global_usr.x_pos][(unsigned)(global_usr.y_pos - global_usr.y_dir * global_usr.mov_speed)].w) global_usr.y_pos -= global_usr.y_dir * global_usr.mov_speed; } if (Keystate[global_bind.rmove]) { if (!global_map.world.tile[(unsigned)(global_usr.x_pos + global_usr.x_plane * global_usr.mov_speed)][(unsigned)global_usr.y_pos].w) global_usr.x_pos += global_usr.x_plane * global_usr.mov_speed; if (!global_map.world.tile[(unsigned)global_usr.x_pos][(unsigned)(global_usr.y_pos + global_usr.y_plane * global_usr.mov_speed)].w) global_usr.y_pos += global_usr.y_plane * global_usr.mov_speed; } if (Keystate[global_bind.lmove]) { if (!global_map.world.tile[(unsigned)(global_usr.x_pos - global_usr.x_plane * global_usr.mov_speed)][(unsigned)global_usr.y_pos].w) global_usr.x_pos -= global_usr.x_plane * global_usr.mov_speed; if (!global_map.world.tile[(unsigned)global_usr.x_pos][(unsigned)(global_usr.y_pos - global_usr.y_plane * global_usr.mov_speed)].w) global_usr.y_pos -= global_usr.y_plane * global_usr.mov_speed; } if (Keystate[global_bind.ulook]) { } if (Keystate[global_bind.dlook]) { } if (Keystate[global_bind.rlook]) { global_usr.x_dir_old = global_usr.x_dir; global_usr.x_dir = global_usr.x_dir * cos(-global_usr.rot_speed) - global_usr.y_dir * sin(-global_usr.rot_speed); global_usr.y_dir = global_usr.x_dir_old * sin(-global_usr.rot_speed) + global_usr.y_dir * cos(-global_usr.rot_speed); global_usr.x_plane_old = global_usr.x_plane; global_usr.x_plane = global_usr.x_plane * cos(-global_usr.rot_speed) - global_usr.y_plane * sin(-global_usr.rot_speed); global_usr.y_plane = global_usr.x_plane_old * sin(-global_usr.rot_speed) + global_usr.y_plane * cos(-global_usr.rot_speed); } if (Keystate[global_bind.llook]) { global_usr.x_dir_old = global_usr.x_dir; global_usr.x_dir = global_usr.x_dir * cos(global_usr.rot_speed) - global_usr.y_dir * sin(global_usr.rot_speed); global_usr.y_dir = global_usr.x_dir_old * sin(global_usr.rot_speed) + global_usr.y_dir * cos(global_usr.rot_speed); global_usr.x_plane_old = global_usr.x_plane; global_usr.x_plane = global_usr.x_plane * cos(global_usr.rot_speed) - global_usr.y_plane * sin(global_usr.rot_speed); global_usr.y_plane = global_usr.x_plane_old * sin(global_usr.rot_speed) + global_usr.y_plane * cos(global_usr.rot_speed); } if (Keystate[global_bind.pfire]) { exit(0); } if (Keystate[global_bind.sfire]) { } if (Keystate[global_bind.tfire]) { } return; }
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/NewsUI.framework/NewsUI */ @interface NUArticlePageStyleOperation : FCOperation { FCArticle * _article; id /* block */ _completion; unsigned long long _pageNextAction; NUPageStyle * _pageStyle; } @property (nonatomic, readonly) FCArticle *article; @property (nonatomic, readonly) id /* block */ completion; @property (nonatomic, readonly) unsigned long long pageNextAction; @property (nonatomic, retain) NUPageStyle *pageStyle; - (void).cxx_destruct; - (id)article; - (id /* block */)completion; - (id)initWithArticle:(id)arg1 pageNextAction:(unsigned long long)arg2 completion:(id /* block */)arg3; - (void)operationDidFinishWithError:(id)arg1; - (unsigned long long)pageNextAction; - (id)pageStyle; - (void)performOperation; - (void)setPageStyle:(id)arg1; - (bool)validateOperation; @end
#include <linux/kernel.h> #include <linux/module.h> /** * int_sqrt - rough approximation to sqrt * @x: integer of which to calculate the sqrt * * A very rough approximation to the sqrt() function. */ unsigned long int_sqrt(unsigned long x) { unsigned long op, res, one; op = x; res = 0; one = 1UL << (BITS_PER_LONG - 2); while (one > op) one >>= 2; while (one != 0) { if (op >= res + one) { op = op - (res + one); res = res + 2 * one; } res /= 2; one /= 4; } return res; } EXPORT_SYMBOL(int_sqrt);
///////////////////////////////////////////////////////////////////////////// // Copyright (C) 2019-2020 <NAME> ///////////////////////////////////////////////////////////////////////////// #pragma once class PepAppHostTask; BOOL UtPepAppHostTasksInitialize(); BOOL UtPepAppHostTasksUninitialize(); BOOL UtPepAppHostTasksCreate(DWORD dwThreadId, PepAppHostTask** ppHostTask); BOOL UtPepAppHostTasksCreate(DWORD dwStackSize, LPTHREAD_START_ROUTINE pStartAddress, PVOID pvParameter, IHostTask** ppHostTask); BOOL UtPepAppHostTasksDestroy(DWORD dwThreadId); BOOL UtPepAppHostTasksFind(DWORD dwThreadId, PepAppHostTask** ppHostTask); ///////////////////////////////////////////////////////////////////////////// // Copyright (C) 2019-2020 <NAME> /////////////////////////////////////////////////////////////////////////////
#ifndef PQCLEAN_NTRULPR653_CLEAN_CRYPTO_ENCODE_653X1541ROUND_H #define PQCLEAN_NTRULPR653_CLEAN_CRYPTO_ENCODE_653X1541ROUND_H #include <stdint.h> #define PQCLEAN_NTRULPR653_CLEAN_crypto_encode_653x1541round_STRBYTES 865 #define PQCLEAN_NTRULPR653_CLEAN_crypto_encode_653x1541round_ITEMS 653 #define PQCLEAN_NTRULPR653_CLEAN_crypto_encode_653x1541round_ITEMBYTES 2 void PQCLEAN_NTRULPR653_CLEAN_crypto_encode_653x1541round(unsigned char *out, const void *v); #endif
<reponame>anycore/anycore-pisa-funcsim<filename>vpi/include/VPI_global_vars.h #ifndef _VPI_GLOBAL_VARS_H #define _VPI_GLOBAL_VARS_H //#define VPI_DEBUG extern veri_memory *VMEM[MAX_THREADS]; extern char *verilog_optstring; extern int numMismatches; #endif
<gh_stars>1000+ /** @file AsmWriteIdtr function Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "BaseLibInternals.h" /** Writes the current Interrupt Descriptor Table Register(GDTR) descriptor. Writes the current IDTR descriptor and returns it in Idtr. This function is only available on IA-32 and x64. @param Idtr The pointer to a IDTR descriptor. **/ VOID EFIAPI InternalX86WriteIdtr ( IN CONST IA32_DESCRIPTOR *Idtr ) { _asm { mov eax, Idtr pushfd cli lidt fword ptr [eax] popfd } }
<filename>tests-clar/object/raw/hash.c #include "clar_libgit2.h" #include "odb.h" #include "hash.h" #include "data.h" static int hash_object(git_oid *oid, git_rawobj *obj) { return git_odb_hash(oid, obj->data, obj->len, obj->type); } static char *hello_id = "22596363b3de40b06f981fb85d82312e8c0ed511"; static char *hello_text = "hello world\n"; static char *bye_id = "ce08fe4884650f067bd5703b6a59a8b3b3c99a09"; static char *bye_text = "bye world\n"; void test_object_raw_hash__hash_by_blocks(void) { git_hash_ctx *ctx; git_oid id1, id2; cl_assert((ctx = git_hash_new_ctx()) != NULL); /* should already be init'd */ git_hash_update(ctx, hello_text, strlen(hello_text)); git_hash_final(&id2, ctx); cl_git_pass(git_oid_fromstr(&id1, hello_id)); cl_assert(git_oid_cmp(&id1, &id2) == 0); /* reinit should permit reuse */ git_hash_init(ctx); git_hash_update(ctx, bye_text, strlen(bye_text)); git_hash_final(&id2, ctx); cl_git_pass(git_oid_fromstr(&id1, bye_id)); cl_assert(git_oid_cmp(&id1, &id2) == 0); git_hash_free_ctx(ctx); } void test_object_raw_hash__hash_buffer_in_single_call(void) { git_oid id1, id2; cl_git_pass(git_oid_fromstr(&id1, hello_id)); git_hash_buf(&id2, hello_text, strlen(hello_text)); cl_assert(git_oid_cmp(&id1, &id2) == 0); } void test_object_raw_hash__hash_vector(void) { git_oid id1, id2; git_buf_vec vec[2]; cl_git_pass(git_oid_fromstr(&id1, hello_id)); vec[0].data = hello_text; vec[0].len = 4; vec[1].data = hello_text+4; vec[1].len = strlen(hello_text)-4; git_hash_vec(&id2, vec, 2); cl_assert(git_oid_cmp(&id1, &id2) == 0); } void test_object_raw_hash__hash_junk_data(void) { git_oid id, id_zero; cl_git_pass(git_oid_fromstr(&id_zero, zero_id)); /* invalid types: */ junk_obj.data = some_data; cl_git_fail(hash_object(&id, &junk_obj)); junk_obj.type = GIT_OBJ__EXT1; cl_git_fail(hash_object(&id, &junk_obj)); junk_obj.type = GIT_OBJ__EXT2; cl_git_fail(hash_object(&id, &junk_obj)); junk_obj.type = GIT_OBJ_OFS_DELTA; cl_git_fail(hash_object(&id, &junk_obj)); junk_obj.type = GIT_OBJ_REF_DELTA; cl_git_fail(hash_object(&id, &junk_obj)); /* data can be NULL only if len is zero: */ junk_obj.type = GIT_OBJ_BLOB; junk_obj.data = NULL; cl_git_pass(hash_object(&id, &junk_obj)); cl_assert(git_oid_cmp(&id, &id_zero) == 0); junk_obj.len = 1; cl_git_fail(hash_object(&id, &junk_obj)); } void test_object_raw_hash__hash_commit_object(void) { git_oid id1, id2; cl_git_pass(git_oid_fromstr(&id1, commit_id)); cl_git_pass(hash_object(&id2, &commit_obj)); cl_assert(git_oid_cmp(&id1, &id2) == 0); } void test_object_raw_hash__hash_tree_object(void) { git_oid id1, id2; cl_git_pass(git_oid_fromstr(&id1, tree_id)); cl_git_pass(hash_object(&id2, &tree_obj)); cl_assert(git_oid_cmp(&id1, &id2) == 0); } void test_object_raw_hash__hash_tag_object(void) { git_oid id1, id2; cl_git_pass(git_oid_fromstr(&id1, tag_id)); cl_git_pass(hash_object(&id2, &tag_obj)); cl_assert(git_oid_cmp(&id1, &id2) == 0); } void test_object_raw_hash__hash_zero_length_object(void) { git_oid id1, id2; cl_git_pass(git_oid_fromstr(&id1, zero_id)); cl_git_pass(hash_object(&id2, &zero_obj)); cl_assert(git_oid_cmp(&id1, &id2) == 0); } void test_object_raw_hash__hash_one_byte_object(void) { git_oid id1, id2; cl_git_pass(git_oid_fromstr(&id1, one_id)); cl_git_pass(hash_object(&id2, &one_obj)); cl_assert(git_oid_cmp(&id1, &id2) == 0); } void test_object_raw_hash__hash_two_byte_object(void) { git_oid id1, id2; cl_git_pass(git_oid_fromstr(&id1, two_id)); cl_git_pass(hash_object(&id2, &two_obj)); cl_assert(git_oid_cmp(&id1, &id2) == 0); } void test_object_raw_hash__hash_multi_byte_object(void) { git_oid id1, id2; cl_git_pass(git_oid_fromstr(&id1, some_id)); cl_git_pass(hash_object(&id2, &some_obj)); cl_assert(git_oid_cmp(&id1, &id2) == 0); }
<reponame>Oeldin/fsmon /* fsmon -- MIT - Copyright NowSecure 2015-2020 - <EMAIL> */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <limits.h> #include <signal.h> #include <getopt.h> #include <unistd.h> #include <inttypes.h> #include <sys/time.h> #include "fsmon.h" static FileMonitor fm = { 0 }; static bool firstnode = true; static bool colorful = true; FileMonitorBackend *backends[] = { #if __APPLE__ #if !TARGET_WATCHOS &fmb_fsevapi, #endif &fmb_devfsev, &fmb_kqueue, &fmb_kdebug, #else &fmb_inotify, #if HAVE_FANOTIFY &fmb_fanotify, #endif #endif NULL }; static void control_c(int sig) { fm.running = false; } static bool setup_signals() { bool res = true; struct sigaction int_handler = { .sa_handler = control_c }; if (sigaction (SIGINT, &int_handler, 0) == -1) { eprintf ("Cannot setup the SIGINT handler\n"); res = false; } fm.running = true; if (fm.alarm) { if (sigaction (SIGALRM, &int_handler, 0) == -1) { eprintf ("Cannot setup the SIGALRM handler.\n"); res = false; } if (alarm (fm.alarm) != 0) { eprintf ("Warning: A previous alarm was found.\n"); res = false; } } return res; } static uint64_t __sys_now(void) { uint64_t ret; struct timeval now; gettimeofday (&now, NULL); ret = now.tv_sec; ret <<= 20; ret |= now.tv_usec; //(sizeof (now.tv_sec) == 4 return ret; } static bool callback(FileMonitor *fm, FileMonitorEvent *ev) { if (fm->child) { if (fm->pid && ev->pid != fm->pid) { if (ev->ppid != fm->pid) { return false; } } } else { if (fm->pid && ev->pid != fm->pid) { return false; } } if (fm->root && ev->file) { if (strncmp (ev->file, fm->root, strlen (fm->root))) { return false; } } if (fm->link && ev->file) { if (!strncmp (ev->file, fm->link, strlen (fm->link))) { return false; } } if (fm->proc && ev->proc) { if (!strstr (ev->proc, fm->proc)) { return false; } } if (fm->json || fm->jsonStream) { if (fm->jsonStream) { firstnode = true; } char *filename = fmu_jsonfilter (ev->file); printf ("%s{\"filename\":\"%s\"", (fm->jsonStream || firstnode)? "":",", filename); if (ev->pid) { printf (",\"pid\":%d", ev->pid); } if (ev->uid && ev->gid) { printf (",\"uid\":%d,\"gid\":%d,", ev->uid, ev->gid); } firstnode = false; free (filename); if (ev->inode) { printf ("\"inode\":%d,", ev->inode); } if (ev->tstamp) { uint64_t now = __sys_now (); printf ("\"time\":%" PRId64 ",", now); } if (ev->tstamp) { printf ("\"timestamp\":%" PRId64 ",", ev->tstamp); } if (ev->inode) { printf ("\"dev\":{\"major\":%d,\"minor\":%d},", ev->dev_major, ev->dev_minor); } if (ev->mode) { printf ("\"mode\":%d,", ev->mode); } if (ev->ppid) { printf ("\"ppid\":%d,", ev->ppid); } if (ev->proc && *ev->proc) { char *proc = fmu_jsonfilter (ev->proc); printf ("\"proc\":\"%s\",", proc); free (proc); } if (ev->event && *ev->event) { char *event = fmu_jsonfilter (ev->event); printf ("\"event\":\"%s\",", event); free (event); } if (ev->newfile && *ev->newfile) { char *filename = fmu_jsonfilter (ev->newfile); printf ("\"newfile\":\"%s\",", filename); free (filename); } printf ("\"type\":\"%s\"}", fm_typestr (ev->type)); if (fm->jsonStream) { printf ("\n"); fflush (stdout); } } else { if (fm->fileonly && ev->file) { const char *p = ev->file; for (p = p + strlen (p); p > ev->file; p--) { if (*p == '/') ev->file = p + 1; } } const char *color_begin = colorful? fm_colorstr (ev->type): ""; const char *color_begin2 = colorful? Color_MAGENTA: ""; const char *color_end = colorful? Color_RESET: ""; // TODO . show event type if (ev->type == FSE_RENAME) { printf ("%s%s%s\t%d\t\"%s%s%s\"\t%s -> %s\n", color_begin, fm_typestr (ev->type), color_end, ev->pid, color_begin2, ev->proc? ev->proc: "", color_end, ev->file, ev->newfile? ev->newfile: "?"); } else { printf ("%s%s%s\t%d\t\"%s%s%s\"\t%s\n", color_begin, fm_typestr (ev->type), color_end, ev->pid, color_begin2, ev->proc? ev->proc: "", color_end, ev->file); } } if (fm->link) { size_t i; char dst[1024]; const char *src = ev->file; char *fname = strdup (ev->file); if (!fname) { eprintf ("Cannot allocate ev->file\n"); return false; } for (i = 0; fname[i]; i++) { if (fname[i] == '/') { fname[i] = '_'; } } if (ev->newfile) { src = ev->newfile; } if (is_directory (src)) { eprintf ("[I] Directories not copied\n"); } else { snprintf (dst, sizeof (dst), "%s/%s", fm->link, fname); if (!copy_file (src, dst)) { eprintf ("[E] Error copying %s\n", dst); } } free (fname); } return false; } static void help (const char *argv0) { eprintf ("Usage: %s [-Jjc] [-a sec] [-b dir] [-B name] [-p pid] [-P proc] [path]\n" " -a [sec] stop monitoring after N seconds (alarm)\n" " -b [dir] backup files to DIR folder (EXPERIMENTAL)\n" " -B [name] specify an alternative backend\n" " -c follow children of -p PID\n" " -f show only filename (no path)\n" " -h show this help\n" " -j output in JSON format\n" " -J output in JSON stream format\n" " -n do not use colors\n" " -L list all filemonitor backends\n" " -p [pid] only show events from this pid\n" " -P [proc] events only from process name\n" " -v show version\n" " [path] only get events from this path\n" "Examples:\n" " fsmon /data\n" " fsmon -J / | jq -r .filename\n" " fsmon -B fanotify /home\n" , argv0); } static bool use_backend(const char *name) { size_t i; for (i = 0; backends[i]; i++) { if (!strcmp (backends[i]->name, name)) { fm.backend = *backends[i]; return true; } } return false; } static void list_backends() { size_t i; for (i = 0; backends[i]; i++) { printf ("%s\n", backends[i]->name); } } int main (int argc, char **argv) { char *absroot[PATH_MAX]; int c, ret = 0; #if __APPLE__ fm.backend = fmb_devfsev; #else fm.backend = fmb_inotify; #endif while ((c = getopt (argc, argv, "a:chb:B:d:fjJlLnp:P:v")) != -1) { switch (c) { case 'a': fm.alarm = atoi (optarg); if (fm.alarm < 1) { eprintf ("Invalid alarm time\n"); return 1; } break; case 'b': fm.link = optarg; break; case 'B': use_backend (optarg); break; case 'c': fm.child = true; break; case 'h': help (argv[0]); return 0; case 'f': fm.fileonly = true; break; case 'j': fm.json = true; break; case 'J': fm.jsonStream = true; break; case 'l': case 'L': list_backends (); return 0; case 'n': colorful = false; break; case 'p': fm.pid = atoi (optarg); break; case 'P': fm.proc = optarg; break; case 'v': printf ("fsmon %s\n", FSMON_VERSION); return 0; } } if (optind < argc) { if (optind + 1 < argc) { eprintf ("Warning: Too many arguments passed, capturing events only from the first path.\n"); } char * res = realpath (argv[optind], (char *)absroot); if (!res) { eprintf ("Invalid path\n"); return 1; } fm.root = (const char *)absroot; } if (fm.child && !fm.pid) { eprintf ("-c requires -p\n"); return 1; } if (fm.json && !fm.jsonStream) { printf ("["); } if (fm.backend.begin (&fm)) { (void)setup_signals (); fm.backend.loop (&fm, callback); } else { ret = 1; } if (fm.json && !fm.jsonStream) { printf ("]\n"); } fflush (stdout); fm.backend.end (&fm); return ret; }
<gh_stars>0 /* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "EUTRA-RRC-Definitions" * found in "/home/lixh/enb_folder/openair2/RRC/LTE/MESSAGES/asn1c/ASN1_files/lte-rrc-14.7.0.asn1" * `asn1c -pdu=all -fcompound-names -gen-PER -no-gen-OER -no-gen-example -D /home/lixh/enb_folder/cmake_targets/lte_build_oai/build/CMakeFiles/RRC_Rel14` */ #include "LTE_SystemInformationBlockType8.h" static int memb_LTE_longCodeState1XRTT_constraint_7(const asn_TYPE_descriptor_t *td, const void *sptr, asn_app_constraint_failed_f *ctfailcb, void *app_key) { const BIT_STRING_t *st = (const BIT_STRING_t *)sptr; size_t size; if(!sptr) { ASN__CTFAIL(app_key, td, sptr, "%s: value not given (%s:%d)", td->name, __FILE__, __LINE__); return -1; } if(st->size > 0) { /* Size in bits */ size = 8 * st->size - (st->bits_unused & 0x07); } else { size = 0; } if((size == 42)) { /* Constraint check succeeded */ return 0; } else { ASN__CTFAIL(app_key, td, sptr, "%s: constraint failed (%s:%d)", td->name, __FILE__, __LINE__); return -1; } } /* * This type is implemented using NativeEnumerated, * so here we adjust the DEF accordingly. */ static int memb_LTE_searchWindowSize_constraint_1(const asn_TYPE_descriptor_t *td, const void *sptr, asn_app_constraint_failed_f *ctfailcb, void *app_key) { long value; if(!sptr) { ASN__CTFAIL(app_key, td, sptr, "%s: value not given (%s:%d)", td->name, __FILE__, __LINE__); return -1; } value = *(const long *)sptr; if((value >= 0 && value <= 15)) { /* Constraint check succeeded */ return 0; } else { ASN__CTFAIL(app_key, td, sptr, "%s: constraint failed (%s:%d)", td->name, __FILE__, __LINE__); return -1; } } static asn_per_constraints_t asn_PER_memb_LTE_longCodeState1XRTT_constr_9 CC_NOTUSED = { { APC_UNCONSTRAINED, -1, -1, 0, 0 }, { APC_CONSTRAINED, 0, 0, 42, 42 } /* (SIZE(42..42)) */, 0, 0 /* No PER value map */ }; static asn_per_constraints_t asn_PER_type_LTE_csfb_DualRxTxSupport_r10_constr_20 CC_NOTUSED = { { APC_CONSTRAINED, 0, 0, 0, 0 } /* (0..0) */, { APC_UNCONSTRAINED, -1, -1, 0, 0 }, 0, 0 /* No PER value map */ }; static asn_per_constraints_t asn_PER_memb_LTE_searchWindowSize_constr_3 CC_NOTUSED = { { APC_CONSTRAINED, 4, 4, 0, 15 } /* (0..15) */, { APC_UNCONSTRAINED, -1, -1, 0, 0 }, 0, 0 /* No PER value map */ }; static asn_TYPE_member_t asn_MBR_LTE_parametersHRPD_4[] = { { ATF_NOFLAGS, 0, offsetof(struct LTE_SystemInformationBlockType8__parametersHRPD, preRegistrationInfoHRPD), (ASN_TAG_CLASS_CONTEXT | (0 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_LTE_PreRegistrationInfoHRPD, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "preRegistrationInfoHRPD" }, { ATF_POINTER, 1, offsetof(struct LTE_SystemInformationBlockType8__parametersHRPD, cellReselectionParametersHRPD), (ASN_TAG_CLASS_CONTEXT | (1 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_LTE_CellReselectionParametersCDMA2000, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "cellReselectionParametersHRPD" }, }; static const int asn_MAP_LTE_parametersHRPD_oms_4[] = { 1 }; static const ber_tlv_tag_t asn_DEF_LTE_parametersHRPD_tags_4[] = { (ASN_TAG_CLASS_CONTEXT | (2 << 2)), (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; static const asn_TYPE_tag2member_t asn_MAP_LTE_parametersHRPD_tag2el_4[] = { { (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* preRegistrationInfoHRPD */ { (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 } /* cellReselectionParametersHRPD */ }; static asn_SEQUENCE_specifics_t asn_SPC_LTE_parametersHRPD_specs_4 = { sizeof(struct LTE_SystemInformationBlockType8__parametersHRPD), offsetof(struct LTE_SystemInformationBlockType8__parametersHRPD, _asn_ctx), asn_MAP_LTE_parametersHRPD_tag2el_4, 2, /* Count of tags in the map */ asn_MAP_LTE_parametersHRPD_oms_4, /* Optional members */ 1, 0, /* Root/Additions */ -1, /* First extension addition */ }; static /* Use -fall-defs-global to expose */ asn_TYPE_descriptor_t asn_DEF_LTE_parametersHRPD_4 = { "parametersHRPD", "parametersHRPD", &asn_OP_SEQUENCE, asn_DEF_LTE_parametersHRPD_tags_4, sizeof(asn_DEF_LTE_parametersHRPD_tags_4) /sizeof(asn_DEF_LTE_parametersHRPD_tags_4[0]) - 1, /* 1 */ asn_DEF_LTE_parametersHRPD_tags_4, /* Same as above */ sizeof(asn_DEF_LTE_parametersHRPD_tags_4) /sizeof(asn_DEF_LTE_parametersHRPD_tags_4[0]), /* 2 */ { 0, 0, SEQUENCE_constraint }, asn_MBR_LTE_parametersHRPD_4, 2, /* Elements count */ &asn_SPC_LTE_parametersHRPD_specs_4 /* Additional specs */ }; static asn_TYPE_member_t asn_MBR_LTE_parameters1XRTT_7[] = { { ATF_POINTER, 3, offsetof(struct LTE_SystemInformationBlockType8__parameters1XRTT, csfb_RegistrationParam1XRTT), (ASN_TAG_CLASS_CONTEXT | (0 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_LTE_CSFB_RegistrationParam1XRTT, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "csfb-RegistrationParam1XRTT" }, { ATF_POINTER, 2, offsetof(struct LTE_SystemInformationBlockType8__parameters1XRTT, longCodeState1XRTT), (ASN_TAG_CLASS_CONTEXT | (1 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_BIT_STRING, 0, { 0, &asn_PER_memb_LTE_longCodeState1XRTT_constr_9, memb_LTE_longCodeState1XRTT_constraint_7 }, 0, 0, /* No default value */ "longCodeState1XRTT" }, { ATF_POINTER, 1, offsetof(struct LTE_SystemInformationBlockType8__parameters1XRTT, cellReselectionParameters1XRTT), (ASN_TAG_CLASS_CONTEXT | (2 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_LTE_CellReselectionParametersCDMA2000, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "cellReselectionParameters1XRTT" }, }; static const int asn_MAP_LTE_parameters1XRTT_oms_7[] = { 0, 1, 2 }; static const ber_tlv_tag_t asn_DEF_LTE_parameters1XRTT_tags_7[] = { (ASN_TAG_CLASS_CONTEXT | (3 << 2)), (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; static const asn_TYPE_tag2member_t asn_MAP_LTE_parameters1XRTT_tag2el_7[] = { { (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* csfb-RegistrationParam1XRTT */ { (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 }, /* longCodeState1XRTT */ { (ASN_TAG_CLASS_CONTEXT | (2 << 2)), 2, 0, 0 } /* cellReselectionParameters1XRTT */ }; static asn_SEQUENCE_specifics_t asn_SPC_LTE_parameters1XRTT_specs_7 = { sizeof(struct LTE_SystemInformationBlockType8__parameters1XRTT), offsetof(struct LTE_SystemInformationBlockType8__parameters1XRTT, _asn_ctx), asn_MAP_LTE_parameters1XRTT_tag2el_7, 3, /* Count of tags in the map */ asn_MAP_LTE_parameters1XRTT_oms_7, /* Optional members */ 3, 0, /* Root/Additions */ -1, /* First extension addition */ }; static /* Use -fall-defs-global to expose */ asn_TYPE_descriptor_t asn_DEF_LTE_parameters1XRTT_7 = { "parameters1XRTT", "parameters1XRTT", &asn_OP_SEQUENCE, asn_DEF_LTE_parameters1XRTT_tags_7, sizeof(asn_DEF_LTE_parameters1XRTT_tags_7) /sizeof(asn_DEF_LTE_parameters1XRTT_tags_7[0]) - 1, /* 1 */ asn_DEF_LTE_parameters1XRTT_tags_7, /* Same as above */ sizeof(asn_DEF_LTE_parameters1XRTT_tags_7) /sizeof(asn_DEF_LTE_parameters1XRTT_tags_7[0]), /* 2 */ { 0, 0, SEQUENCE_constraint }, asn_MBR_LTE_parameters1XRTT_7, 3, /* Elements count */ &asn_SPC_LTE_parameters1XRTT_specs_7 /* Additional specs */ }; static asn_TYPE_member_t asn_MBR_LTE_ext1_13[] = { { ATF_POINTER, 5, offsetof(struct LTE_SystemInformationBlockType8__ext1, csfb_SupportForDualRxUEs_r9), (ASN_TAG_CLASS_CONTEXT | (0 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_BOOLEAN, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "csfb-SupportForDualRxUEs-r9" }, { ATF_POINTER, 4, offsetof(struct LTE_SystemInformationBlockType8__ext1, cellReselectionParametersHRPD_v920), (ASN_TAG_CLASS_CONTEXT | (1 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_LTE_CellReselectionParametersCDMA2000_v920, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "cellReselectionParametersHRPD-v920" }, { ATF_POINTER, 3, offsetof(struct LTE_SystemInformationBlockType8__ext1, cellReselectionParameters1XRTT_v920), (ASN_TAG_CLASS_CONTEXT | (2 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_LTE_CellReselectionParametersCDMA2000_v920, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "cellReselectionParameters1XRTT-v920" }, { ATF_POINTER, 2, offsetof(struct LTE_SystemInformationBlockType8__ext1, csfb_RegistrationParam1XRTT_v920), (ASN_TAG_CLASS_CONTEXT | (3 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_LTE_CSFB_RegistrationParam1XRTT_v920, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "csfb-RegistrationParam1XRTT-v920" }, { ATF_POINTER, 1, offsetof(struct LTE_SystemInformationBlockType8__ext1, ac_BarringConfig1XRTT_r9), (ASN_TAG_CLASS_CONTEXT | (4 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_LTE_AC_BarringConfig1XRTT_r9, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "ac-BarringConfig1XRTT-r9" }, }; static const int asn_MAP_LTE_ext1_oms_13[] = { 0, 1, 2, 3, 4 }; static const ber_tlv_tag_t asn_DEF_LTE_ext1_tags_13[] = { (ASN_TAG_CLASS_CONTEXT | (5 << 2)), (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; static const asn_TYPE_tag2member_t asn_MAP_LTE_ext1_tag2el_13[] = { { (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* csfb-SupportForDualRxUEs-r9 */ { (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 }, /* cellReselectionParametersHRPD-v920 */ { (ASN_TAG_CLASS_CONTEXT | (2 << 2)), 2, 0, 0 }, /* cellReselectionParameters1XRTT-v920 */ { (ASN_TAG_CLASS_CONTEXT | (3 << 2)), 3, 0, 0 }, /* csfb-RegistrationParam1XRTT-v920 */ { (ASN_TAG_CLASS_CONTEXT | (4 << 2)), 4, 0, 0 } /* ac-BarringConfig1XRTT-r9 */ }; static asn_SEQUENCE_specifics_t asn_SPC_LTE_ext1_specs_13 = { sizeof(struct LTE_SystemInformationBlockType8__ext1), offsetof(struct LTE_SystemInformationBlockType8__ext1, _asn_ctx), asn_MAP_LTE_ext1_tag2el_13, 5, /* Count of tags in the map */ asn_MAP_LTE_ext1_oms_13, /* Optional members */ 5, 0, /* Root/Additions */ -1, /* First extension addition */ }; static /* Use -fall-defs-global to expose */ asn_TYPE_descriptor_t asn_DEF_LTE_ext1_13 = { "ext1", "ext1", &asn_OP_SEQUENCE, asn_DEF_LTE_ext1_tags_13, sizeof(asn_DEF_LTE_ext1_tags_13) /sizeof(asn_DEF_LTE_ext1_tags_13[0]) - 1, /* 1 */ asn_DEF_LTE_ext1_tags_13, /* Same as above */ sizeof(asn_DEF_LTE_ext1_tags_13) /sizeof(asn_DEF_LTE_ext1_tags_13[0]), /* 2 */ { 0, 0, SEQUENCE_constraint }, asn_MBR_LTE_ext1_13, 5, /* Elements count */ &asn_SPC_LTE_ext1_specs_13 /* Additional specs */ }; static const asn_INTEGER_enum_map_t asn_MAP_LTE_csfb_DualRxTxSupport_r10_value2enum_20[] = { { 0, 4, "true" } }; static const unsigned int asn_MAP_LTE_csfb_DualRxTxSupport_r10_enum2value_20[] = { 0 /* true(0) */ }; static const asn_INTEGER_specifics_t asn_SPC_LTE_csfb_DualRxTxSupport_r10_specs_20 = { asn_MAP_LTE_csfb_DualRxTxSupport_r10_value2enum_20, /* "tag" => N; sorted by tag */ asn_MAP_LTE_csfb_DualRxTxSupport_r10_enum2value_20, /* N => "tag"; sorted by N */ 1, /* Number of elements in the maps */ 0, /* Enumeration is not extensible */ 1, /* Strict enumeration */ 0, /* Native long size */ 0 }; static const ber_tlv_tag_t asn_DEF_LTE_csfb_DualRxTxSupport_r10_tags_20[] = { (ASN_TAG_CLASS_CONTEXT | (0 << 2)), (ASN_TAG_CLASS_UNIVERSAL | (10 << 2)) }; static /* Use -fall-defs-global to expose */ asn_TYPE_descriptor_t asn_DEF_LTE_csfb_DualRxTxSupport_r10_20 = { "csfb-DualRxTxSupport-r10", "csfb-DualRxTxSupport-r10", &asn_OP_NativeEnumerated, asn_DEF_LTE_csfb_DualRxTxSupport_r10_tags_20, sizeof(asn_DEF_LTE_csfb_DualRxTxSupport_r10_tags_20) /sizeof(asn_DEF_LTE_csfb_DualRxTxSupport_r10_tags_20[0]) - 1, /* 1 */ asn_DEF_LTE_csfb_DualRxTxSupport_r10_tags_20, /* Same as above */ sizeof(asn_DEF_LTE_csfb_DualRxTxSupport_r10_tags_20) /sizeof(asn_DEF_LTE_csfb_DualRxTxSupport_r10_tags_20[0]), /* 2 */ { 0, &asn_PER_type_LTE_csfb_DualRxTxSupport_r10_constr_20, NativeEnumerated_constraint }, 0, 0, /* Defined elsewhere */ &asn_SPC_LTE_csfb_DualRxTxSupport_r10_specs_20 /* Additional specs */ }; static asn_TYPE_member_t asn_MBR_LTE_ext2_19[] = { { ATF_POINTER, 1, offsetof(struct LTE_SystemInformationBlockType8__ext2, csfb_DualRxTxSupport_r10), (ASN_TAG_CLASS_CONTEXT | (0 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_LTE_csfb_DualRxTxSupport_r10_20, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "csfb-DualRxTxSupport-r10" }, }; static const int asn_MAP_LTE_ext2_oms_19[] = { 0 }; static const ber_tlv_tag_t asn_DEF_LTE_ext2_tags_19[] = { (ASN_TAG_CLASS_CONTEXT | (6 << 2)), (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; static const asn_TYPE_tag2member_t asn_MAP_LTE_ext2_tag2el_19[] = { { (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 } /* csfb-DualRxTxSupport-r10 */ }; static asn_SEQUENCE_specifics_t asn_SPC_LTE_ext2_specs_19 = { sizeof(struct LTE_SystemInformationBlockType8__ext2), offsetof(struct LTE_SystemInformationBlockType8__ext2, _asn_ctx), asn_MAP_LTE_ext2_tag2el_19, 1, /* Count of tags in the map */ asn_MAP_LTE_ext2_oms_19, /* Optional members */ 1, 0, /* Root/Additions */ -1, /* First extension addition */ }; static /* Use -fall-defs-global to expose */ asn_TYPE_descriptor_t asn_DEF_LTE_ext2_19 = { "ext2", "ext2", &asn_OP_SEQUENCE, asn_DEF_LTE_ext2_tags_19, sizeof(asn_DEF_LTE_ext2_tags_19) /sizeof(asn_DEF_LTE_ext2_tags_19[0]) - 1, /* 1 */ asn_DEF_LTE_ext2_tags_19, /* Same as above */ sizeof(asn_DEF_LTE_ext2_tags_19) /sizeof(asn_DEF_LTE_ext2_tags_19[0]), /* 2 */ { 0, 0, SEQUENCE_constraint }, asn_MBR_LTE_ext2_19, 1, /* Elements count */ &asn_SPC_LTE_ext2_specs_19 /* Additional specs */ }; static asn_TYPE_member_t asn_MBR_LTE_ext3_22[] = { { ATF_POINTER, 1, offsetof(struct LTE_SystemInformationBlockType8__ext3, sib8_PerPLMN_List_r11), (ASN_TAG_CLASS_CONTEXT | (0 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_LTE_SIB8_PerPLMN_List_r11, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "sib8-PerPLMN-List-r11" }, }; static const int asn_MAP_LTE_ext3_oms_22[] = { 0 }; static const ber_tlv_tag_t asn_DEF_LTE_ext3_tags_22[] = { (ASN_TAG_CLASS_CONTEXT | (7 << 2)), (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; static const asn_TYPE_tag2member_t asn_MAP_LTE_ext3_tag2el_22[] = { { (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 } /* sib8-PerPLMN-List-r11 */ }; static asn_SEQUENCE_specifics_t asn_SPC_LTE_ext3_specs_22 = { sizeof(struct LTE_SystemInformationBlockType8__ext3), offsetof(struct LTE_SystemInformationBlockType8__ext3, _asn_ctx), asn_MAP_LTE_ext3_tag2el_22, 1, /* Count of tags in the map */ asn_MAP_LTE_ext3_oms_22, /* Optional members */ 1, 0, /* Root/Additions */ -1, /* First extension addition */ }; static /* Use -fall-defs-global to expose */ asn_TYPE_descriptor_t asn_DEF_LTE_ext3_22 = { "ext3", "ext3", &asn_OP_SEQUENCE, asn_DEF_LTE_ext3_tags_22, sizeof(asn_DEF_LTE_ext3_tags_22) /sizeof(asn_DEF_LTE_ext3_tags_22[0]) - 1, /* 1 */ asn_DEF_LTE_ext3_tags_22, /* Same as above */ sizeof(asn_DEF_LTE_ext3_tags_22) /sizeof(asn_DEF_LTE_ext3_tags_22[0]), /* 2 */ { 0, 0, SEQUENCE_constraint }, asn_MBR_LTE_ext3_22, 1, /* Elements count */ &asn_SPC_LTE_ext3_specs_22 /* Additional specs */ }; asn_TYPE_member_t asn_MBR_LTE_SystemInformationBlockType8_1[] = { { ATF_POINTER, 8, offsetof(struct LTE_SystemInformationBlockType8, systemTimeInfo), (ASN_TAG_CLASS_CONTEXT | (0 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_LTE_SystemTimeInfoCDMA2000, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "systemTimeInfo" }, { ATF_POINTER, 7, offsetof(struct LTE_SystemInformationBlockType8, searchWindowSize), (ASN_TAG_CLASS_CONTEXT | (1 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_NativeInteger, 0, { 0, &asn_PER_memb_LTE_searchWindowSize_constr_3, memb_LTE_searchWindowSize_constraint_1 }, 0, 0, /* No default value */ "searchWindowSize" }, { ATF_POINTER, 6, offsetof(struct LTE_SystemInformationBlockType8, parametersHRPD), (ASN_TAG_CLASS_CONTEXT | (2 << 2)), 0, &asn_DEF_LTE_parametersHRPD_4, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "parametersHRPD" }, { ATF_POINTER, 5, offsetof(struct LTE_SystemInformationBlockType8, parameters1XRTT), (ASN_TAG_CLASS_CONTEXT | (3 << 2)), 0, &asn_DEF_LTE_parameters1XRTT_7, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "parameters1XRTT" }, { ATF_POINTER, 4, offsetof(struct LTE_SystemInformationBlockType8, lateNonCriticalExtension), (ASN_TAG_CLASS_CONTEXT | (4 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_OCTET_STRING, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "lateNonCriticalExtension" }, { ATF_POINTER, 3, offsetof(struct LTE_SystemInformationBlockType8, ext1), (ASN_TAG_CLASS_CONTEXT | (5 << 2)), 0, &asn_DEF_LTE_ext1_13, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "ext1" }, { ATF_POINTER, 2, offsetof(struct LTE_SystemInformationBlockType8, ext2), (ASN_TAG_CLASS_CONTEXT | (6 << 2)), 0, &asn_DEF_LTE_ext2_19, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "ext2" }, { ATF_POINTER, 1, offsetof(struct LTE_SystemInformationBlockType8, ext3), (ASN_TAG_CLASS_CONTEXT | (7 << 2)), 0, &asn_DEF_LTE_ext3_22, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "ext3" }, }; static const int asn_MAP_LTE_SystemInformationBlockType8_oms_1[] = { 0, 1, 2, 3, 4, 5, 6, 7 }; static const ber_tlv_tag_t asn_DEF_LTE_SystemInformationBlockType8_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; static const asn_TYPE_tag2member_t asn_MAP_LTE_SystemInformationBlockType8_tag2el_1[] = { { (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* systemTimeInfo */ { (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 }, /* searchWindowSize */ { (ASN_TAG_CLASS_CONTEXT | (2 << 2)), 2, 0, 0 }, /* parametersHRPD */ { (ASN_TAG_CLASS_CONTEXT | (3 << 2)), 3, 0, 0 }, /* parameters1XRTT */ { (ASN_TAG_CLASS_CONTEXT | (4 << 2)), 4, 0, 0 }, /* lateNonCriticalExtension */ { (ASN_TAG_CLASS_CONTEXT | (5 << 2)), 5, 0, 0 }, /* ext1 */ { (ASN_TAG_CLASS_CONTEXT | (6 << 2)), 6, 0, 0 }, /* ext2 */ { (ASN_TAG_CLASS_CONTEXT | (7 << 2)), 7, 0, 0 } /* ext3 */ }; asn_SEQUENCE_specifics_t asn_SPC_LTE_SystemInformationBlockType8_specs_1 = { sizeof(struct LTE_SystemInformationBlockType8), offsetof(struct LTE_SystemInformationBlockType8, _asn_ctx), asn_MAP_LTE_SystemInformationBlockType8_tag2el_1, 8, /* Count of tags in the map */ asn_MAP_LTE_SystemInformationBlockType8_oms_1, /* Optional members */ 4, 4, /* Root/Additions */ 4, /* First extension addition */ }; asn_TYPE_descriptor_t asn_DEF_LTE_SystemInformationBlockType8 = { "SystemInformationBlockType8", "SystemInformationBlockType8", &asn_OP_SEQUENCE, asn_DEF_LTE_SystemInformationBlockType8_tags_1, sizeof(asn_DEF_LTE_SystemInformationBlockType8_tags_1) /sizeof(asn_DEF_LTE_SystemInformationBlockType8_tags_1[0]), /* 1 */ asn_DEF_LTE_SystemInformationBlockType8_tags_1, /* Same as above */ sizeof(asn_DEF_LTE_SystemInformationBlockType8_tags_1) /sizeof(asn_DEF_LTE_SystemInformationBlockType8_tags_1[0]), /* 1 */ { 0, 0, SEQUENCE_constraint }, asn_MBR_LTE_SystemInformationBlockType8_1, 8, /* Elements count */ &asn_SPC_LTE_SystemInformationBlockType8_specs_1 /* Additional specs */ };
<reponame>unterweg/peanoclaw // This file is part of the Peano project. For conditions of distribution and // use, please see the copyright notice at www.peano-framework.org #ifndef _PEANOCLAW_REPOSITORIES_REPOSITORY_ARRAY_STD_H_ #define _PEANOCLAW_REPOSITORIES_REPOSITORY_ARRAY_STD_H_ #include "peanoclaw/repositories/Repository.h" #include "peanoclaw/records/RepositoryState.h" #include "peanoclaw/State.h" #include "peanoclaw/Vertex.h" #include "peanoclaw/Cell.h" #include "peano/grid/Grid.h" #include "peano/stacks/CellSTDStack.h" #include "peano/stacks/VertexSTDStack.h" #include "peanoclaw/adapters/InitialiseGrid.h" #include "peanoclaw/adapters/InitialiseAndValidateGrid.h" #include "peanoclaw/adapters/Plot.h" #include "peanoclaw/adapters/PlotAndValidateGrid.h" #include "peanoclaw/adapters/Remesh.h" #include "peanoclaw/adapters/SolveTimestep.h" #include "peanoclaw/adapters/SolveTimestepAndValidateGrid.h" #include "peanoclaw/adapters/SolveTimestepAndPlot.h" #include "peanoclaw/adapters/SolveTimestepAndPlotAndValidateGrid.h" #include "peanoclaw/adapters/GatherCurrentSolution.h" #include "peanoclaw/adapters/GatherCurrentSolutionAndValidateGrid.h" #include "peanoclaw/adapters/Cleanup.h" namespace peanoclaw { namespace repositories { class RepositorySTDStack; } } class peanoclaw::repositories::RepositorySTDStack: public peanoclaw::repositories::Repository { private: static tarch::logging::Log _log; peano::geometry::Geometry& _geometry; typedef peano::stacks::CellSTDStack<peanoclaw::Cell> CellStack; typedef peano::stacks::VertexSTDStack<peanoclaw::Vertex> VertexStack; CellStack _cellStack; VertexStack _vertexStack; peanoclaw::State _solverState; peano::grid::RegularGridContainer<peanoclaw::Vertex,peanoclaw::Cell> _regularGridContainer; peano::grid::TraversalOrderOnTopLevel _traversalOrderOnTopLevel; peano::grid::Grid<peanoclaw::Vertex,peanoclaw::Cell,peanoclaw::State,VertexStack,CellStack,peanoclaw::adapters::InitialiseGrid> _gridWithInitialiseGrid; peano::grid::Grid<peanoclaw::Vertex,peanoclaw::Cell,peanoclaw::State,VertexStack,CellStack,peanoclaw::adapters::InitialiseAndValidateGrid> _gridWithInitialiseAndValidateGrid; peano::grid::Grid<peanoclaw::Vertex,peanoclaw::Cell,peanoclaw::State,VertexStack,CellStack,peanoclaw::adapters::Plot> _gridWithPlot; peano::grid::Grid<peanoclaw::Vertex,peanoclaw::Cell,peanoclaw::State,VertexStack,CellStack,peanoclaw::adapters::PlotAndValidateGrid> _gridWithPlotAndValidateGrid; peano::grid::Grid<peanoclaw::Vertex,peanoclaw::Cell,peanoclaw::State,VertexStack,CellStack,peanoclaw::adapters::Remesh> _gridWithRemesh; peano::grid::Grid<peanoclaw::Vertex,peanoclaw::Cell,peanoclaw::State,VertexStack,CellStack,peanoclaw::adapters::SolveTimestep> _gridWithSolveTimestep; peano::grid::Grid<peanoclaw::Vertex,peanoclaw::Cell,peanoclaw::State,VertexStack,CellStack,peanoclaw::adapters::SolveTimestepAndValidateGrid> _gridWithSolveTimestepAndValidateGrid; peano::grid::Grid<peanoclaw::Vertex,peanoclaw::Cell,peanoclaw::State,VertexStack,CellStack,peanoclaw::adapters::SolveTimestepAndPlot> _gridWithSolveTimestepAndPlot; peano::grid::Grid<peanoclaw::Vertex,peanoclaw::Cell,peanoclaw::State,VertexStack,CellStack,peanoclaw::adapters::SolveTimestepAndPlotAndValidateGrid> _gridWithSolveTimestepAndPlotAndValidateGrid; peano::grid::Grid<peanoclaw::Vertex,peanoclaw::Cell,peanoclaw::State,VertexStack,CellStack,peanoclaw::adapters::GatherCurrentSolution> _gridWithGatherCurrentSolution; peano::grid::Grid<peanoclaw::Vertex,peanoclaw::Cell,peanoclaw::State,VertexStack,CellStack,peanoclaw::adapters::GatherCurrentSolutionAndValidateGrid> _gridWithGatherCurrentSolutionAndValidateGrid; peano::grid::Grid<peanoclaw::Vertex,peanoclaw::Cell,peanoclaw::State,VertexStack,CellStack,peanoclaw::adapters::Cleanup> _gridWithCleanup; peanoclaw::records::RepositoryState _repositoryState; tarch::timing::Measurement _measureInitialiseGridCPUTime; tarch::timing::Measurement _measureInitialiseAndValidateGridCPUTime; tarch::timing::Measurement _measurePlotCPUTime; tarch::timing::Measurement _measurePlotAndValidateGridCPUTime; tarch::timing::Measurement _measureRemeshCPUTime; tarch::timing::Measurement _measureSolveTimestepCPUTime; tarch::timing::Measurement _measureSolveTimestepAndValidateGridCPUTime; tarch::timing::Measurement _measureSolveTimestepAndPlotCPUTime; tarch::timing::Measurement _measureSolveTimestepAndPlotAndValidateGridCPUTime; tarch::timing::Measurement _measureGatherCurrentSolutionCPUTime; tarch::timing::Measurement _measureGatherCurrentSolutionAndValidateGridCPUTime; tarch::timing::Measurement _measureCleanupCPUTime; tarch::timing::Measurement _measureInitialiseGridCalendarTime; tarch::timing::Measurement _measureInitialiseAndValidateGridCalendarTime; tarch::timing::Measurement _measurePlotCalendarTime; tarch::timing::Measurement _measurePlotAndValidateGridCalendarTime; tarch::timing::Measurement _measureRemeshCalendarTime; tarch::timing::Measurement _measureSolveTimestepCalendarTime; tarch::timing::Measurement _measureSolveTimestepAndValidateGridCalendarTime; tarch::timing::Measurement _measureSolveTimestepAndPlotCalendarTime; tarch::timing::Measurement _measureSolveTimestepAndPlotAndValidateGridCalendarTime; tarch::timing::Measurement _measureGatherCurrentSolutionCalendarTime; tarch::timing::Measurement _measureGatherCurrentSolutionAndValidateGridCalendarTime; tarch::timing::Measurement _measureCleanupCalendarTime; public: RepositorySTDStack( peano::geometry::Geometry& geometry, const tarch::la::Vector<DIMENSIONS,double>& domainSize, const tarch::la::Vector<DIMENSIONS,double>& computationalDomainOffset ); /** * Parallel Constructor * * Used in parallel mode only where the size of the domain is not known * when the type of repository is determined. */ RepositorySTDStack( peano::geometry::Geometry& geometry ); virtual ~RepositorySTDStack(); virtual void restart( const tarch::la::Vector<DIMENSIONS,double>& domainSize, const tarch::la::Vector<DIMENSIONS,double>& domainOffset, int domainLevel, const tarch::la::Vector<DIMENSIONS,int>& positionOfCentralElementWithRespectToCoarserRemoteLevel ); virtual void terminate(); virtual peanoclaw::State& getState(); virtual const peanoclaw::State& getState() const; virtual void iterate(int numberOfIterations=1, bool exchangeBoundaryVertices=true); virtual void writeCheckpoint(peano::grid::Checkpoint<peanoclaw::Vertex, peanoclaw::Cell> * const checkpoint); virtual void readCheckpoint( peano::grid::Checkpoint<peanoclaw::Vertex, peanoclaw::Cell> const * const checkpoint ); virtual peano::grid::Checkpoint<peanoclaw::Vertex, peanoclaw::Cell>* createEmptyCheckpoint(); virtual void switchToInitialiseGrid(); virtual void switchToInitialiseAndValidateGrid(); virtual void switchToPlot(); virtual void switchToPlotAndValidateGrid(); virtual void switchToRemesh(); virtual void switchToSolveTimestep(); virtual void switchToSolveTimestepAndValidateGrid(); virtual void switchToSolveTimestepAndPlot(); virtual void switchToSolveTimestepAndPlotAndValidateGrid(); virtual void switchToGatherCurrentSolution(); virtual void switchToGatherCurrentSolutionAndValidateGrid(); virtual void switchToCleanup(); virtual bool isActiveAdapterInitialiseGrid() const; virtual bool isActiveAdapterInitialiseAndValidateGrid() const; virtual bool isActiveAdapterPlot() const; virtual bool isActiveAdapterPlotAndValidateGrid() const; virtual bool isActiveAdapterRemesh() const; virtual bool isActiveAdapterSolveTimestep() const; virtual bool isActiveAdapterSolveTimestepAndValidateGrid() const; virtual bool isActiveAdapterSolveTimestepAndPlot() const; virtual bool isActiveAdapterSolveTimestepAndPlotAndValidateGrid() const; virtual bool isActiveAdapterGatherCurrentSolution() const; virtual bool isActiveAdapterGatherCurrentSolutionAndValidateGrid() const; virtual bool isActiveAdapterCleanup() const; #ifdef Parallel virtual ContinueCommand continueToIterate(); virtual void runGlobalStep(); #endif virtual void setMaximumMemoryFootprintForTemporaryRegularGrids(double value); virtual void logIterationStatistics() const; virtual void clearIterationStatistics(); }; #endif
<filename>include/functions.h #ifndef FUNCTION_H #define FUNCTION_H #include "main.h" #include "ports.h" using namespace pros; class Intake { public: bool intakeSpinning = false; Motor motor = Motor(M_INTAKE, E_MOTOR_GEARSET_18, false); Controller controller; Intake(Controller c); void handle(); void spin(int direction); // -1 flip cap, 0 stop, 1 flip ball }; enum class PuncherState { PullBack, // Initial pull back of the puncher Ready, // Pulled back fully Punch, // Final rotation of slip gear, causes puncher to punch PunchWait, // Delay before pull back to allow puncher to punch Detension, // Reverse motor to remove puncher tension Idle // Motor enters hold mode for band repair }; class Puncher { public: Motor motor = Motor(M_PUNCHER, E_MOTOR_GEARSET_18, false); Motor motor2 = Motor(M_PUNCHER_2, E_MOTOR_GEARSET_18, false); ADIButton limsw = ADIButton(SW_PUNCHER); PuncherState state = PuncherState::PullBack; // Pull Back First Thing! int lastUpdate = millis(); Controller controller; Puncher(Controller c); void handle(); void punch(); void waitUntilSettled(); // Wait until the puncher is ready for the next shot. void waitUntilShot(); // Wait until the puncher has finished the current shot and the robot is ready to move. }; class Arm { public: Motor motor = Motor(M_ARM, E_MOTOR_GEARSET_18, false); ADIButton limsw = ADIButton(SW_ARM); Controller controller; public: double position; // Arm target position in degrees bool manualMode = false; Arm(Controller c); void handle(); void drop(); // initial calibration, at stowed position void moveTo(double pos); }; class Flipper { public: Motor motor = Motor(M_FLIPPER, E_MOTOR_GEARSET_18, false); ADIButton limsw = ADIButton(SW_FLIPPER); Controller controller; double position; Flipper(Controller c); void handle(); void drop(); // initial calibration, at stowed position void moveTo(double pos); }; #endif
<gh_stars>1-10 #pragma once #include <pxl/types.h> #include <pxl/graphics/shader.h> #include <pxl/graphics/texture.h> #include <pxl/graphics/sampler.h> #include <memory> namespace pxl { class Material; using MaterialRef = std::shared_ptr<Material>; class Material { public: static MaterialRef create(const ShaderRef& shader); Material(const Material&) = delete; Material(Material&&) = delete; Material& operator=(const Material&) = delete; Material& operator=(Material&&) = delete; ~Material() = default; void setTexture(String name, const TextureRef& texture); void setTexture(int slot, const TextureRef& texture); void setSampler(String name, const TextureSampler& sampler); void setSampler(int slot, const TextureSampler& sampler); void setFloat(String name, const float* values, i64 length); ShaderRef shader() const { return _shader; } TextureRef texture(int slot, int index) const; TextureSampler sampler(int slot, int index) const; const float* floats() { return _floats.data(); } private: Material(const ShaderRef& shader); ShaderRef _shader; Vector<TextureRef> _textures; Vector<TextureSampler> _samplers; Vector<float> _floats; }; }
<filename>src/qt/include/QtCore/private/qthreadpool_p.h #include "../../../src/corelib/concurrent/qthreadpool_p.h"
<reponame>copslock/broadcom_cpri /*! \file mod.c * * Mirror-on-drop Module Emulator above SDKLT. * * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. * * Copyright 2007-2020 Broadcom Inc. All rights reserved. */ #include <bcm/types.h> #include <bcm/error.h> #include <bcm/cosq.h> #include <bcm_int/ltsw_dispatch.h> #include <bcm_int/ltsw/mod.h> #include <bcm_int/ltsw/mbcm/mod.h> #include <bsl/bsl.h> #include <sal/sal_types.h> #include <sal/sal_mutex.h> #include <shr/shr_debug.h> /****************************************************************************** * Local definitions */ #define BSL_LOG_MODULE BSL_LS_BCM_COSQ /*! * \brief MOD information data structure. */ typedef struct mod_info_s { /*! Module is initialized. */ bool inited; /*! Module lock. */ sal_mutex_t mutex; } mod_info_t; /* * Static global variable to hold MOD info. */ static mod_info_t mod_info[BCM_MAX_NUM_UNITS] = {{0}}; /* MOD info. */ #define MOD_INFO(unit) \ (&mod_info[unit]) /* Check if MOD module is initialized. */ #define MOD_INIT_CHECK(unit) \ do { \ mod_info_t *mod = MOD_INFO(unit); \ if (mod->inited == false) { \ SHR_IF_ERR_VERBOSE_EXIT(SHR_E_INIT); \ } \ } while(0) /* Take MOD lock. */ #define MOD_LOCK(unit) \ sal_mutex_take(MOD_INFO(unit)->mutex, SAL_MUTEX_FOREVER) /* Give MOD lock. */ #define MOD_UNLOCK(unit) \ sal_mutex_give(MOD_INFO(unit)->mutex) /****************************************************************************** * Private functions */ /****************************************************************************** * Public functions */ int bcmi_ltsw_cosq_mod_detach(int unit) { bool locked = false; SHR_FUNC_ENTER(unit); /* If not initialized, return success. */ if (MOD_INFO(unit)->inited == false) { SHR_EXIT(); } MOD_LOCK(unit); locked = true; MOD_INFO(unit)->inited = false; SHR_IF_ERR_VERBOSE_EXIT (mbcm_ltsw_cosq_mod_detach(unit)); MOD_UNLOCK(unit); locked = false; if (MOD_INFO(unit)->mutex) { sal_mutex_destroy(MOD_INFO(unit)->mutex); MOD_INFO(unit)->mutex = NULL; } exit: if (locked) { MOD_UNLOCK(unit); } SHR_FUNC_EXIT(); } int bcmi_ltsw_cosq_mod_init(int unit) { SHR_FUNC_ENTER(unit); if (MOD_INFO(unit)->inited) { SHR_IF_ERR_VERBOSE_EXIT (bcmi_ltsw_cosq_mod_detach(unit)); } if (MOD_INFO(unit)->mutex == NULL) { MOD_INFO(unit)->mutex = sal_mutex_create("MOD mutex"); SHR_NULL_CHECK(MOD_INFO(unit)->mutex, SHR_E_MEMORY); } SHR_IF_ERR_VERBOSE_EXIT (mbcm_ltsw_cosq_mod_init(unit)); MOD_INFO(unit)->inited = true; exit: SHR_FUNC_EXIT(); } int bcmi_ltsw_cosq_mod_dest_add(int unit, bcmi_ltsw_cosq_mod_dest_t *mod_dest) { int rv; SHR_FUNC_ENTER(unit); MOD_INIT_CHECK(unit); SHR_NULL_CHECK(mod_dest, SHR_E_PARAM); MOD_LOCK(unit); rv = mbcm_ltsw_cosq_mod_dest_add(unit, mod_dest); MOD_UNLOCK(unit); SHR_IF_ERR_VERBOSE_EXIT(rv); exit: SHR_FUNC_EXIT(); } int bcmi_ltsw_cosq_mod_dest_delete(int unit, bcmi_ltsw_cosq_mod_dest_t *mod_dest) { int rv; SHR_FUNC_ENTER(unit); MOD_INIT_CHECK(unit); MOD_LOCK(unit); rv = mbcm_ltsw_cosq_mod_dest_delete(unit, mod_dest); MOD_UNLOCK(unit); SHR_IF_ERR_VERBOSE_EXIT(rv); exit: SHR_FUNC_EXIT(); } int bcmi_ltsw_cosq_mod_dest_get(int unit, bcmi_ltsw_cosq_mod_dest_t *mod_dest) { int rv; SHR_FUNC_ENTER(unit); MOD_INIT_CHECK(unit); SHR_NULL_CHECK(mod_dest, SHR_E_PARAM); MOD_LOCK(unit); rv = mbcm_ltsw_cosq_mod_dest_get(unit, mod_dest); MOD_UNLOCK(unit); SHR_IF_ERR_VERBOSE_EXIT(rv); exit: SHR_FUNC_EXIT(); } int bcmi_ltsw_cosq_mod_instance_id_get(int unit, int *instance_id) { int rv; SHR_FUNC_ENTER(unit); MOD_INIT_CHECK(unit); SHR_NULL_CHECK(instance_id, SHR_E_PARAM); MOD_LOCK(unit); rv = mbcm_ltsw_cosq_mod_instance_id_get(unit, instance_id); MOD_UNLOCK(unit); SHR_IF_ERR_VERBOSE_EXIT(rv); exit: SHR_FUNC_EXIT(); } int bcm_ltsw_cosq_mod_control_set(int unit, bcm_cosq_mod_control_t *control) { int rv; SHR_FUNC_ENTER(unit); MOD_INIT_CHECK(unit); SHR_NULL_CHECK(control, SHR_E_PARAM); MOD_LOCK(unit); rv = mbcm_ltsw_cosq_mod_control_set(unit, control); MOD_UNLOCK(unit); SHR_IF_ERR_VERBOSE_EXIT(rv); exit: SHR_FUNC_EXIT(); } int bcm_ltsw_cosq_mod_control_get(int unit, bcm_cosq_mod_control_t *control) { int rv; SHR_FUNC_ENTER(unit); MOD_INIT_CHECK(unit); SHR_NULL_CHECK(control, SHR_E_PARAM); MOD_LOCK(unit); rv = mbcm_ltsw_cosq_mod_control_get(unit, control); MOD_UNLOCK(unit); SHR_IF_ERR_VERBOSE_EXIT(rv); exit: SHR_FUNC_EXIT(); } int bcm_ltsw_cosq_mod_profile_create(int unit, uint32_t options, int *profile_id) { int rv; SHR_FUNC_ENTER(unit); MOD_INIT_CHECK(unit); SHR_NULL_CHECK(profile_id, SHR_E_PARAM); MOD_LOCK(unit); rv = mbcm_ltsw_cosq_mod_profile_create(unit, options, profile_id); MOD_UNLOCK(unit); SHR_IF_ERR_VERBOSE_EXIT(rv); exit: SHR_FUNC_EXIT(); } int bcm_ltsw_cosq_mod_profile_destroy(int unit, int profile_id) { int rv; SHR_FUNC_ENTER(unit); MOD_INIT_CHECK(unit); MOD_LOCK(unit); rv = mbcm_ltsw_cosq_mod_profile_destroy(unit, profile_id); MOD_UNLOCK(unit); SHR_IF_ERR_VERBOSE_EXIT(rv); exit: SHR_FUNC_EXIT(); } int bcm_ltsw_cosq_mod_profile_set(int unit, int profile_id, bcm_cosq_mod_profile_t *profile) { int rv; SHR_FUNC_ENTER(unit); MOD_INIT_CHECK(unit); SHR_NULL_CHECK(profile, SHR_E_PARAM); MOD_LOCK(unit); rv = mbcm_ltsw_cosq_mod_profile_set(unit, profile_id, profile); MOD_UNLOCK(unit); SHR_IF_ERR_VERBOSE_EXIT(rv); exit: SHR_FUNC_EXIT(); } int bcm_ltsw_cosq_mod_profile_get(int unit, int profile_id, bcm_cosq_mod_profile_t *profile) { int rv; SHR_FUNC_ENTER(unit); MOD_INIT_CHECK(unit); SHR_NULL_CHECK(profile, SHR_E_PARAM); MOD_LOCK(unit); rv = mbcm_ltsw_cosq_mod_profile_get(unit, profile_id, profile); MOD_UNLOCK(unit); SHR_IF_ERR_VERBOSE_EXIT(rv); exit: SHR_FUNC_EXIT(); } int bcm_ltsw_cosq_mod_stat_set(int unit, bcm_cosq_object_id_t *id, bcm_cosq_mod_stat_t stat, uint64 value) { int rv; SHR_FUNC_ENTER(unit); MOD_INIT_CHECK(unit); SHR_NULL_CHECK(id, SHR_E_PARAM); MOD_LOCK(unit); rv = mbcm_ltsw_cosq_mod_stat_set(unit, id, stat, value); MOD_UNLOCK(unit); SHR_IF_ERR_VERBOSE_EXIT(rv); exit: SHR_FUNC_EXIT(); } int bcm_ltsw_cosq_mod_stat_get(int unit, bcm_cosq_object_id_t *id, bcm_cosq_mod_stat_t stat, uint64 *value) { int rv; SHR_FUNC_ENTER(unit); MOD_INIT_CHECK(unit); SHR_NULL_CHECK(id, SHR_E_PARAM); SHR_NULL_CHECK(value, SHR_E_PARAM); MOD_LOCK(unit); rv = mbcm_ltsw_cosq_mod_stat_get(unit, id, stat, value); MOD_UNLOCK(unit); SHR_IF_ERR_VERBOSE_EXIT(rv); exit: SHR_FUNC_EXIT(); }
<reponame>edawson/parliament2<filename>resources/home/dnanexus/root/include/TDocDirective.h // @(#)root/html:$Id$ // Author: <NAME> 2007-01-25 /************************************************************************* * Copyright (C) 1995-2007, <NAME> and <NAME>. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_TDocDirective #define ROOT_TDocDirective //////////////////////////////////////////////////////////////////////////// // // // TDocDirective // // // // Special treatment of comments, like HTML source, a macro, or latex. // // // //////////////////////////////////////////////////////////////////////////// #include "TNamed.h" class TClass; class TDocParser; class TDocOutput; class THtml; class TLatex; class TMacro; class TVirtualPad; class TDocDirective: public TNamed { protected: TDocParser* fDocParser; // parser invoking this handler THtml* fHtml; // parser's THtml object TDocOutput* fDocOutput; // parser invoking this handler TString fParameters; // parameters to the directive Int_t fCounter; // counter to generate unique names, -1 to ignore virtual void AddParameter(const TString& /*name*/, const char* /*value*/ = 0) {} TDocDirective() {} TDocDirective(const char* name): TNamed(name, ""), fDocParser(0), fHtml(0), fDocOutput(0), fCounter(-1) {}; virtual ~TDocDirective() {} const char* GetName() const { return TNamed::GetName(); } void GetName(TString& name) const; TDocParser* GetDocParser() const { return fDocParser; } TDocOutput* GetDocOutput() const { return fDocOutput; } THtml* GetHtml() const { return fHtml; } const char* GetOutputDir() const; void SetParser(TDocParser* parser); void SetParameters(const char* params); void SetTag(const char* tag) { SetTitle(tag); } void SetCounter(Int_t count) { fCounter = count; } virtual void DeleteOutputFiles(const char* ext) const; public: // get the tag ending this directive virtual const char* GetEndTag() const = 0; // add a line to the directive's text virtual void AddLine(const TSubString& line) = 0; // retrieve the result (replacement) of the directive; return false if invalid virtual Bool_t GetResult(TString& result) = 0; // Delete output for the parser's current class or module. virtual void DeleteOutput() const {} friend class TDocParser; ClassDef(TDocDirective, 0); // THtml directive handler }; class TDocHtmlDirective: public TDocDirective { private: TString fText; // HTML text to be kept Bool_t fVerbatim; // whether we are in a <pre></pre> block public: TDocHtmlDirective(): TDocDirective("HTML"), fVerbatim(kFALSE) {} virtual ~TDocHtmlDirective() {} virtual void AddLine(const TSubString& line); virtual const char* GetEndTag() const { return "end_html"; } virtual Bool_t GetResult(TString& result); ClassDef(TDocHtmlDirective, 0); // Handler for "Begin_Html"/"End_Html" for raw HTML in documentation comments }; class TDocMacroDirective: public TDocDirective { private: TMacro* fMacro; // macro to be executed Bool_t fNeedGraphics; // if set, we cannot switch to batch mode Bool_t fShowSource; // whether a source tab should be created Bool_t fIsFilename; // whether the directive is a failename to be executed virtual void AddParameter(const TString& name, const char* value = 0); TString CreateSubprocessInputFile(); public: TDocMacroDirective(): TDocDirective("MACRO"), fMacro(0), fNeedGraphics(kFALSE), fShowSource(kFALSE), fIsFilename(kTRUE) {}; virtual ~TDocMacroDirective(); virtual void AddLine(const TSubString& line); virtual const char* GetEndTag() const { return "end_macro"; } virtual Bool_t GetResult(TString& result); // Delete output for the parser's current class or module. virtual void DeleteOutput() const { DeleteOutputFiles(".gif"); } static void SubProcess(const TString& what, const TString& out); ClassDef(TDocMacroDirective, 0); // Handler for "Begin_Macro"/"End_Macro" for code that is executed and that can generate an image for documentation }; class TDocLatexDirective: public TDocDirective { protected: TMacro* fLatex; // collection of lines Int_t fFontSize; // fontsize for current latex block, in pixels TString fSeparator; // column separator, often "=" Bool_t fSepIsRegexp; // whether fSeparator is a regexp expression TString fAlignment; // column alignment: 'l' for justify left, 'c' for center, 'r' for right TVirtualPad* fBBCanvas; // canvas for bounding box determination virtual void CreateLatex(const char* filename); virtual void AddParameter(const TString& name, const char* value = 0); virtual void GetBoundingBox(TLatex& latex, const char* text, Float_t& width, Float_t& height); public: TDocLatexDirective(): TDocDirective("LATEX"), fLatex(0), fFontSize(16), fSepIsRegexp(kFALSE), fBBCanvas(0) {}; virtual ~TDocLatexDirective(); virtual void AddLine(const TSubString& line); virtual const char* GetEndTag() const {return "end_latex";} const char* GetAlignment() const {return fAlignment;} const char* GetSeparator() const {return fSeparator;} Bool_t SeparatorIsRegexp() const {return fSepIsRegexp;} Int_t GetFontSize() const {return fFontSize;} TList* GetListOfLines() const; virtual Bool_t GetResult(TString& result); // Delete output for the parser's current class or module. virtual void DeleteOutput() const { DeleteOutputFiles(".gif"); } ClassDef(TDocLatexDirective, 0); // Handler for "Begin_Latex"/"End_Latex" to generate an image from latex }; #endif // ROOT_TDocDirective
#include "receipter.h" #include <assert.h> #include <ctype.h> #define MAX_LENGTH (4096U) #define MAX_ITEM_COUNT (10U) #define MAX_MESSAGE_LENGTH (76U) #define MAX_ITEM_NAME_LENGTH (26U) #define LINE_LENGTH (50U) static size_t s_receipt_count = 0; static size_t s_item_count = 0; static char s_item_name_array[MAX_ITEM_COUNT][MAX_ITEM_NAME_LENGTH]; static double s_item_price_array[MAX_ITEM_COUNT] = { 0.0, }; static char s_message[MAX_MESSAGE_LENGTH] = { 0, }; static double s_tip = 0.0; static size_t s_flag_item_setted = FALSE; static size_t s_flag_message_setted = FALSE; static size_t s_flag_tip_setted = FALSE; int add_item(const char* name, double price) { if (name == NULL) { return FALSE; } if ((price < 0.0) || (price > 999.99)) { return FALSE; } if (s_item_count >= MAX_ITEM_COUNT) { return FALSE; } strncpy(s_item_name_array[s_item_count], name, (MAX_ITEM_NAME_LENGTH - 1)); s_item_name_array[s_item_count][MAX_ITEM_NAME_LENGTH - 1] = '\0'; s_item_price_array[s_item_count] = price; s_item_count++; s_flag_item_setted = TRUE; return TRUE; } void set_tip(double tip) { if (tip <= 0.0) { return; } if (s_flag_item_setted == FALSE) { return; } assert(tip <= 999.99); s_tip = tip; s_flag_tip_setted = TRUE; } void set_message(const char* message) { size_t msg_length = 0; size_t msg_length_remain = 0; if (message == NULL) { return; } if (s_flag_item_setted == FALSE) { return; } if (strlen(s_message) >= MAX_MESSAGE_LENGTH - 1) { return; } if (s_flag_message_setted == FALSE) { strncpy(s_message, message, (MAX_MESSAGE_LENGTH - 1)); s_message[MAX_MESSAGE_LENGTH - 1] = '\0'; /* MSG DEBUG */ fprintf(stdout, "set_message() -> msg = %s\n", s_message); fprintf(stdout, "set_message() -> msg_length = %d\n", strlen(s_message)); */ } else { msg_length = strlen(s_message); msg_length_remain = MAX_MESSAGE_LENGTH - msg_length - 1; if (msg_length_remain == 0) { return; } strncat(s_message, message, msg_length_remain); s_message[MAX_MESSAGE_LENGTH - 1] = '\0'; /* ADD MSG DEBUG */ fprintf(stdout, "set_message() -> add msg = %s\n", s_message); fprintf(stdout, "set_message() -> add msg_length = %d\n", strlen(s_message)); } s_flag_message_setted = TRUE; } int print_receipt(const char* filename, time_t timestamp) { FILE* receipt_file; struct tm* time_set; char buffer[MAX_LENGTH] = { 0, }; size_t item_count = 0; size_t item_name_count = 0; size_t message_length = 0; size_t message_count = 0; double price = 0.0; double price_sum = 0.0; double tax = 0.0; double total_price = 0.0; if (filename == NULL) { return FALSE; } if (s_flag_item_setted == FALSE) { return FALSE; } if (s_item_count == 0) { return FALSE; } assert(s_receipt_count <= 99999); /* open receipt file */ receipt_file = fopen(filename, "w+"); /* get current local time */ time(&timestamp); time_set = gmtime(&timestamp); /* print default info */ sprintf(buffer, "Charles' Seafood"); fprintf(receipt_file, "%s\n", buffer); sprintf(buffer, "--------------------------------------------------"); fprintf(receipt_file, "%s\n", buffer); /* print time info */ sprintf(buffer, "%04d-%02d-%02d %02d:%02d:%02d", time_set->tm_year + 1900, time_set->tm_mon + 1, time_set->tm_mday, time_set->tm_hour, time_set->tm_min, time_set->tm_sec); fprintf(receipt_file, "%s", buffer); sprintf(buffer, "%26s%05d", " ", s_receipt_count); fprintf(receipt_file, "%s\n", buffer); sprintf(buffer, "--------------------------------------------------"); fprintf(receipt_file, "%s\n", buffer); /* print item info */ for (item_count = 0; item_count < s_item_count; item_count++) { sprintf(buffer, "%33s", s_item_name_array[item_count]); fprintf(receipt_file, "%s", buffer); price = s_item_price_array[item_count]; price_sum += price; sprintf(buffer, "%17.2lf", price); fprintf(receipt_file, "%s\n\n", buffer); } /* print calc info */ tax = price_sum * 0.05; total_price = price_sum + s_tip + tax; sprintf(buffer, "%33s", "Subtotal"); fprintf(receipt_file, "%s", buffer); sprintf(buffer, "%17.2lf", price_sum); fprintf(receipt_file, "%s\n", buffer); if (s_flag_tip_setted == TRUE) { sprintf(buffer, "%33s", "Tip"); fprintf(receipt_file, "%s", buffer); sprintf(buffer, "%17.2lf", s_tip); fprintf(receipt_file, "%s\n", buffer); } sprintf(buffer, "%33s", "Tax"); fprintf(receipt_file, "%s", buffer); sprintf(buffer, "%17.2lf", tax); fprintf(receipt_file, "%s\n", buffer); sprintf(buffer, "%33s", "Total"); fprintf(receipt_file, "%s", buffer); sprintf(buffer, "%17.2lf", total_price); fprintf(receipt_file, "%s\n", buffer); /* print message info */ if (s_flag_message_setted == TRUE) { fputc('\n', receipt_file); message_length = strlen(s_message); if (message_length > 50) { for (message_count = 0; message_count < LINE_LENGTH; message_count++) { fputc(s_message[message_count], receipt_file); } fputc('\n', receipt_file); for (message_count = LINE_LENGTH; message_count < message_length; message_count++) { assert(message_count < MAX_MESSAGE_LENGTH); fputc(s_message[message_count], receipt_file); } fputc('\n', receipt_file); } else { for (message_count = 0; message_count < message_length; message_count++) { fputc(s_message[message_count], receipt_file); } fputc('\n', receipt_file); } } else { fputc('\n', receipt_file); } /* print final info */ sprintf(buffer, "=================================================="); fprintf(receipt_file, "%s\n", buffer); sprintf(buffer, "%50s", "Tax#-51234"); fprintf(receipt_file, "%s", buffer); /* initialize for next receipt */ s_receipt_count++; for (item_count = 0; item_count < MAX_ITEM_COUNT; item_count++) { for (item_name_count = 0; item_name_count < MAX_ITEM_NAME_LENGTH; item_name_count++) { s_item_name_array[item_count][item_name_count] = 0; } s_item_price_array[item_count] = 0.0; } s_flag_item_setted = FALSE; s_item_count = 0; if (s_flag_message_setted == TRUE) { for (message_count = 0; message_count < MAX_MESSAGE_LENGTH; message_count++) { s_message[message_count] = 0; } s_flag_message_setted = FALSE; } if (s_flag_tip_setted == TRUE) { s_tip = 0.0; s_flag_tip_setted = FALSE; } fclose(receipt_file); return TRUE; }
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/SafariShared.framework/SafariShared */ @interface WBSRecentlyUsedAutoFillSet : NSObject { NSArray * _fillMatches; NSString * _label; NSArray * _skipMatches; } @property (nonatomic, readonly, copy) NSArray *fillMatches; @property (nonatomic, readonly, copy) NSString *label; @property (nonatomic, readonly, copy) NSArray *skipMatches; - (void).cxx_destruct; - (id)fillMatches; - (id)initWithFillMatches:(id)arg1 skipMatches:(id)arg2 label:(id)arg3; - (id)label; - (id)skipMatches; @end
/* * File I/O extension to the State Threads Library. */ /* * The contents of this file are subject to the Mozilla Public * License Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * The Original Code is the file I/O extension to the State Threads Library. * * The Initial Developer of the Original Code is Jeff * <<EMAIL>>. Portions created by the Initial * Developer are Copyright (C) 2002 the Initial Developer. All Rights * Reserved. * * Contributor(s): (none) * * Alternatively, the contents of this file may be used under the * terms of the GNU General Public License Version 2 or later (the * "GPL"), in which case the provisions of the GPL are applicable * instead of those above. If you wish to allow use of your * version of this file only under the terms of the GPL and not to * allow others to use your version of this file under the MPL, * indicate your decision by deleting the provisions above and * replace them with the notice and other provisions required by * the GPL. If you do not delete the provisions above, a recipient * may use your version of this file under either the MPL or the * GPL. */ #include <stdlib.h> #include "stx_fileio.h" #define STX_FILEIO_SIGNUM SIGUSR2 typedef struct { st_netfd_t data_fd; st_netfd_t control_fd; pid_t pid; } fileio_data_t; #define FILEREADER_MAX_READ 1024 typedef struct { off_t offset; ssize_t nbytes; } file_reader_cb_t; /** * Fork a process to read a file and return its pid. Receives * offset/length commands from control stream and sends corresponding data * to out stream. A zero length on the control stream signals an end. * * @param fd stream from which to read * @param control_out receives the file descriptor to which control commands can be sent * @param fd_out receives the file descriptor from which the output of the command can be read. * @return PID of the process created to execute the command */ pid_t file_reader(int fd, int *fd_control, int *fd_out) { pid_t pid; int control_pipe[2], out_pipe[2]; if (pipe(control_pipe) < 0 || pipe(out_pipe) < 0) { return (pid_t)-1; } pid = fork(); if (pid == (pid_t) -1) { close(control_pipe[0]); close(control_pipe[1]); close(out_pipe[0]); close(out_pipe[1]); return pid; } else if (pid == (pid_t) 0) { // child off_t pos = 0; file_reader_cb_t cb; char buf[FILEREADER_MAX_READ]; if (fd == -1) { _exit(EXIT_FAILURE); } while (sizeof(cb) == read(control_pipe[0], &cb, sizeof(cb))) { ssize_t nb; if (0 >= cb.nbytes) { goto clean_exit; } if (pos != cb.offset) { pos = lseek(fd, cb.offset, SEEK_SET); if (pos == (off_t)-1) { break; } } nb = read(fd, buf, cb.nbytes); if (nb == (ssize_t)-1) { break; } pos += nb; write(out_pipe[1], (char *)&nb, sizeof(nb)); write(out_pipe[1], buf, nb); } perror("ERROR: file_reader: "); clean_exit: close(control_pipe[0]); close(control_pipe[1]); close(out_pipe[0]); close(out_pipe[1]); _exit(EXIT_SUCCESS); } // parent close(out_pipe[1]); close(control_pipe[0]); *fd_out = out_pipe[0]; *fd_control = control_pipe[1]; return pid; } /** * fileio_data_t destructor callback */ static void fileio_data_destructor(void *dat_in) { if (dat_in) { fileio_data_t *dat = (fileio_data_t *)dat_in; file_reader_cb_t cb; cb.offset = 0; cb.nbytes = 0; st_write(dat->control_fd, (char *)&cb, sizeof(cb), ST_UTIME_NO_TIMEOUT); waitpid(dat->pid, NULL, 0); st_netfd_close(dat->control_fd); st_netfd_close(dat->data_fd); free(dat_in); } } /** * Retrieve fileio_data_t struct from an st descriptor. Create and store * a new one if needed. */ static fileio_data_t *get_fileio_data(st_netfd_t fd) { fileio_data_t *dat = (fileio_data_t *)st_netfd_getspecific(fd); if (!dat) { int fd_control, fd_out; pid_t pid = file_reader(st_netfd_fileno(fd), &fd_control, &fd_out); if (pid != (pid_t)-1) { dat = (fileio_data_t *)calloc(1, sizeof(fileio_data_t)); dat->control_fd = st_netfd_open(fd_control); dat->data_fd = st_netfd_open(fd_out); dat->pid = pid; st_netfd_setspecific(fd, dat, fileio_data_destructor); } } return dat; } /** * Read data from the specified section of a file. Uses a forked * file_reader process to do the actual reading so as to avoid causing all * State Threads to block. * * @param fd must refer to a seekable file. * @param offset absolute offset within the file * @param buf output buffer * @param nbytes size of the output buffer * @param timeout */ ssize_t stx_file_read(st_netfd_t fd, off_t offset, void *buf, size_t nbytes, st_utime_t timeout) { fileio_data_t *dat = get_fileio_data(fd); if (dat) { file_reader_cb_t cb; ssize_t ret = (ssize_t)-1; cb.offset = offset; cb.nbytes = nbytes; st_write(dat->control_fd, (char *)&cb, sizeof(cb), timeout); if (sizeof(ret) == st_read(dat->data_fd, (char *)&ret, sizeof(ret), timeout) && 0 < ret && ret <= nbytes) { return st_read(dat->data_fd, buf, ret, timeout); } else { return ret; } } return (ssize_t)-1; }
<filename>Sources/UISNPhotos.h // // UISNPhotos.h // SNImagePicker // // Created by luowei on 2018/9/19. // Copyright © 2018年 luowei. All rights reserved. // #import <UIKit/UIKit.h> #import <Photos/Photos.h> #import "SNCommon.h" @protocol UISNPhotosDelegate; @interface UISNPhotos : UIViewController @property(nonatomic,strong)PHAssetCollection *collection; @property(nonatomic,weak)id<UISNPhotosDelegate> delegate; @property(nonatomic,assign)NSInteger maxCount;//最大数量 @property(nonatomic,assign)NSInteger mediaType;//图片、视频、录音 @property(nonatomic,assign)NSInteger maxSeconds;//最大时长 (秒) @end @protocol UISNPhotosDelegate<NSObject> - (void)selectImage:(UISNPhotos*)imagePicker with:(NSArray*)results withType:(NSInteger)type; @end
<reponame>tomzhang/graphengine<gh_stars>0 /** * Copyright 2019-2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef GE_OPSKERNEL_MANAGER_OPS_KERNEL_MANAGER_H_ #define GE_OPSKERNEL_MANAGER_OPS_KERNEL_MANAGER_H_ #include <map> #include <memory> #include <string> #include <vector> #include <mutex> #include "common/debug/log.h" #include "common/ge/plugin_manager.h" #include "common/ge/op_tiling_manager.h" #include "common/ge_inner_error_codes.h" #include "common/opskernel/ops_kernel_info_store.h" #include "common/optimizer/graph_optimizer.h" #include "graph/optimize/graph_optimize.h" #include "framework/common/ge_inner_error_codes.h" #include "ge/ge_api_types.h" #include "runtime/base.h" using std::map; using std::string; using std::vector; namespace ge { using OpsKernelInfoStorePtr = std::shared_ptr<OpsKernelInfoStore>; class OpsKernelManager { public: friend class GELib; // get opsKernelInfo by type const vector<OpInfo> &GetOpsKernelInfo(const string &op_type); // get all opsKernelInfo const map<string, vector<OpInfo>> &GetAllOpsKernelInfo() const; // get opsKernelInfoStore by name OpsKernelInfoStorePtr GetOpsKernelInfoStore(const std::string &name) const; // get all opsKernelInfoStore const map<string, OpsKernelInfoStorePtr> &GetAllOpsKernelInfoStores() const; // get all graph_optimizer const map<string, GraphOptimizerPtr> &GetAllGraphOptimizerObjs() const; // get all graph_optimizer by priority const vector<pair<string, GraphOptimizerPtr>> &GetAllGraphOptimizerObjsByPriority() const; // get subgraphOptimizer by engine name void GetGraphOptimizerByEngine(const std::string &engine_name, vector<GraphOptimizerPtr> &graph_optimizer); // get enableFeFlag bool GetEnableFeFlag() const; // get enableAICPUFlag bool GetEnableAICPUFlag() const; // get enablePluginFlag bool GetEnablePluginFlag() const; private: OpsKernelManager(); ~OpsKernelManager(); // opsKernelManager initialize, load all opsKernelInfoStore and graph_optimizer Status Initialize(const map<string, string> &options); // opsKernelManager finalize, unload all opsKernelInfoStore and graph_optimizer Status Finalize(); Status InitOpKernelInfoStores(const map<string, string> &options); Status CheckPluginPtr() const; void GetExternalEnginePath(std::string &path, const std::map<string, string> &options); void InitOpsKernelInfo(); Status InitGraphOptimzers(const map<string, string> &options); Status InitPluginOptions(const map<string, string> &options); Status ParsePluginOptions(const map<string, string> &options, const string &plugin_name, bool &enable_flag); Status LoadGEGraphOptimizer(map<string, GraphOptimizerPtr> &graphOptimizer); Status InitGraphOptimizerPriority(); // Finalize other ops kernel resource Status FinalizeOpsKernel(); PluginManager plugin_manager_; OpTilingManager op_tiling_manager_; // opsKernelInfoStore map<string, OpsKernelInfoStorePtr> ops_kernel_store_{}; // graph_optimizer map<string, GraphOptimizerPtr> graph_optimizers_{}; // ordered graph_optimzer vector<pair<string, GraphOptimizerPtr>> graph_optimizers_by_priority_{}; // opsKernelInfo map<string, vector<OpInfo>> ops_kernel_info_{}; map<string, string> initialize_{}; vector<OpInfo> empty_op_info_{}; bool init_flag_; bool enable_fe_flag_ = false; bool enable_aicpu_flag_ = false; }; } // namespace ge #endif // GE_OPSKERNEL_MANAGER_OPS_KERNEL_MANAGER_H_
<filename>test/test.h #ifndef _TEST_H_ #define _TEST_H_ #include <stdio.h> #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) #define AT __FILE__ ":" TOSTRING(__LINE__) ": " #define DEBUG( ... ) { printf( AT "\033[1;41m" __VA_ARGS__); printf("\033[0m\n"); } #define ASSERT( T, ... ) if ( !(T) ) { DEBUG( __VA_ARGS__ ); exit(__LINE__); } #define PASS printf( __FILE__ ": \033[1;42mpassed\033[0m\n" ) #endif
/* * The lack of #pragma once is intentional, * as the user might need to include this header multiple times. */ #include <util/system/platform.h> #if defined(_win_) #undef GetFreeSpace #undef LoadImage #undef GetMessage #undef SendMessage #undef DeleteFile #undef GetUserName #undef CreateMutex #undef GetObject #undef GetGeoInfo #undef GetClassName #undef GetKValue #undef StartDoc #undef UpdateResource #undef GetNameInfo #undef GetProp #undef SetProp #undef RemoveProp // FIXME thegeorg@: undefining CONST breaks too many projects. // #undef CONST #undef DEFAULT_QUALITY #undef ERROR #undef IGNORE #undef OPTIONAL #undef TRANSPARENT #undef LANG_LAO #undef LANG_YI #undef CM_NONE #endif